def cli(env, **args):
    """Order/create virtual servers."""

    vsi = SoftLayer.VSManager(env.client)
    _validate_args(env, args)
    create_args = _parse_create_args(env.client, args)
    test = args.get('test', False)
    do_create = not (args.get('export') or test)

    if do_create:
        if not (env.skip_confirmations or formatting.confirm(
                "This action will incur charges on your account. Continue?")):
            raise exceptions.CLIAbort('Aborting virtual server order.')

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

    else:
        result = vsi.order_guest(create_args, test)
        output = _build_receipt_table(result, args.get('billing'), test)

        if do_create:
            env.fout(_build_guest_table(result))
        env.fout(output)

        if args.get('wait'):
            virtual_guests = utils.lookup(result, 'orderDetails', 'virtualGuests')
            guest_id = virtual_guests[0]['id']
            click.secho("Waiting for %s to finish provisioning..." % guest_id, fg='green')
            ready = vsi.wait_for_ready(guest_id, args.get('wait') or 1)
            if ready is False:
                env.out(env.fmt(output))
                raise exceptions.CLIHalt(code=1)
Example #2
0
    def test_export_to_template(self):
        if(sys.platform.startswith("win")):
            self.skipTest("Test doesn't work in Windows")
        # Tempfile creation is wonky on windows
        with tempfile.NamedTemporaryFile() as tmp:

            template.export_to_template(tmp.name, {
                'os': None,
                'datacenter': 'ams01',
                'disk': ('disk1', 'disk2'),
                # The following should get stripped out
                'config': 'no',
                'really': 'no',
                'format': 'no',
                'debug': 'no',
                # exclude list
                'test': 'test',
            }, exclude=['test'])

            with open(tmp.name) as f:
                data = f.read()

                self.assertEqual(len(data.splitlines()), 2)
                self.assertIn('datacenter=ams01\n', data)
                self.assertIn('disk=disk1,disk2\n', data)
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
    def test_export_to_template(self):
        with mock.patch(open_path, mock.mock_open(), create=True) as open_:
            template.export_to_template('filename', {
                'os': None,
                'datacenter': 'ams01',
                'disk': ('disk1', 'disk2'),
                # The following should get stripped out
                'config': 'no',
                'really': 'no',
                'format': 'no',
                'debug': 'no',
                # exclude list
                'test': 'test',
            }, exclude=['test'])

            open_.assert_called_with('filename', 'w')
            open_().write.assert_has_calls([
                mock.call('datacenter=ams01\n'),
                mock.call('disk=disk1,disk2\n'),
            ], any_order=True)  # Order isn't really guaranteed
    def test_export_to_template(self):
        with tempfile.NamedTemporaryFile() as tmp:

            template.export_to_template(tmp.name, {
                'os': None,
                'datacenter': 'ams01',
                'disk': ('disk1', 'disk2'),
                # The following should get stripped out
                'config': 'no',
                'really': 'no',
                'format': 'no',
                'debug': 'no',
                # exclude list
                'test': 'test',
            }, exclude=['test'])

            with open(tmp.name) as f:
                data = f.read()

                self.assertEqual(len(data.splitlines()), 2)
                self.assertIn('datacenter=ams01\n', data)
                self.assertIn('disk=disk1,disk2\n', data)
    def test_export_to_template(self):
        with mock.patch(open_path, mock.mock_open(), create=True) as open_:
            template.export_to_template(
                "filename",
                {
                    "--os": None,
                    "--datacenter": "ams01",
                    "--disk": ["disk1", "disk2"],
                    # The following should get stripped out
                    "--config": "no",
                    "--really": "no",
                    "--format": "no",
                    "--debug": "no",
                    # exclude list
                    "--test": "test",
                },
                exclude=["--test"],
            )

            open_.assert_called_with("filename", "w")
            open_().write.assert_has_calls(
                [mock.call("datacenter=ams01\n"), mock.call("disk=disk1,disk2\n")], any_order=True
            )  # Order isn't really guaranteed
