예제 #1
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.")
예제 #2
0
def cli(env, volume_id, capacity, tier, upgrade):
    """Order snapshot space for a block storage volume."""
    block_manager = SoftLayer.BlockStorageManager(env.client)

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

    try:
        order = block_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.")
예제 #3
0
def cli(env, volume_id, snapshot_schedule, location, tier, os_type):
    """Order a block storage replica volume."""
    block_manager = SoftLayer.BlockStorageManager(env.client)

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

    try:
        order = block_manager.order_replicant_volume(
            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(
            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.")
예제 #4
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."
        )
예제 #5
0
def cli(env, access_id):
    """List block storage assigned subnets for the given host id.

    access_id is the host_id obtained by: slcli block access-list <volume_id>
    """

    try:
        block_manager = SoftLayer.BlockStorageManager(env.client)
        resolved_id = helpers.resolve_id(block_manager.resolve_ids, access_id,
                                         'Volume Id')
        subnets = block_manager.get_subnets_in_acl(resolved_id)

        table = formatting.Table(COLUMNS)
        for subnet in subnets:
            row = [
                "{0}".format(subnet['id']), "{0}".format(subnet['createDate']),
                "{0}".format(subnet['networkIdentifier']),
                "{0}".format(subnet['cidr'])
            ]
            table.add_row(row)

        env.fout(table)

    except SoftLayer.SoftLayerAPIError as ex:
        message = "Unable to list assigned subnets for access-id: {}.\nReason: {}".format(
            access_id, ex.faultString)
        click.echo(message)
예제 #6
0
def cli(env, volume_id, schedule_type, retention_count, minute, hour,
        day_of_week):
    """Enables snapshots for a given volume on the specified schedule"""
    block_manager = SoftLayer.BlockStorageManager(env.client)

    valid_schedule_types = {'INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY'}
    valid_days = {
        'SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY',
        'SATURDAY'
    }

    if schedule_type not in valid_schedule_types:
        raise exceptions.CLIAbort(
            '--schedule-type must be INTERVAL, HOURLY, DAILY,' +
            'or WEEKLY, not ' + schedule_type)

    if schedule_type == 'INTERVAL' and (minute < 30 or minute > 59):
        raise exceptions.CLIAbort('--minute value must be between 30 and 59')
    if minute < 0 or minute > 59:
        raise exceptions.CLIAbort('--minute value must be between 0 and 59')
    if hour < 0 or hour > 23:
        raise exceptions.CLIAbort('--hour value must be between 0 and 23')
    if day_of_week not in valid_days:
        raise exceptions.CLIAbort(
            '--day_of_week value must be a valid day (ex: SUNDAY)')

    enabled = block_manager.enable_snapshots(volume_id, schedule_type,
                                             retention_count, minute, hour,
                                             day_of_week)

    if enabled:
        click.echo('%s snapshots have been enabled for volume %s' %
                   (schedule_type, volume_id))
예제 #7
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.")
예제 #8
0
def cli(env, access_id, subnet_id):
    """Assign block storage subnets to the given host id.

    access_id is the host_id obtained by: slcli block access-list <volume_id>

    SoftLayer_Account::iscsiisolationdisabled must be False to use this command
    """
    try:
        subnet_ids = list(subnet_id)
        block_manager = SoftLayer.BlockStorageManager(env.client)
        assigned_subnets = block_manager.assign_subnets_to_acl(
            access_id, subnet_ids)

        for subnet in assigned_subnets:
            message = "Successfully assigned subnet id: {} to allowed host id: {}".format(
                subnet, access_id)
            click.echo(message)

        failed_to_assign_subnets = list(
            set(subnet_ids) - set(assigned_subnets))
        for subnet in failed_to_assign_subnets:
            message = "Failed to assign subnet id: {} to allowed host id: {}".format(
                subnet, access_id)
            click.echo(message)

    except SoftLayer.SoftLayerAPIError as ex:
        message = "Unable to assign subnets.\nReason: {}".format(
            ex.faultString)
        click.echo(message)
예제 #9
0
def cli(env, snapshot_id):
    """Deletes a snapshot on a given volume"""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    deleted = block_manager.delete_snapshot(snapshot_id)

    if deleted:
        click.echo('Snapshot %s deleted' % snapshot_id)
예제 #10
0
 def __init__(self):
     try:
         self._BSmgr = SoftLayer.BlockStorageManager(SoftLayer.Client())
         self._Nmgr = SoftLayer.managers.network.NetworkManager(
             SoftLayer.Client())
     except EnvironmentError:
         raise Exception("Cannot initialize SoftLayer Client")
예제 #11
0
def cli(env, volume_id, snapshot_id):
    """Restore block volume using a given snapshot"""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    success = block_manager.restore_from_snapshot(volume_id, snapshot_id)

    if success:
        click.echo('Block volume %s is being restored using snapshot %s' %
                   (volume_id, snapshot_id))
예제 #12
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.")
예제 #13
0
def cli(env, volume_id, reason, immediate):
    """Cancel an existing block storage volume."""

    block_storage_manager = SoftLayer.BlockStorageManager(env.client)

    if not (env.skip_confirmations or formatting.no_going_back(volume_id)):
        raise exceptions.CLIAbort('Aborted')

    block_storage_manager.cancel_block_volume(volume_id, reason, immediate)
예제 #14
0
def cli(env, volume_id):
    """Failback a block volume from the given replicant volume."""
    block_storage_manager = SoftLayer.BlockStorageManager(env.client)

    success = block_storage_manager.failback_from_replicant(volume_id)

    if success:
        click.echo("Failback from replicant is now in progress.")
    else:
        click.echo("Failback operation could not be initiated.")
예제 #15
0
def cli(env, volume_id, enable):
    """Enables/Disables snapshot space usage threshold warning for a given volume"""
    block_manager = SoftLayer.BlockStorageManager(env.client)

    status = block_manager.set_volume_snapshot_notification(volume_id, enable)

    if status:
        click.echo(
            'Snapshots space usage threshold warning notification has bee set to %s for volume %s'
            % (enable, volume_id))
예제 #16
0
def cli(env, volume_id, notes):
    """Creates a snapshot on a given volume"""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    snapshot = block_manager.create_snapshot(volume_id, notes=notes)

    if 'id' in snapshot:
        click.echo('New snapshot created with id: %s' % snapshot['id'])
    else:
        click.echo('Error occurred while creating snapshot.\n'
                   'Ensure volume is not failed over or in another '
                   'state which prevents taking snapshots.')
예제 #17
0
def cli(env, volume_id, replicant_id):
    """Failover a block volume to the given replicant volume."""
    block_storage_manager = SoftLayer.BlockStorageManager(env.client)

    success = block_storage_manager.failover_to_replicant(
        volume_id, replicant_id)

    if success:
        click.echo("Failover to replicant is now in progress.")
    else:
        click.echo("Failover operation could not be initiated.")
예제 #18
0
def cli(env, sortby, columns, datacenter, username, storage_type, order):
    """List block storage."""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    block_volumes = block_manager.list_block_volumes(datacenter=datacenter,
                                                     username=username,
                                                     storage_type=storage_type,
                                                     order=order,
                                                     mask=columns.mask())

    table = storage_utils.build_output_table(env, block_volumes, columns,
                                             sortby)
    env.fout(table)
예제 #19
0
def cli(env, host_id):
    """Retrieves a list of subents that have been assigned to a host."""
    block_manager = SoftLayer.BlockStorageManager(env.client)

    #Add a check in case the subnet_id_list is empty

    result = block_manager.get_subnets_in_acl(host_id)

    env.fout(result)

    # If no exception was raised, the command succeeded
    click.echo('Retrieving subnets for host ID: %s' % host_id)
예제 #20
0
def cli(env, volume_id):
    """Get snapshots space usage threshold warning flag setting for a given volume"""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    enabled = block_manager.get_volume_snapshot_notification_status(volume_id)

    if enabled == 0:
        click.echo(
            "Disabled: Snapshots space usage threshold is disabled for volume {}"
            .format(volume_id))
    else:
        click.echo(
            "Enabled: Snapshots space usage threshold is enabled for volume {}"
            .format(volume_id))
예제 #21
0
def cli(env, volume_id, schedule_type):
    """Disables snapshots on the specified schedule for a given volume"""

    if (schedule_type not in ['INTERVAL', 'HOURLY', 'DAILY', 'WEEKLY']):
        raise exceptions.CLIAbort(
            '--schedule-type must be INTERVAL, HOURLY, DAILY, or WEEKLY')

    block_manager = SoftLayer.BlockStorageManager(env.client)
    disabled = block_manager.disable_snapshots(volume_id, schedule_type)

    if disabled:
        click.echo('%s snapshots have been disabled for volume %s'
                   % (schedule_type, volume_id))
예제 #22
0
def cli(env, volume_id):
    """Lists snapshot schedules for a given volume"""

    block_manager = SoftLayer.BlockStorageManager(env.client)

    snapshot_schedules = block_manager.list_volume_schedules(volume_id)

    table = formatting.Table([
        'id', 'active', 'type', 'replication', 'date_created', 'minute',
        'hour', 'day', 'week', 'day_of_week', 'date_of_month', 'month_of_year',
        'maximum_snapshots'
    ])

    for schedule in snapshot_schedules:

        if 'REPLICATION' in schedule['type']['keyname']:
            replication = '*'
        else:
            replication = formatting.blank()

        block_schedule_type = schedule['type']['keyname'].replace(
            'REPLICATION_', '')
        block_schedule_type = block_schedule_type.replace('SNAPSHOT_', '')

        property_list = [
            'MINUTE', 'HOUR', 'DAY', 'WEEK', 'DAY_OF_WEEK', 'DAY_OF_MONTH',
            'MONTH_OF_YEAR', 'SNAPSHOT_LIMIT'
        ]

        schedule_properties = []
        for prop_key in property_list:
            item = formatting.blank()
            for schedule_property in schedule.get('properties', []):
                if schedule_property['type']['keyname'] == prop_key:
                    if schedule_property['value'] == '-1':
                        item = '*'
                    else:
                        item = schedule_property['value']
                    break
            schedule_properties.append(item)

        table_row = [
            schedule['id'], '*' if schedule.get('active', '') else '',
            block_schedule_type, replication,
            schedule.get('createDate', '')
        ]
        table_row.extend(schedule_properties)

        table.add_row(table_row)

    env.fout(table)
예제 #23
0
def cli(env, sortby):
    """List number of block storage volumes limit per datacenter."""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    block_volumes = block_manager.list_block_volume_limit()

    table = formatting.KeyValueTable(DEFAULT_COLUMNS)
    table.sortby = sortby
    for volume in block_volumes:
        datacenter_name = volume['datacenterName']
        maximum_available_count = volume['maximumAvailableCount']
        provisioned_count = volume['provisionedCount']
        table.add_row(
            [datacenter_name, maximum_available_count, provisioned_count])
    env.fout(table)
예제 #24
0
def cli(env, volume_id, sortby, columns):
    """List block storage snapshots."""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    snapshots = block_manager.get_block_volume_snapshot_list(
        volume_id, mask=columns.mask())

    table = formatting.Table(columns.columns)
    table.sortby = sortby

    for snapshot in snapshots:
        table.add_row(
            [value or formatting.blank() for value in columns.row(snapshot)])

    env.fout(table)
예제 #25
0
def cli(env, volume_id, note):
    """Set note for an existing block storage volume."""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    block_volume_id = helpers.resolve_id(block_manager.resolve_ids, volume_id,
                                         'Block Volume')

    result = block_manager.volume_set_note(block_volume_id, note)

    if result:
        click.echo("Set note successfully!")

    else:
        click.echo(
            "Note could not be set! Please verify your options and try again.")
예제 #26
0
def cli(env, access_id, password):
    """Changes a password for a volume's access.

    access id is the allowed_host_id from slcli block access-list
    """

    block_manager = SoftLayer.BlockStorageManager(env.client)

    result = block_manager.set_credential_password(access_id=access_id,
                                                   password=password)

    if result:
        click.echo('Password updated for %s' % access_id)
    else:
        click.echo('FAILED updating password for %s' % access_id)
예제 #27
0
def cli(env, sortby, columns, datacenter, username, storage_type):
    """List block storage."""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    block_volumes = block_manager.list_block_volumes(datacenter=datacenter,
                                                     username=username,
                                                     storage_type=storage_type,
                                                     mask=columns.mask())

    table = formatting.Table(columns.columns)
    table.sortby = sortby

    for block_volume in block_volumes:
        table.add_row([value or formatting.blank()
                       for value in columns.row(block_volume)])

    env.fout(table)
예제 #28
0
def cli(env, host_id, subnet_id):
    """Removes hosts to access a given volume"""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    subnet_id_list = list(subnet_id)

    # click.echo('Test to spit out %s' % subnet_id_list[0])

    # click.echo('\n Test to spit out 2 %s' % type(subnet_id))

    #print out the subnet input to find out what's happening here :O
    #Add a check in case the subnet_id_list is empty

    block_manager.remove_subnets_from_acl(host_id, subnet_id_list)

    # If no exception was raised, the command succeeded
    click.echo('Desired subnets removed from host with id: %s' % host_id)
예제 #29
0
def cli(env, volume_id, hardware_id, virtual_id, ip_address_id, ip_address):
    """Revokes authorization for hosts accessing a given volume"""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    ip_address_id_list = list(ip_address_id)

    # Convert actual IP Addresses to their SoftLayer ids
    if ip_address is not None:
        network_manager = SoftLayer.NetworkManager(env.client)
        for ip_address_value in ip_address:
            ip_address_object = network_manager.ip_lookup(ip_address_value)
            ip_address_id_list.append(ip_address_object['id'])

    block_manager.deauthorize_host_to_volume(volume_id, hardware_id,
                                             virtual_id, ip_address_id_list)

    # If no exception was raised, the command succeeded
    click.echo('Access to %s was revoked for the specified hosts' % volume_id)
예제 #30
0
def cli(env, volume_id):
    """Display details for a specified volume."""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    block_volume = block_manager.get_block_volume_details(volume_id)
    block_volume = utils.NestedDict(block_volume)

    table = formatting.KeyValueTable(['Name', 'Value'])
    table.align['Name'] = 'r'
    table.align['Value'] = 'l'

    storage_type = block_volume['storageType']['keyName'].split('_').pop(0)
    table.add_row(['ID', block_volume['id']])
    table.add_row(['Username', block_volume['username']])
    table.add_row(['Type', storage_type])
    table.add_row(['Capacity (GB)', "%iGB" % block_volume['capacityGb']])
    table.add_row(['LUN Id', "%s" % block_volume['lunId']])

    if block_volume.get('iops'):
        table.add_row(['IOPs', block_volume['iops']])

    if block_volume.get('storageTierLevel'):
        table.add_row([
            'Endurance Tier',
            block_volume['storageTierLevel']['description'],
        ])

    table.add_row([
        'Data Center',
        block_volume['serviceResource']['datacenter']['name'],
    ])
    table.add_row([
        'Target IP',
        block_volume['serviceResourceBackendIpAddress'],
    ])

    if block_volume['snapshotCapacityGb']:
        table.add_row([
            'Snapshot Capacity (GB)',
            block_volume['snapshotCapacityGb'],
        ])
        table.add_row([
            'Snapshot Used (Bytes)',
            block_volume['parentVolume']['snapshotSizeBytes'],
        ])

    env.fout(table)