def cli(env, title, subject_id, body, hardware_identifier, virtual_identifier):
    """Create a support ticket."""
    ticket_mgr = SoftLayer.TicketManager(env.client)

    if body is None:
        body = click.edit('\n\n' + ticket.TEMPLATE_MSG)

    created_ticket = ticket_mgr.create_ticket(
        title=title,
        body=body,
        subject=subject_id)

    if hardware_identifier:
        hardware_mgr = SoftLayer.HardwareManager(env.client)
        hardware_id = helpers.resolve_id(hardware_mgr.resolve_ids,
                                         hardware_identifier,
                                         'hardware')
        ticket_mgr.attach_hardware(created_ticket['id'], hardware_id)

    if virtual_identifier:
        vs_mgr = SoftLayer.VSManager(env.client)
        vs_id = helpers.resolve_id(vs_mgr.resolve_ids,
                                   virtual_identifier,
                                   'VS')
        ticket_mgr.attach_virtual_server(created_ticket['id'], vs_id)

    env.fout(ticket.get_ticket_results(ticket_mgr, created_ticket['id']))
def cli(env, snapshot_id, volume_id):
    """Restores volume from existing snapshot."""
    iscsi_mgr = SoftLayer.ISCSIManager(env.client)
    volume_id = helpers.resolve_id(iscsi_mgr.resolve_ids, volume_id, 'iSCSI')
    snapshot_id = helpers.resolve_id(iscsi_mgr.resolve_ids,
                                     snapshot_id,
                                     'Snapshot')
    iscsi_mgr.restore_from_snapshot(volume_id, snapshot_id)
Example #3
0
 def execute(self, args):
     iscsi_mgr = ISCSIManager(self.client)
     volume_id = resolve_id(
         iscsi_mgr.resolve_ids, args.get('<volume_identifier>'), 'iSCSI')
     snapshot_id = resolve_id(
         iscsi_mgr.resolve_ids,
         args.get('<snapshot_identifier>'),
         'Snapshot')
     iscsi_mgr.restore_from_snapshot(volume_id, snapshot_id)
 def execute(self, args):
     cci = CCIManager(self.client)
     cci_id = resolve_id(cci.resolve_ids, args.get('<identifier>'), 'CCI')
     keys = []
     if args.get('--key'):
         for key in args.get('--key'):
             key_id = resolve_id(SshKeyManager(self.client).resolve_ids,
                                 key, 'SshKey')
             keys.append(key_id)
     if args['--really'] or no_going_back(cci_id):
         cci.reload_instance(cci_id, args['--postinstall'], keys)
     else:
         CLIAbort('Aborted')
Example #5
0
 def execute(self, args):
     hardware = SoftLayer.HardwareManager(self.client)
     hardware_id = helpers.resolve_id(
         hardware.resolve_ids, args.get('<identifier>'), 'hardware')
     keys = []
     if args.get('--key'):
         for key in args.get('--key'):
             resolver = SoftLayer.SshKeyManager(self.client).resolve_ids
             key_id = helpers.resolve_id(resolver, key, 'SshKey')
             keys.append(key_id)
     if args['--really'] or formatting.no_going_back(hardware_id):
         hardware.reload(hardware_id, args['--postinstall'], keys)
     else:
         raise exceptions.CLIAbort('Aborted')
 def execute(self, args):
     hardware = HardwareManager(self.client)
     hardware_id = resolve_id(
         hardware.resolve_ids, args.get('<identifier>'), 'hardware')
     keys = []
     if args.get('--key'):
         for key in args.get('--key'):
             key_id = resolve_id(SshKeyManager(self.client).resolve_ids,
                                 key, 'SshKey')
             keys.append(key_id)
     if args['--really'] or no_going_back(hardware_id):
         hardware.reload(hardware_id, args['--postinstall'], keys)
     else:
         CLIAbort('Aborted')