Example #7
0
def cli(env, **args):
    """Order/create virtual servers."""

    template.update_with_template_args(args, list_args=['disk', 'key'])
    vsi = SoftLayer.VSManager(env.client)
    _update_with_like_args(env.client, args)
    _validate_args(args)

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

    table = formatting.Table(['Item', 'cost'])
    table.align['Item'] = 'r'
    table.align['cost'] = 'r'
    data = _parse_create_args(env.client, args)

    output = []
    if args.get('test'):
        result = vsi.verify_create_instance(**data)
        total_monthly = 0.0
        total_hourly = 0.0

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

        for price in result['prices']:
            total_monthly += float(price.get('recurringFee', 0.0))
            total_hourly += float(price.get('hourlyRecurringFee', 0.0))
            if args.get('billing') == 'hourly':
                rate = "%.2f" % float(price['hourlyRecurringFee'])
            elif args.get('billing') == 'monthly':
                rate = "%.2f" % float(price['recurringFee'])

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

        total = 0
        if args.get('billing') == 'hourly':
            total = total_hourly
        elif args.get('billing') == 'monthly':
            total = total_monthly

        billing_rate = 'monthly'
        if args.get('billing') == 'hourly':
            billing_rate = 'hourly'
        table.add_row(['Total %s cost' % billing_rate, "%.2f" % total])
        output.append(table)
        output.append(formatting.FormattedItem(
            None,
            ' -- ! 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 not (env.skip_confirmations or formatting.confirm(
                "This action will incur charges on your account. Continue?")):
            raise exceptions.CLIAbort('Aborting virtual server order.')

        result = vsi.create_instance(**data)

        table = formatting.KeyValueTable(['name', 'value'])
        table.align['name'] = 'r'
        table.align['value'] = 'l'
        table.add_row(['id', result['id']])
        table.add_row(['created', result['createDate']])
        table.add_row(['guid', result['globalIdentifier']])
        output.append(table)

        if args.get('wait'):
            ready = vsi.wait_for_ready(
                result['id'], int(args.get('wait') or 1))
            table.add_row(['ready', ready])

    return output
Example #8
0
def cli(env, **args):
    """Order/create a dedicated server."""

    template.update_with_template_args(args, list_args=['key'])
    _validate_args(args)

    mgr = SoftLayer.HardwareManager(env.client)

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

    order = {
        'hostname': args['hostname'],
        'domain': args['domain'],
        'size': args['size'],
        'public_vlan': args.get('vlan_public'),
        'private_vlan': args.get('vlan_private'),
        'location': args.get('datacenter'),
        'ssh_keys': ssh_keys,
        'post_uri': args.get('postinstall'),
        'os': args['os'],
        'hourly': args.get('billing') == 'hourly',
        'port_speed': args.get('port_speed'),
        'no_public': args.get('no_public') or False,
        'extras': args.get('extra'),
    }

    # 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 not (env.skip_confirmations or formatting.confirm(
                "This action will incur charges on your account. "
                "Continue?")):
            raise exceptions.CLIAbort('Aborting dedicated server order.')

        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

    return output
Example #9
0
def cli(env, **args):
    """Order/create a dedicated server."""
    mgr = SoftLayer.HardwareManager(env.client)

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

    order = {
        'hostname': args['hostname'],
        'domain': args['domain'],
        'size': args['size'],
        'location': args.get('datacenter'),
        'ssh_keys': ssh_keys,
        'post_uri': args.get('postinstall'),
        'os': args['os'],
        'hourly': args.get('billing') == 'hourly',
        'port_speed': args.get('port_speed'),
        'no_public': args.get('no_public') or False,
        'extras': args.get('extra'),
        'network': args.get('network'),
        'public_router': args.get('router_public', None),
        'private_router': args.get('router_private', None)
    }

    # 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'])
        env.fout('Successfully exported options to a template file.')
        return

    if do_create:
        if not (env.skip_confirmations or formatting.confirm(
                "This action will incur charges on your account. Continue?")):
            raise exceptions.CLIAbort('Aborting dedicated server order.')

        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

    env.fout(output)
