Exemplo n.º 1
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))
Exemplo n.º 2
0
def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, tag):
    """List hardware servers."""

    manager = SoftLayer.HardwareManager(env.client)

    servers = manager.list_hardware(hostname=hostname,
                                    domain=domain,
                                    cpus=cpu,
                                    memory=memory,
                                    datacenter=datacenter,
                                    nic_speed=network,
                                    tags=tag)

    table = formatting.Table([
        'id',
        'hostname',
        'primary_ip',
        'backend_ip',
        'datacenter',
        'action',
    ])
    table.sortby = sortby or 'hostname'

    for server in servers:
        table.add_row([
            utils.lookup(server, 'id'),
            utils.lookup(server, 'hostname') or formatting.blank(),
            utils.lookup(server, 'primaryIpAddress') or formatting.blank(),
            utils.lookup(server, 'primaryBackendIpAddress')
            or formatting.blank(),
            utils.lookup(server, 'datacenter', 'name') or formatting.blank(),
            formatting.active_txn(server),
        ])

    return table
Exemplo n.º 3
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")
Exemplo n.º 4
0
    def get_physical_servers(self):
        '''Get all the hardware instances'''
        hw = SoftLayer.HardwareManager(self.client)
        instances = hw.list_hardware()

        for instance in instances:
            self.process_instance(instance, 'hardware')
Exemplo n.º 5
0
def cli(env, identifier, start_date, end_date, summary_period, quite_summary):
    """Bandwidth data over date range. Bandwidth is listed in GB

    Using just a date might get you times off by 1 hour, use T00:01 to get just the specific days data
    Timezones can also be included with the YYYY-MM-DDTHH:mm:ss.00000-HH:mm format.

    Due to some rounding and date alignment details, results here might be slightly different than
    results in the control portal.

    Example::

        slcli hw bandwidth 1234 -s 2019-05-01T00:01 -e 2019-05-02T00:00:01.00000-12:00
    """
    hardware = SoftLayer.HardwareManager(env.client)
    hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier,
                                     'hardware')
    data = hardware.get_bandwidth_data(hardware_id, start_date, end_date, None,
                                       summary_period)

    title = "Bandwidth Report: %s - %s" % (start_date, end_date)
    table, sum_table = create_bandwidth_table(data, summary_period, title)

    env.fout(sum_table)
    if not quite_summary:
        env.fout(table)
Exemplo n.º 6
0
    def on_get(self, req, resp):
        client = req.env['sl_client']
        hardware = SoftLayer.HardwareManager(client)

        nodes = []
        hw_items = set([
            'id',
            'hostname',
            'domain',
            'hardwareStatus',
            'globalIdentifier',
            'fullyQualifiedDomainName',
            'processorPhysicalCoreAmount',
            'memoryCapacity',
            'primaryBackendIpAddress',
            'primaryIpAddress',
            'datacenter',
        ])
        server_items = set([
            'activeTransaction[id, transactionStatus[friendlyName,name]]',
        ])

        mask = ('[mask[%s],'
                ' mask(SoftLayer_Hardware_Server)[%s]]' %
                (','.join(hw_items), ','.join(server_items)))

        for hw in hardware.list_hardware(mask=mask):
            nodes.append({
                "uuid": hw['id'],
                "instance_uuid": hw['id'],
                # Get the actual power state of every device??? N+1 alert!
                # "power_state": '',
                "provision_state": hw['hardwareStatus']['status'],
            })
        resp.body = {'nodes': nodes}