def cli(env, **args):
    """Create a placement group."""
    manager = PlacementManager(env.client)
    backend_router_id = helpers.resolve_id(manager.get_backend_router_id_from_hostname,
                                           args.get('backend_router'),
                                           'backendRouter')
    rule_id = helpers.resolve_id(manager.get_rule_id_from_name, args.get('rule'), 'Rule')
    placement_object = {
        'name': args.get('name'),
        'backendRouterId': backend_router_id,
        'ruleId': rule_id
    }

    result = manager.create(placement_object)
    click.secho("Successfully created placement group: ID: %s, Name: %s" % (result['id'], result['name']), fg='green')
Example #8
0
def cli(env, identifier, postinstall, key):
    """Reload operating system on a virtual server."""

    vsi = SoftLayer.VSManager(env.client)
    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    keys = []
    if key:
        for single_key in key:
            resolver = SoftLayer.SshKeyManager(env.client).resolve_ids
            key_id = helpers.resolve_id(resolver, single_key, 'SshKey')
            keys.append(key_id)
    if not (env.skip_confirmations or formatting.no_going_back(vs_id)):
        raise exceptions.CLIAbort('Aborted')

    vsi.reload_instance(vs_id, postinstall, keys)
Example #9
0
def cli(env, identifier, count):
    """Get details for a ticket."""

    mgr = SoftLayer.TicketManager(env.client)

    ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket')
    return ticket.get_ticket_results(mgr, ticket_id, update_count=count)
Example #10
0
def cli(env, zone, data, record, ttl, type):
    """List all records in a zone."""

    manager = SoftLayer.DNSManager(env.client)
    table = formatting.Table(['id', 'record', 'type', 'ttl', 'data'])

    table.align['ttl'] = 'l'
    table.align['record'] = 'r'
    table.align['data'] = 'l'

    zone_id = helpers.resolve_id(manager.resolve_ids, zone, name='zone')

    records = manager.get_records(zone_id,
                                  record_type=type,
                                  host=record,
                                  ttl=ttl,
                                  data=data)

    for the_record in records:
        table.add_row([
            the_record['id'], the_record['host'], the_record['type'].upper(),
            the_record['ttl'], the_record['data']
        ])

    env.fout(table)
Example #11
0
def cli(env, identifier):
    """View details of a placement group.

    IDENTIFIER can be either the Name or Id of the placement group you want to view
    """
    manager = PlacementManager(env.client)
    group_id = helpers.resolve_id(manager.resolve_ids, identifier,
                                  'placement_group')
    result = manager.get_object(group_id)
    table = formatting.Table(
        ["Id", "Name", "Backend Router", "Rule", "Created"])

    table.add_row([
        result['id'], result['name'], result['backendRouter']['hostname'],
        result['rule']['name'], result['createDate']
    ])
    guest_table = formatting.Table([
        "Id", "FQDN", "Primary IP", "Backend IP", "CPU", "Memory",
        "Provisioned", "Transaction"
    ])
    for guest in result['guests']:
        guest_table.add_row([
            guest.get('id'),
            guest.get('fullyQualifiedDomainName'),
            guest.get('primaryIpAddress'),
            guest.get('primaryBackendIpAddress'),
            guest.get('maxCpu'),
            guest.get('maxMemory'),
            guest.get('provisionDate'),
            formatting.active_txn(guest)
        ])

    env.fout(table)
    env.fout(guest_table)
Example #12
0
def cli(env, identifier, count):
    """Get details for a ticket."""

    mgr = SoftLayer.TicketManager(env.client)

    ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, "ticket")
    env.fout(ticket.get_ticket_results(mgr, ticket_id, update_count=count))