Example #10
0
    def execute(self, args):
        template.update_with_template_args(args, list_args=['--disk', '--key'])
        vsi = SoftLayer.VSManager(self.client)
        self._update_with_like_args(args)
        self._validate_args(args)

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

        table = formatting.Table(['Item', 'cost'])
        table.align['Item'] = 'r'
        table.align['cost'] = 'r'
        data = self._parse_create_args(args)

        output = []
        if args.get('--test'):
            result = vsi.verify_create_instance(**data)
            total_monthly = 0.0
            total_hourly = 0.0

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

            for price in result['prices']:
                total_monthly += float(price.get('recurringFee', 0.0))
                total_hourly += float(price.get('hourlyRecurringFee', 0.0))
                if args.get('--hourly'):
                    rate = "%.2f" % float(price['hourlyRecurringFee'])
                else:
                    rate = "%.2f" % float(price['recurringFee'])

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

            if args.get('--hourly'):
                total = total_hourly
            else:
                total = total_monthly

            billing_rate = 'monthly'
            if args.get('--hourly'):
                billing_rate = 'hourly'
            table.add_row(['Total %s cost' % billing_rate, "%.2f" % total])
            output.append(table)
            output.append(formatting.FormattedItem(
                None,
                ' -- ! 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 args['--really'] or formatting.confirm(
                    "This action will incur charges on your account. "
                    "Continue?"):
                result = vsi.create_instance(**data)

                table = formatting.KeyValueTable(['name', 'value'])
                table.align['name'] = 'r'
                table.align['value'] = 'l'
                table.add_row(['id', result['id']])
                table.add_row(['created', result['createDate']])
                table.add_row(['guid', result['globalIdentifier']])
                output.append(table)

                if args.get('--wait'):
                    ready = vsi.wait_for_ready(
                        result['id'], int(args.get('--wait') or 1))
                    table.add_row(['ready', ready])
            else:
                raise exceptions.CLIAbort('Aborting virtual server order.')

        return output
Example #11
0
def cli(env, **args):
    """Order/create virtual servers."""
    vsi = SoftLayer.VSManager(env.client)
    _validate_args(env, args)

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

    table = formatting.Table(['Item', 'cost'])
    table.align['Item'] = 'r'
    table.align['cost'] = 'r'
    data = _parse_create_args(env.client, args)

    output = []
    if args.get('test'):
        result = vsi.verify_create_instance(**data)

        if result['presetId']:
            ordering_mgr = SoftLayer.OrderingManager(env.client)
            item_prices = ordering_mgr.get_item_prices(result['packageId'])
            preset_prices = ordering_mgr.get_preset_prices(result['presetId'])
            search_keys = ["guest_core", "ram"]
            for price in preset_prices['prices']:
                if price['item']['itemCategory'][
                        'categoryCode'] in search_keys:
                    item_key_name = price['item']['keyName']
                    _add_item_prices(item_key_name, item_prices, result)

        table = _build_receipt_table(result['prices'], args.get('billing'))

        output.append(table)
        output.append(
            formatting.FormattedItem(
                None, ' -- ! 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'])
        env.fout('Successfully exported options to a template file.')

    if do_create:
        if not (env.skip_confirmations or formatting.confirm(
                "This action will incur charges on your account. Continue?")):
            raise exceptions.CLIAbort('Aborting virtual server order.')

        result = vsi.create_instance(**data)

        table = formatting.KeyValueTable(['name', 'value'])
        table.align['name'] = 'r'
        table.align['value'] = 'l'
        table.add_row(['id', result['id']])
        table.add_row(['created', result['createDate']])
        table.add_row(['guid', result['globalIdentifier']])
        output.append(table)

        if args.get('wait'):
            ready = vsi.wait_for_ready(result['id'], args.get('wait') or 1)
            table.add_row(['ready', ready])
            if ready is False:
                env.out(env.fmt(output))
                raise exceptions.CLIHalt(code=1)

    env.fout(output)
Example #12
0
def cli(env, **args):
    """Order/create virtual servers."""
    vsi = SoftLayer.VSManager(env.client)
    _validate_args(env, args)

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

    table = formatting.Table(['Item', 'cost'])
    table.align['Item'] = 'r'
    table.align['cost'] = 'r'
    data = _parse_create_args(env.client, args)

    output = []
    if args.get('test'):
        result = vsi.verify_create_instance(**data)
        total_monthly = 0.0
        total_hourly = 0.0

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

        for price in result['prices']:
            total_monthly += float(price.get('recurringFee', 0.0))
            total_hourly += float(price.get('hourlyRecurringFee', 0.0))
            if args.get('billing') == 'hourly':
                rate = "%.2f" % float(price['hourlyRecurringFee'])
            elif args.get('billing') == 'monthly':
                rate = "%.2f" % float(price['recurringFee'])

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

        total = 0
        if args.get('billing') == 'hourly':
            total = total_hourly
        elif args.get('billing') == 'monthly':
            total = total_monthly

        billing_rate = 'monthly'
        if args.get('billing') == 'hourly':
            billing_rate = 'hourly'
        table.add_row(['Total %s cost' % billing_rate, "%.2f" % total])
        output.append(table)
        output.append(
            formatting.FormattedItem(
                None, ' -- ! 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'])
        env.fout('Successfully exported options to a template file.')

    if do_create:
        if not (env.skip_confirmations or formatting.confirm(
                "This action will incur charges on your account. Continue?")):
            raise exceptions.CLIAbort('Aborting virtual server order.')

        result = vsi.create_instance(**data)

        table = formatting.KeyValueTable(['name', 'value'])
        table.align['name'] = 'r'
        table.align['value'] = 'l'
        table.add_row(['id', result['id']])
        table.add_row(['created', result['createDate']])
        table.add_row(['guid', result['globalIdentifier']])
        output.append(table)

        if args.get('wait'):
            ready = vsi.wait_for_ready(result['id'], args.get('wait') or 1)
            table.add_row(['ready', ready])
            if ready is False:
                env.out(env.fmt(output))
                raise exceptions.CLIHalt(code=1)

    env.fout(output)
Example #13
0
def cli(env, **kwargs):
    """Order/create a dedicated host."""
    mgr = SoftLayer.DedicatedHostManager(env.client)

    order = {
        'hostname': kwargs['hostname'],
        'domain': kwargs['domain'],
        'flavor': kwargs['flavor'],
        'location': kwargs['datacenter'],
        'hourly': kwargs.get('billing') == 'hourly',
    }

    if kwargs['router']:
        order['router'] = kwargs['router']

    do_create = not (kwargs['export'] or kwargs['verify'])

    output = None

    result = mgr.verify_order(**order)
    table = formatting.Table(['Item', 'cost'])
    table.align['Item'] = 'r'
    table.align['cost'] = 'r'
    if len(result['prices']) != 1:
        raise exceptions.ArgumentError("More than 1 price was found or no "
                                       "prices found")
    price = result['prices']
    if order['hourly']:
        total = float(price[0].get('hourlyRecurringFee', 0.0))
    else:
        total = float(price[0].get('recurringFee', 0.0))

    if order['hourly']:
        table.add_row(['Total hourly cost', "%.2f" % total])
    else:
        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 kwargs['export']:
        export_file = kwargs.pop('export')
        template.export_to_template(export_file,
                                    kwargs,
                                    exclude=['wait', 'verify'])
        env.fout('Successfully exported options to a template file.')

    if do_create:
        if not env.skip_confirmations and not formatting.confirm(
                "This action will incur charges on your account. "
                "Continue?"):
            raise exceptions.CLIAbort('Aborting dedicated host order.')

        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.append(table)

    env.fout(output)
Example #14
0
def cli(env, **kwargs):
    """Order/create a dedicated host."""
    mgr = SoftLayer.DedicatedHostManager(env.client)

    order = {
        'hostname': kwargs['hostname'],
        'domain': kwargs['domain'],
        'flavor': kwargs['flavor'],
        'location': kwargs['datacenter'],
        'hourly': kwargs.get('billing') == 'hourly',
    }

    if kwargs['router']:
        order['router'] = kwargs['router']

    do_create = not (kwargs['export'] or kwargs['verify'])

    output = None

    result = mgr.verify_order(**order)
    table = formatting.Table(['Item', 'cost'])
    table.align['Item'] = 'r'
    table.align['cost'] = 'r'
    if len(result['prices']) != 1:
        raise exceptions.ArgumentError("More than 1 price was found or no "
                                       "prices found")
    price = result['prices']
    if order['hourly']:
        total = float(price[0].get('hourlyRecurringFee', 0.0))
    else:
        total = float(price[0].get('recurringFee', 0.0))

    if order['hourly']:
        table.add_row(['Total hourly cost', "%.2f" % total])
    else:
        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 kwargs['export']:
        export_file = kwargs.pop('export')
        template.export_to_template(export_file, kwargs,
                                    exclude=['wait', 'verify'])
        env.fout('Successfully exported options to a template file.')

    if do_create:
        if not env.skip_confirmations and not formatting.confirm(
                "This action will incur charges on your account. "
                "Continue?"):
            raise exceptions.CLIAbort('Aborting dedicated host order.')

        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.append(table)

    env.fout(output)