Exemplo n.º 7
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.')
Exemplo n.º 8
0
def cli(env, title, subject_id, body, hardware_identifier, virtual_identifier,
        priority):
    """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,
                                              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']))
Exemplo n.º 9
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")
Exemplo n.º 10
0
def cli(env, identifier):
    """Get details for a hardware monitors device."""

    hardware = SoftLayer.HardwareManager(env.client)

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

    monitoring = hardware.get_hardware(identifier)

    table.add_row(['Domain', monitoring.get('fullyQualifiedDomainName')])
    table.add_row(['Public Ip', monitoring.get('primaryIpAddress')])
    table.add_row(['Private Ip', monitoring.get('primaryBackendIpAddress')])
    table.add_row(['Location', monitoring['datacenter']['longName']])

    monitoring_table = formatting.Table(
        ['Id', 'IpAddress', 'Status', 'Type', 'Notify'])
    for monitor in monitoring['networkMonitors']:
        monitoring_table.add_row([
            monitor.get('id'),
            monitor.get('ipAddress'),
            monitor.get('status'), monitor['queryType']['name'],
            monitor['responseAction']['actionDescription']
        ])

    table.add_row(['Devices monitors', monitoring_table])

    env.fout(table)
Exemplo n.º 11
0
def cli(env, identifier):
    """Get billing for a hardware device."""
    hardware = SoftLayer.HardwareManager(env.client)

    hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier,
                                     'hardware')
    result = hardware.get_hardware(hardware_id)
    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    table.add_row(['Id', identifier])

    table.add_row(
        ['Billing Item Id',
         utils.lookup(result, 'billingItem', 'id')])
    table.add_row(
        ['Recurring Fee',
         utils.lookup(result, 'billingItem', 'recurringFee')])
    table.add_row([
        'Total',
        utils.lookup(result, 'billingItem', 'nextInvoiceTotalRecurringAmount')
    ])
    table.add_row([
        'Provision Date',
        utils.lookup(result, 'billingItem', 'provisionDate')
    ])

    price_table = formatting.Table(['Item', 'Recurring Price'])
    for item in utils.lookup(result, 'billingItem', 'children') or []:
        price_table.add_row(
            [item['description'], item['nextInvoiceTotalRecurringAmount']])

    table.add_row(['prices', price_table])
    env.fout(table)
Exemplo n.º 12
0
def cli(env, **args):
    """Order/create a dedicated server."""

    template.update_with_template_args(args, list_args=['disk', 'key'])
    mgr = SoftLayer.HardwareManager(env.client)

    ds_options = mgr.get_dedicated_server_create_options(args['chassis'])

    order = _process_args(env, args, ds_options)

    # Do not create hardware server with --test or --export
    do_create = not (args['export'] or args['test'])

    output = None
    if args.get('test'):
        result = mgr.verify_order(**order)

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

        total = 0.0
        for price in result['prices']:
            total += float(price.get('recurringFee', 0.0))
            rate = "%.2f" % float(price['recurringFee'])

            table.add_row([price['item']['description'], rate])

        table.add_row(['Total monthly cost', "%.2f" % total])
        output = []
        output.append(table)
        output.append(
            formatting.FormattedItem(
                '', ' -- ! Prices reflected here are retail and do not '
                'take account level discounts and are not guaranteed.'))

    if args['export']:
        export_file = args.pop('export')
        template.export_to_template(export_file,
                                    args,
                                    exclude=['wait', 'test'])
        return 'Successfully exported options to a template file.'

    if do_create:
        if env.skip_confirmations or formatting.confirm(
                "This action will incur charges on your account. "
                "Continue?"):
            result = mgr.place_order(**order)

            table = formatting.KeyValueTable(['name', 'value'])
            table.align['name'] = 'r'
            table.align['value'] = 'l'
            table.add_row(['id', result['orderId']])
            table.add_row(['created', result['orderDate']])
            output = table
        else:
            raise exceptions.CLIAbort('Aborting dedicated server order.')

    return output
Exemplo n.º 13
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)
Exemplo n.º 14
0
    def get_physical_servers(self):
        '''Get all the hardware instances'''
        hw = SoftLayer.HardwareManager(self.client)
        mask = "mask[%s]" % ','.join(itertools.chain(self.common_items, self.hw_items))
        instances = hw.list_hardware(mask=mask)

        for instance in instances:
            self.process_instance(instance, 'hardware')
Exemplo n.º 15
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'])
Exemplo n.º 16
0
def cli(env, identifier):
    """List virtual server credentials."""

    hardware = SoftLayer.HardwareManager(env.client)
    result = hardware.get_hardware(identifier)
    table = formatting.Table(['username', 'password'])
    for item in result['operatingSystem']['passwords']:
        table.add_row([item['username'], item['password']])
    return table
Exemplo n.º 17
0
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.')
Exemplo n.º 18
0
def cli(env, identifier, discrete):
    """Retrieve a server’s hardware state via its internal sensors."""
    mgr = SoftLayer.HardwareManager(env.client)
    sensors = mgr.get_sensors(identifier)

    temperature_table = formatting.Table(["Sensor", "Status", "Reading", "Min", "Max"],
                                         title='Temperature (c)')

    volts_table = formatting.Table(["Sensor", "Status", "Reading", "Min", "Max"],
                                   title='Volts')

    watts_table = formatting.Table(["Sensor", "Status", "Reading"],
                                   title='Watts')

    rpm_table = formatting.Table(["Sensor", "Status", "Reading", "Min"],
                                 title='RPM')

    discrete_table = formatting.Table(["Sensor", "Status", "Reading"],
                                      title='Discrete')

    for sensor in sensors:
        if sensor.get('sensorUnits') == 'degrees C':
            temperature_table.add_row([sensor.get('sensorId'),
                                       sensor.get('status'),
                                       sensor.get('sensorReading'),
                                       sensor.get('upperNonCritical'),
                                       sensor.get('upperCritical')])

        if sensor.get('sensorUnits') == 'volts':
            volts_table.add_row([sensor.get('sensorId'),
                                 sensor.get('status'),
                                 sensor.get('sensorReading'),
                                 sensor.get('lowerNonCritical'),
                                 sensor.get('lowerCritical')])

        if sensor.get('sensorUnits') == 'Watts':
            watts_table.add_row([sensor.get('sensorId'),
                                 sensor.get('status'),
                                 sensor.get('sensorReading')])

        if sensor.get('sensorUnits') == 'RPM':
            rpm_table.add_row([sensor.get('sensorId'),
                               sensor.get('status'),
                               sensor.get('sensorReading'),
                               sensor.get('lowerCritical')])

        if sensor.get('sensorUnits') == 'discrete':
            discrete_table.add_row([sensor.get('sensorId'),
                                    sensor.get('status'),
                                    sensor.get('sensorReading')])
    env.fout(temperature_table)
    env.fout(rpm_table)
    env.fout(volts_table)
    env.fout(watts_table)
    if discrete:
        env.fout(discrete_table)
Exemplo n.º 19
0
 def execute(self, args):
     mgr = SoftLayer.HardwareManager(self.client)
     hw_id = helpers.resolve_id(mgr.resolve_ids, args.get('<identifier>'),
                                'hardware')
     if args['--really'] or formatting.confirm('This will power off the '
                                               'server with id %s '
                                               'Continue?' % hw_id):
         self.client['Hardware_Server'].powerOff(id=hw_id)
     else:
         raise exceptions.CLIAbort('Aborted.')
Exemplo n.º 20
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)
Exemplo n.º 21
0
    def execute(self, args):
        table = formatting.Table(['Code', 'Reason'])
        table.align['Code'] = 'r'
        table.align['Reason'] = 'l'

        mgr = SoftLayer.HardwareManager(self.client)

        for code, reason in mgr.get_cancellation_reasons().items():
            table.add_row([code, reason])

        return table
Exemplo n.º 22
0
def cli(env, identifier, wait):
    """Check if a server is ready."""

    compute = SoftLayer.HardwareManager(env.client)
    compute_id = helpers.resolve_id(compute.resolve_ids, identifier,
                                    'hardware')
    ready = compute.wait_for_ready(compute_id, wait)
    if ready:
        env.fout("READY")
    else:
        raise exceptions.CLIAbort("Server %s not ready" % compute_id)
Exemplo n.º 23
0
def cli(env, identifier):
    """Update server firmware."""

    mgr = SoftLayer.HardwareManager(env.client)
    hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
    if not (env.skip_confirmations or formatting.confirm(
            'This will power off the server with id %s and '
            'update device firmware. Continue?' % hw_id)):
        raise exceptions.CLIAbort('Aborted.')

    mgr.update_firmware(hw_id)
Exemplo n.º 24
0
    def connect(self, access, authentication_data, region):
        '''
        TBD
        '''

        try:
            _status = 100
            _fmsg = "An error has occurred, but no error message was captured"

            _username, _api_key, _api_type = authentication_data.split('-')
            if access.lower().count("private"):
                self.slconn = SoftLayer.create_client_from_env (username = _username.strip(), \
                                                                api_key= _api_key.strip(), \
                                                                endpoint_url = SoftLayer.API_PRIVATE_ENDPOINT)
            else:
                self.slconn = SoftLayer.create_client_from_env (username = _username.strip(), \
                                                                api_key= _api_key.strip(), \
                                                                endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT)

            _resp = self.slconn.call('Account', 'getObject')

            _datacenters = SoftLayer.VSManager(
                self.slconn).get_create_options()['datacenters']
            for _dcitem in _datacenters:
                if region == _dcitem['template']['datacenter']['name']:
                    _region = _dcitem['template']['datacenter']['name']

            _msg = "Selected region is " + str(region) + " (" + _region + ")"

            if _api_type.lower().count("baremetal"):
                self.nodeman = SoftLayer.HardwareManager(self.slconn)
            else:
                self.nodeman = SoftLayer.VSManager(self.slconn)

            self.sshman = SoftLayer.SshKeyManager(self.slconn)

            self.imageman = SoftLayer.ImageManager(self.slconn)

            _status = 0

        except Exception as msg:
            _fmsg = str(msg)
            _status = 23

        finally:
            if _status:
                _msg = self.get_description() + " connection failure: " + _fmsg
                cberr(_msg)
                raise CldOpsException(_msg, _status)
            else:

                _msg = self.get_description() + " connection successful."
                cbdebug(_msg)
                return _status, _msg, _region
Exemplo n.º 25
0
def power_off(env, identifier):
    """Power off an active server."""

    mgr = SoftLayer.HardwareManager(env.client)
    hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware')
    if env.skip_confirmations or formatting.confirm('This will power off the '
                                                    'server with id %s '
                                                    'Continue?' % hw_id):
        env.client['Hardware_Server'].powerOff(id=hw_id)
    else:
        raise exceptions.CLIAbort('Aborted.')
Exemplo n.º 26
0
def cli(env, identifier):
    """List virtual server credentials."""

    manager = SoftLayer.HardwareManager(env.client)
    hardware_id = helpers.resolve_id(manager.resolve_ids, identifier,
                                     'hardware')
    instance = manager.get_hardware(hardware_id)

    table = formatting.Table(['username', 'password'])
    for item in instance['operatingSystem']['passwords']:
        table.add_row([item['username'], item['password']])
    env.fout(table)
Exemplo n.º 27
0
def power_cycle(env, identifier):
    """Power cycle a server."""

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

    if not (env.skip_confirmations
            or formatting.confirm('This will power off the server with id %s. '
                                  'Continue?' % hw_id)):
        raise exceptions.CLIAbort('Aborted.')

    env.client['Hardware_Server'].powerCycle(id=hw_id)
Exemplo n.º 28
0
def rescue(env, identifier):
    """Reboot server into a rescue image."""

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

    if not (env.skip_confirmations or formatting.confirm(
            "This action will reboot this server. Continue?")):

        raise exceptions.CLIAbort('Aborted')

    env.client['Hardware_Server'].bootToRescueLayer(id=hw_id)
Exemplo n.º 29
0
    def execute(self, args):
        table = formatting.Table(['Code', 'Chassis'])
        table.align['Code'] = 'r'
        table.align['Chassis'] = 'l'

        mgr = SoftLayer.HardwareManager(self.client)
        chassis = mgr.get_available_dedicated_server_packages()

        for chassis in chassis:
            table.add_row([chassis[0], chassis[1]])

        return table
Exemplo n.º 30
0
    def execute(self, args):
        server = SoftLayer.HardwareManager(self.client)
        server_id = helpers.resolve_id(server.resolve_ids,
                                       args.get('<identifier>'), 'hardware')

        if args['--really'] or formatting.confirm(
                "This action will reboot this server. "
                "Continue?"):

            server.rescue(server_id)
        else:
            raise exceptions.CLIAbort('Aborted')