Example #13
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")
Example #14
0
    def execute(self, args):
        mgr = SoftLayer.FirewallManager(self.client)
        input_id = helpers.resolve_id(
            mgr.resolve_ids, args.get('<identifier>'), 'firewall')
        ha_support = args.get('--ha', False)
        if not args['--really']:
            if args['--vlan']:
                pkg = mgr.get_dedicated_package(ha_enabled=ha_support)
            elif args['--cci']:
                pkg = mgr.get_standard_package(input_id)
            elif args['--server']:
                pkg = mgr.get_standard_package(input_id, is_cci=False)

            if not pkg:
                return "Unable to add firewall - Is network public enabled?"
            print_package_info(pkg)

            if not formatting.confirm("This action will incur charges on your "
                                      "account. Continue?"):
                raise exceptions.CLIAbort('Aborted.')

        if args['--vlan']:
            mgr.add_vlan_firewall(input_id, ha_enabled=ha_support)
        elif args['--cci']:
            mgr.add_standard_firewall(input_id, is_cci=True)
        elif args['--server']:
            mgr.add_standard_firewall(input_id, is_cci=False)

        return "Firewall is being created!"
    def list_zone(self, args):
        """ list records for a particular zone """
        manager = SoftLayer.DNSManager(self.client)
        table = formatting.Table(['id', 'record', 'type', 'ttl', 'value'])

        table.align['ttl'] = 'l'
        table.align['record'] = 'r'
        table.align['value'] = 'l'

        zone_id = helpers.resolve_id(manager.resolve_ids, args['<zone>'],
                                     name='zone')

        records = manager.get_records(
            zone_id,
            record_type=args.get('--type'),
            host=args.get('--record'),
            ttl=args.get('--ttl'),
            data=args.get('--data'),
        )

        for record in records:
            table.add_row([
                record['id'],
                record['host'],
                record['type'].upper(),
                record['ttl'],
                record['data']
            ])

        return table
Example #16
0
    def execute(self, args):
        vsi = SoftLayer.VSManager(self.client)

        vs_id = helpers.resolve_id(vsi.resolve_ids,
                                   args.get('<identifier>'),
                                   'VS')

        if args['--all']:
            additional_disks = True
        else:
            additional_disks = False

        capture = vsi.capture(vs_id,
                              args.get('--name'),
                              additional_disks,
                              args.get('--note'))

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

        table.add_row(['vs_id', capture['guestId']])
        table.add_row(['date', capture['createDate'][:10]])
        table.add_row(['time', capture['createDate'][11:19]])
        table.add_row(['transaction', formatting.transaction_status(capture)])
        table.add_row(['transaction_id', capture['id']])
        table.add_row(['all_disks', additional_disks])
        return table
    def execute(self, args):
        data = {}

        if args['--userdata'] and args['--userfile']:
            raise ArgumentError('[-u | --userdata] not allowed with '
                                '[-F | --userfile]')
        if args['--userfile']:
            if not os.path.exists(args['--userfile']):
                raise 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 = HardwareManager(self.client)
        hw_id = resolve_id(mgr.resolve_ids, args.get('<identifier>'),
                           'hardware')
        if not mgr.edit(hw_id, **data):
            raise CLIAbort("Failed to update hardware")
Example #18
0
 def execute(self, args):
     virtual_guest = self.client['Virtual_Guest']
     vsi = SoftLayer.VSManager(self.client)
     vs_id = helpers.resolve_id(vsi.resolve_ids,
                                args.get('<identifier>'),
                                'VS')
     virtual_guest.resume(id=vs_id)
Example #19
0
def cli(env, identifier):
    """Delete an image."""

    image_mgr = SoftLayer.ImageManager(env.client)
    image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')

    image_mgr.delete_image(image_id)
Example #20
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))
def cli(env, identifier):
    """Cancel all virtual guests of the dedicated host immediately.

       Use the 'slcli vs cancel' command to cancel an specific guest
    """

    dh_mgr = SoftLayer.DedicatedHostManager(env.client)

    host_id = helpers.resolve_id(dh_mgr.resolve_ids, identifier, 'dedicated host')

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

    table = formatting.Table(['id', 'server name', 'status'])

    result = dh_mgr.cancel_guests(host_id)

    if result:
        for status in result:
            table.add_row([
                status['id'],
                status['fqdn'],
                status['status']
            ])

        env.fout(table)
    else:
        click.secho('There is not any guest into the dedicated host %s' % host_id, fg='red')
Example #22
0
def cli(env, identifier, target):
    """Assigns the global IP to a target."""

    mgr = SoftLayer.NetworkManager(env.client)
    global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier,
                                      name='global ip')
    mgr.assign_global_ip(global_ip_id, target)
Example #23
0
def cli(env, identifier, cpu, private, memory, network):
    """Upgrade a virtual server."""

    vsi = SoftLayer.VSManager(env.client)

    if not any([cpu, memory, network]):
        raise exceptions.ArgumentError(
            "Must provide [--cpu], [--memory], or [--network] 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):
        raise exceptions.CLIAbort('VS Upgrade Failed')
Example #24
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")
Example #25
0
 def execute(self, args):
     vsi = VSManager(self.client)
     vs_id = resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS')
     if args['--really'] or no_going_back(vs_id):
         vsi.cancel_instance(vs_id)
     else:
         CLIAbort('Aborted')
Example #26
0
def cli(env, identifier, body):
    """Adds an update to an existing ticket.

Will update the ticket with `Some text`.::

        slcli ticket update 123456 --body="Some text"

Will update the ticket with text from STDIN::

        cat sometfile.txt | slcli ticket update 123456

Will open the default text editor, and once closed, use that text to update the ticket::

        slcli ticket update 123456
    """
    mgr = SoftLayer.TicketManager(env.client)

    ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket')
    if body is None:
        stdin = click.get_text_stream('stdin')
        # Means there is text on the STDIN buffer, read it and add to the ticket
        if not stdin.isatty():
            body = stdin.read()
        # This is an interactive terminal, open a text editor
        else:
            body = click.edit('\n\n' + ticket.TEMPLATE_MSG)
    mgr.update_ticket(ticket_id=ticket_id, body=body)
    env.fout("Ticket Updated!")
Example #27
0
 def execute(self, args):
     cci = CCIManager(self.client)
     cci_id = resolve_id(cci.resolve_ids, args.get('<identifier>'), 'CCI')
     if args['--really'] or no_going_back(cci_id):
         cci.cancel_instance(cci_id)
     else:
         CLIAbort('Aborted')
Example #28
0
def cli(env, identifier, network, speed):
    """Manage NIC settings."""

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

    mgr.change_port_speed(hw_id, network == 'public', int(speed))
Example #29
0
    def execute(self, args):
        data = {}

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

        if args.get('--userdata'):
            data['userdata'] = args['--userdata']
        elif args.get('--userfile'):
            f = open(args['--userfile'], 'r')
            try:
                data['userdata'] = f.read()
            finally:
                f.close()

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

        cci = CCIManager(self.client)
        cci_id = resolve_id(cci.resolve_ids, args.get('<identifier>'), 'CCI')
        if not cci.edit(cci_id, **data):
            raise CLIAbort("Failed to update CCI")
Example #30
0
def cli(env, zone, data, record, ttl, type):
    """List all records in a zone."""

    manager = SoftLayer.DNSManager(env.client)
    table = formatting.Table(['id', 'record', 'type', 'ttl', 'data'])

    table.align['ttl'] = 'l'
    table.align['record'] = 'r'
    table.align['data'] = 'l'

    zone_id = helpers.resolve_id(manager.resolve_ids, zone, name='zone')

    records = manager.get_records(zone_id,
                                  record_type=type,
                                  host=record,
                                  ttl=ttl,
                                  data=data)

    for record in records:
        table.add_row([
            record['id'],
            record['host'],
            record['type'].upper(),
            record['ttl'],
            record['data']
        ])

    env.fout(table)
Example #31
0
def cli(env, identifier):
    """Unassigns a global IP from a target."""

    mgr = SoftLayer.NetworkManager(env.client)
    global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier,
                                      name='global ip')
    mgr.unassign_global_ip(global_ip_id)
Example #32
0
    def execute(self, args):
        cci = CCIManager(self.client)

        cci_id = resolve_id(cci.resolve_ids, args.get('<identifier>'), 'CCI')

        if args['--all']:
            additional_disks = True
        else:
            additional_disks = False

        capture = cci.capture(cci_id,
                              args.get('--name'),
                              additional_disks,
                              args.get('--note'))

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

        table.add_row(['cci_id', capture['guestId']])
        table.add_row(['date', capture['createDate'][:10]])
        table.add_row(['time', capture['createDate'][11:19]])
        table.add_row(['transaction', transaction_status(capture)])
        table.add_row(['transaction_id', capture['id']])
        table.add_row(['all_disks', additional_disks])
        return table
Example #33
0
    def execute(self, args):
        public = args['public']

        cci = CCIManager(self.client)
        cci_id = resolve_id(cci.resolve_ids, args.get('<identifier>'), 'CCI')

        cci.change_port_speed(cci_id, public, args['--speed'])
Example #34
0
def cli(env, identifier, domain, userfile, tag, hostname, userdata,
        public_speed, private_speed):
    """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")

    if public_speed is not None:
        mgr.change_port_speed(hw_id, True, int(public_speed))

    if private_speed is not None:
        mgr.change_port_speed(hw_id, False, int(private_speed))
Example #35
0
    def execute(self, args):
        public = args['public']

        vsi = VSManager(self.client)
        vs_id = resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS')

        vsi.change_port_speed(vs_id, public, args['--speed'])
Example #36
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)
Example #37
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")
Example #38
0
    def execute(self, args):
        public = args['public']

        mgr = SoftLayer.HardwareManager(self.client)
        hw_id = helpers.resolve_id(mgr.resolve_ids, args.get('<identifier>'),
                                   'hardware')

        mgr.change_port_speed(hw_id, public, args['--speed'])
Example #39
0
    def execute(self, args):
        public = args['public']

        vsi = SoftLayer.VSManager(self.client)
        vs_id = helpers.resolve_id(vsi.resolve_ids, args.get('<identifier>'),
                                   'VS')

        vsi.change_port_speed(vs_id, public, args['--speed'])
Example #40
0
def cli(env, identifier):
    """Unassigns a global IP from a target."""

    mgr = SoftLayer.NetworkManager(env.client)
    global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids,
                                      identifier,
                                      name='global ip')
    mgr.unassign_global_ip(global_ip_id)
Example #41
0
def cli(env, identifier, postinstall, key):
    """Reload operating system on a server."""

    hardware = SoftLayer.HardwareManager(env.client)
    hardware_id = helpers.resolve_id(hardware.resolve_ids,
                                     identifier,
                                     'hardware')
    key_list = []
    if key:
        for single_key in key:
            resolver = SoftLayer.SshKeyManager(env.client).resolve_ids
            key_id = helpers.resolve_id(resolver, single_key, 'SshKey')
            key_list.append(key_id)
    if env.skip_confirmations or formatting.no_going_back(hardware_id):
        hardware.reload(hardware_id, postinstall, key_list)
    else:
        raise exceptions.CLIAbort('Aborted')
Example #42
0
def cli(env, identifier, target):
    """Assigns the global IP to a target."""

    mgr = SoftLayer.NetworkManager(env.client)
    global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids,
                                      identifier,
                                      name='global ip')
    mgr.assign_global_ip(global_ip_id, target)
Example #43
0
 def execute(self, args):
     vsi = SoftLayer.VSManager(self.client)
     vs_id = helpers.resolve_id(vsi.resolve_ids, args.get('<identifier>'),
                                'VS')
     if args['--really'] or formatting.no_going_back(vs_id):
         vsi.cancel_instance(vs_id)
     else:
         raise exceptions.CLIAbort('Aborted')
Example #44
0
def cli(env, identifier, enable):
    """Toggle the IPMI interface on and off"""

    mgr = SoftLayer.HardwareManager(env.client)
    hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
    result = env.client['Hardware_Server'].toggleManagementInterface(enable,
                                                                     id=hw_id)
    env.fout(result)
Example #45
0
def _parse_create_args(client, args):
    """Converts CLI arguments to args for VSManager.create_instance.

    :param dict args: CLI arguments
    """
    data = {
        "hourly": args['billing'] == 'hourly',
        "cpus": args['cpu'],
        "domain": args['domain'],
        "hostname": args['hostname'],
        "private": args['private'],
        "dedicated": args['dedicated'],
        "disks": args['disk'],
        "local_disk": not args['san'],
    }

    data["memory"] = args['memory']

    if args.get('os'):
        data['os_code'] = args['os']

    if args.get('image'):
        data['image_id'] = args['image']

    if args.get('datacenter'):
        data['datacenter'] = args['datacenter']

    if args.get('network'):
        data['nic_speed'] = args.get('network')

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

    if args.get('postinstall'):
        data['post_uri'] = args.get('postinstall')

    # Get the SSH keys
    if args.get('key'):
        keys = []
        for key in args.get('key'):
            resolver = SoftLayer.SshKeyManager(client).resolve_ids
            key_id = helpers.resolve_id(resolver, key, 'SshKey')
            keys.append(key_id)
        data['ssh_keys'] = keys

    if args.get('vlan_public'):
        data['public_vlan'] = args['vlan_public']

    if args.get('vlan_private'):
        data['private_vlan'] = args['vlan_private']

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

    return data
Example #46
0
def cli(env, title, subject_id, body, hardware_identifier, virtual_identifier,
        priority):
    """Create a Infrastructure support ticket.

    Will create the ticket with `Some text`.::

        slcli ticket create --body="Some text" --subject-id 1522 --hardware 12345 --title "My New Ticket"

    Will create the ticket with text from STDIN::

        cat sometfile.txt | slcli ticket create --subject-id 1003 --virtual 111111 --title "Reboot Me"

    Will open the default text editor, and once closed, use that text to create the ticket::

        slcli ticket create --subject-id 1482 --title "Vyatta Questions..."

    """
    ticket_mgr = SoftLayer.TicketManager(env.client)
    if body is None:
        stdin = click.get_text_stream('stdin')
        # Means there is text on the STDIN buffer, read it and add to the ticket
        if not stdin.isatty():
            body = stdin.read()
        # This is an interactive terminal, open a text editor
        else:
            body = click.edit('\n\n' + ticket.TEMPLATE_MSG)
    created_ticket = ticket_mgr.create_ticket(title=title,
                                              body=body,
                                              subject=subject_id,
                                              priority=priority)

    if hardware_identifier:
        hardware_mgr = SoftLayer.HardwareManager(env.client)
        hardware_id = helpers.resolve_id(hardware_mgr.resolve_ids,
                                         hardware_identifier, 'hardware')
        ticket_mgr.attach_hardware(created_ticket['id'], hardware_id)

    if virtual_identifier:
        vs_mgr = SoftLayer.VSManager(env.client)
        vs_id = helpers.resolve_id(vs_mgr.resolve_ids, virtual_identifier,
                                   'VS')
        ticket_mgr.attach_virtual_server(created_ticket['id'], vs_id)

    env.fout(ticket.get_ticket_results(ticket_mgr, False,
                                       created_ticket['id']))
Example #47
0
def cli(env, **args):
    """Create a placement group"""
    manager = PlacementManager(env.client)
    backend_router_id = helpers.resolve_id(
        manager.get_backend_router_id_from_hostname,
        args.get('backend_router'), 'backendRouter')
    rule_id = helpers.resolve_id(manager.get_rule_id_from_name,
                                 args.get('rule'), 'Rule')
    placement_object = {
        'name': args.get('name'),
        'backendRouterId': backend_router_id,
        'ruleId': rule_id
    }

    result = manager.create(placement_object)
    click.secho("Successfully created placement group: ID: %s, Name: %s" %
                (result['id'], result['name']),
                fg='green')
Example #48
0
def cli(env, identifier, network_type, speed):
    """Manage network settings."""

    public = (network_type == 'public')

    vsi = SoftLayer.VSManager(env.client)
    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')

    vsi.change_port_speed(vs_id, public, speed)
Example #49
0
def cli(env, identifier, postinstall, key, image):
    """Reload operating system on a virtual server."""

    vsi = SoftLayer.VSManager(env.client)
    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    keys = []
    if key:
        for single_key in key:
            resolver = SoftLayer.SshKeyManager(env.client).resolve_ids
            key_id = helpers.resolve_id(resolver, single_key, 'SshKey')
            keys.append(key_id)
    if not (env.skip_confirmations or formatting.no_going_back(vs_id)):
        raise exceptions.CLIAbort('Aborted')

    vsi.reload_instance(vs_id,
                        post_uri=postinstall,
                        ssh_keys=keys,
                        image_id=image)
Example #50
0
def cli(env, identifier, label, note):
    """Edits an SSH key."""

    mgr = SoftLayer.SshKeyManager(env.client)

    key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')

    if not mgr.edit_key(key_id, label=label, notes=note):
        raise exceptions.CLIAbort('Failed to edit SSH key')
Example #51
0
def cli(env, identifier):
    """Cancel virtual servers."""

    vsi = SoftLayer.VSManager(env.client)
    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    if not (env.skip_confirmations or formatting.no_going_back(vs_id)):
        raise exceptions.CLIAbort('Aborted')

    vsi.cancel_instance(vs_id)
Example #52
0
def cli(env, identifier):
    """Permanently removes an SSH key."""
    mgr = SoftLayer.SshKeyManager(env.client)

    key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')
    if not (env.skip_confirmations or formatting.no_going_back(key_id)):
        raise exceptions.CLIAbort('Aborted')

    mgr.delete_key(key_id)
Example #53
0
def cli(env, identifier):
    """Get details for an image."""

    image_mgr = SoftLayer.ImageManager(env.client)
    image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image')

    image = image_mgr.get_image(image_id, mask=image_mod.DETAIL_MASK)
    disk_space = 0
    datacenters = []
    for child in image.get('children'):
        disk_space = int(child.get('blockDevicesDiskSpaceTotal', 0))
        if child.get('datacenter'):
            datacenters.append(utils.lookup(child, 'datacenter', 'name'))

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['id', image['id']])
    table.add_row([
        'global_identifier',
        image.get('globalIdentifier', formatting.blank())
    ])
    table.add_row(['name', image['name'].strip()])
    table.add_row([
        'status',
        formatting.FormattedItem(
            utils.lookup(image, 'status', 'keyname'),
            utils.lookup(image, 'status', 'name'),
        )
    ])
    table.add_row([
        'active_transaction',
        formatting.transaction_status(image.get('transaction')),
    ])
    table.add_row(['account', image.get('accountId', formatting.blank())])
    table.add_row([
        'visibility', image_mod.PUBLIC_TYPE
        if image['publicFlag'] else image_mod.PRIVATE_TYPE
    ])
    table.add_row([
        'type',
        formatting.FormattedItem(
            utils.lookup(image, 'imageType', 'keyName'),
            utils.lookup(image, 'imageType', 'name'),
        )
    ])
    table.add_row(['flex', image.get('flexImageFlag')])
    table.add_row(['note', image.get('note')])
    table.add_row(['created', image.get('createDate')])
    table.add_row(['disk_space', formatting.b_to_gb(disk_space)])
    table.add_row([
        'datacenters',
        formatting.listing(sorted(datacenters), separator=',')
    ])

    env.fout(table)
def cli(env, identifier, username_storage):
    """Authorize File or Block Storage to a Hardware Server."""
    hardware = SoftLayer.HardwareManager(env.client)
    hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier,
                                     'hardware')

    if not hardware.authorize_storage(hardware_id, username_storage):
        raise exceptions.CLIAbort('Authorize Storage Failed')
    env.fout('Successfully Storage Added.')
Example #55
0
def cli(env, identifier, credential_id):
    """Delete the credential of an Object Storage Account."""

    mgr = SoftLayer.ObjectStorageManager(env.client)
    storage_id = helpers.resolve_id(mgr.resolve_ids, identifier,
                                    'Object Storage')
    credential = mgr.delete_credential(storage_id, credential_id=credential_id)

    env.fout(credential)
Example #56
0
    def execute(self, args):
        mgr = SoftLayer.SshKeyManager(self.client)

        key_id = helpers.resolve_id(mgr.resolve_ids, args.get('<identifier>'),
                                    'SshKey')
        if args['--really'] or formatting.no_going_back(key_id):
            mgr.delete_key(key_id)
        else:
            raise exceptions.CLIAbort('Aborted')
Example #57
0
    def execute(self, args):
        mgr = SoftLayer.SshKeyManager(self.client)

        key_id = helpers.resolve_id(mgr.resolve_ids, args.get('<identifier>'),
                                    'SshKey')

        if not mgr.edit_key(
                key_id, label=args['--label'], notes=args['--notes']):
            raise exceptions.CLIAbort('Failed to edit SSH key')
Example #58
0
def cli(env, identifier, no_vs, no_hardware):
    """Get subnet details."""

    mgr = SoftLayer.NetworkManager(env.client)
    subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids,
                                   identifier,
                                   name='subnet')
    subnet = mgr.get_subnet(subnet_id)

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

    table.add_row(['id', subnet['id']])
    table.add_row([
        'identifier',
        '%s/%s' % (subnet['networkIdentifier'], str(subnet['cidr']))
    ])
    table.add_row(['subnet type', subnet['subnetType']])
    table.add_row(['gateway', subnet.get('gateway', formatting.blank())])
    table.add_row(
        ['broadcast',
         subnet.get('broadcastAddress', formatting.blank())])
    table.add_row(['datacenter', subnet['datacenter']['name']])
    table.add_row(
        ['usable ips',
         subnet.get('usableIpAddressCount', formatting.blank())])

    if not no_vs:
        if subnet['virtualGuests']:
            vs_table = formatting.Table(['Hostname', 'Domain', 'IP'])
            vs_table.align['Hostname'] = 'r'
            vs_table.align['IP'] = 'l'
            for vsi in subnet['virtualGuests']:
                vs_table.add_row([
                    vsi['hostname'], vsi['domain'],
                    vsi.get('primaryIpAddress')
                ])
            table.add_row(['vs', vs_table])
        else:
            table.add_row(['vs', 'none'])

    if not no_hardware:
        if subnet['hardware']:
            hw_table = formatting.Table(['Hostname', 'Domain', 'IP'])
            hw_table.align['Hostname'] = 'r'
            hw_table.align['IP'] = 'l'
            for hardware in subnet['hardware']:
                hw_table.add_row([
                    hardware['hostname'], hardware['domain'],
                    hardware.get('primaryIpAddress')
                ])
            table.add_row(['hardware', hw_table])
        else:
            table.add_row(['hardware', 'none'])

    env.fout(table)
Example #59
0
    def _update_with_like_args(self, args):
        """ Update arguments with options taken from a currently running VS.

        :param VSManager args: A VSManager
        :param dict args: CLI arguments
        """
        if args['--like']:
            vsi = SoftLayer.VSManager(self.client)
            vs_id = helpers.resolve_id(vsi.resolve_ids,
                                       args.pop('--like'),
                                       'VS')
            like_details = vsi.get_instance(vs_id)
            like_args = {
                '--hostname': like_details['hostname'],
                '--domain': like_details['domain'],
                '--cpu': like_details['maxCpu'],
                '--memory': like_details['maxMemory'],
                '--hourly': like_details['hourlyBillingFlag'],
                '--monthly': not like_details['hourlyBillingFlag'],
                '--datacenter': like_details['datacenter']['name'],
                '--network': like_details['networkComponents'][0]['maxSpeed'],
                '--user-data': like_details['userData'] or None,
                '--postinstall': like_details.get('postInstallScriptUri'),
                '--dedicated': like_details['dedicatedAccountHostOnlyFlag'],
                '--private': like_details['privateNetworkOnlyFlag'],
            }

            tag_refs = like_details.get('tagReferences', None)
            if tag_refs is not None and len(tag_refs) > 0:
                tags = ','.join([t['tag']['name'] for t in tag_refs])
                like_args['--tag'] = tags

            # Handle mutually exclusive options
            like_image = utils.lookup(like_details,
                                      'blockDeviceTemplateGroup',
                                      'globalIdentifier')
            like_os = utils.lookup(like_details,
                                   'operatingSystem',
                                   'softwareLicense',
                                   'softwareDescription',
                                   'referenceCode')
            if like_image and not args.get('--os'):
                like_args['--image'] = like_image
            elif like_os and not args.get('--image'):
                like_args['--os'] = like_os

            if args.get('--hourly'):
                like_args['--monthly'] = False

            if args.get('--monthly'):
                like_args['--hourly'] = False

            # Merge like VS options with the options passed in
            for key, value in like_args.items():
                if args.get(key) in [None, False]:
                    args[key] = value
Example #60
0
def cli(env, identifier, immediate, comment, reason):
    """Cancel a dedicated server."""

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

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

    mgr.cancel_hardware(hw_id, reason, comment, immediate)