Exemple #1
0
def cli(env, keyword, package_type):
    """List packages that can be ordered via the placeOrder API.


    ::

        # List out all packages for ordering
        slcli order package-list

        # List out all packages with "server" in the name
        slcli order package-list --keyword server

        # Select only specifict package types
        slcli order package-list --package_type BARE_METAL_CPU
    """
    manager = ordering.OrderingManager(env.client)
    table = formatting.Table(COLUMNS)

    _filter = {'type': {'keyName': {'operation': '!= BLUEMIX_SERVICE'}}}
    if keyword:
        _filter['name'] = {'operation': '*= %s' % keyword}
    if package_type:
        _filter['type'] = {'keyName': {'operation': package_type}}

    packages = manager.list_packages(filter=_filter)

    for package in packages:
        table.add_row([
            package['id'], package['name'], package['keyName'],
            package['type']['keyName']
        ])
    env.fout(table)
def cli(env, package_keyname):
    """List Datacenters a package can be ordered in.

    Use the location Key Name to place orders
    """
    manager = ordering.OrderingManager(env.client)
    network_manager = network.NetworkManager(env.client)

    pods = network_manager.get_closed_pods()
    table = formatting.Table(COLUMNS)

    locations = manager.package_locations(package_keyname)
    for region in locations:
        for datacenter in region['locations']:
            closure = []
            for pod in pods:
                if datacenter['location']['name'] in str(pod['name']):
                    closure.append(pod['name'])

            notes = '-'
            if len(closure) > 0:
                notes = 'closed soon: %s' % (', '.join(closure))
            table.add_row([
                datacenter['location']['id'], datacenter['location']['name'],
                region['description'], region['keyname'], notes
            ])
    env.fout(table)
def cli(env, quote):
    """View a quote"""

    manager = ordering.OrderingManager(env.client)
    result = manager.get_quote_details(quote)

    package = result['order']['items'][0]['package']
    title = "{} - Package: {}, Id {}".format(result.get('name'),
                                             package['keyName'], package['id'])
    table = formatting.Table(
        ['Category', 'Description', 'Quantity', 'Recurring', 'One Time'],
        title=title)
    table.align['Category'] = 'l'
    table.align['Description'] = 'l'

    items = lookup(result, 'order', 'items')
    for item in items:
        table.add_row([
            item.get('categoryCode'),
            item.get('description'),
            item.get('quantity'),
            item.get('recurringFee'),
            item.get('oneTimeFee')
        ])

    env.fout(table)
def cli(env, package_keyname, required):
    """List the categories of a package.

    ::

        # List the categories of Bare Metal servers
        slcli order category-list BARE_METAL_SERVER

        # List the required categories for Bare Metal servers
        slcli order category-list BARE_METAL_SERVER --required

    """
    client = env.client
    manager = ordering.OrderingManager(client)
    table = formatting.Table(COLUMNS)

    categories = manager.list_categories(package_keyname)

    if required:
        categories = [cat for cat in categories if cat['isRequired']]

    for cat in categories:
        table.add_row([
            cat['itemCategory']['name'],
            cat['itemCategory']['categoryCode'],
            'Y' if cat['isRequired'] else 'N'
        ])

    env.fout(table)
Exemple #5
0
def cli(env, package_keyname, required):
    """List the categories of a package.

    Package keynames can be retrieved from `slcli order package-list`

    \b
    Example:
        # List the categories of Bare Metal servers
        slcli order category-list BARE_METAL_SERVER

    When using the --required flag, it will list out only the categories
    that are required for ordering that package (see `slcli order item-list`)

    \b
    Example:
        # List the required categories for Bare Metal servers
        slcli order category-list BARE_METAL_SERVER --required

    """
    client = env.client
    manager = ordering.OrderingManager(client)
    table = formatting.Table(COLUMNS)

    categories = manager.list_categories(package_keyname)

    if required:
        categories = [cat for cat in categories if cat['isRequired']]

    for cat in categories:
        table.add_row([
            cat['itemCategory']['name'], cat['itemCategory']['categoryCode'],
            'Y' if cat['isRequired'] else 'N'
        ])

    env.fout(table)
def cli(env, package_keyname, keyword):
    """List package presets.

    Package keynames can be retrieved from `slcli order package-list`.
    Some packages do not have presets.

    \b
    Example:
        # List the presets for Bare Metal servers
        slcli order preset-list BARE_METAL_SERVER

    The --keyword option can also be used for additional filtering on
    the returned presets.

    \b
    Example:
        # List the Bare Metal server presets that include a GPU
        slcli order preset-list BARE_METAL_SERVER --keyword gpu

    """
    table = formatting.Table(COLUMNS)
    manager = ordering.OrderingManager(env.client)

    _filter = {}
    if keyword:
        _filter = {'activePresets': {'name': {'operation': '*= %s' % keyword}}}
    presets = manager.list_presets(package_keyname, filter=_filter)

    for preset in presets:
        table.add_row(
            [preset['name'], preset['keyName'], preset['description']])
    env.fout(table)
    def __init__(self, client, ordering_manager=None):
        self.client = client
        self.account = client['Account']
        self.host = client['Virtual_DedicatedHost']

        if ordering_manager is None:
            self.ordering_manager = ordering.OrderingManager(client)
Exemple #8
0
def cli(env, package_keyname, keyword):
    """List package presets.

    .. Note::
        Presets are set CPU / RAM / Disk allotments. You still need to specify required items.
        Some packages do not have presets.

    ::

        # List the presets for Bare Metal servers
        slcli order preset-list BARE_METAL_SERVER

        # List the Bare Metal server presets that include a GPU
        slcli order preset-list BARE_METAL_SERVER --keyword gpu

    """
    table = formatting.Table(COLUMNS)
    manager = ordering.OrderingManager(env.client)

    _filter = {}
    if keyword:
        _filter = {'activePresets': {'name': {'operation': '*= %s' % keyword}}}
    presets = manager.list_presets(package_keyname, filter=_filter)

    for preset in presets:
        table.add_row([
            str(preset['name']).strip(),
            str(preset['keyName']).strip(),
            str(preset['description']).strip()
        ])
    env.fout(table)
    def __init__(self, client, ordering_manager=None):
        self.client = client
        self.account = client['Account']
        self.capacity_package = 'RESERVED_CAPACITY'
        self.rcg_service = 'Virtual_ReservedCapacityGroup'

        if ordering_manager is None:
            self.ordering_manager = ordering.OrderingManager(client)
Exemple #10
0
 def getOrderObject(self, dc, items, extras, quantity=1):
     """Uses the ordering manager to build a order object"""
     om = ordering.OrderingManager(self.client)
     order = om.generate_order(self.package_keyname, dc, items,
                               self.complex_type, False, None, extras,
                               quantity)
     # pp(order)
     return order
Exemple #11
0
def cli(env, package_keyname, keyword, prices):
    """List package presets.

    .. Note::
        Presets are set CPU / RAM / Disk allotments. You still need to specify required items.
        Some packages do not have presets.

    ::

        # List the presets for Bare Metal servers
        slcli order preset-list BARE_METAL_SERVER

        # List the Bare Metal server presets that include a GPU
        slcli order preset-list BARE_METAL_SERVER --keyword gpu

    """
    manager = ordering.OrderingManager(env.client)

    _filter = {}
    if keyword:
        _filter = {'activePresets': {'name': {'operation': '*= %s' % keyword}}}
    presets = manager.list_presets(package_keyname, filter=_filter)

    if prices:
        table = formatting.Table([
            'keyName', 'priceId', 'Hourly', 'Monthly', 'Restriction',
            'Location'
        ])
        for price in presets:
            locations = []
            if price['locations'] != []:
                for location in price['locations']:
                    locations.append(location['name'])
            cr_max = get_item_price_data(price['prices'][0],
                                         'capacityRestrictionMaximum')
            cr_min = get_item_price_data(price['prices'][0],
                                         'capacityRestrictionMinimum')
            cr_type = get_item_price_data(price['prices'][0],
                                          'capacityRestrictionType')
            table.add_row([
                price['keyName'], price['id'],
                get_item_price_data(price['prices'][0], 'hourlyRecurringFee'),
                get_item_price_data(price['prices'][0], 'recurringFee'),
                "%s - %s %s" % (cr_min, cr_max, cr_type),
                str(locations)
            ])

    else:
        table = formatting.Table(COLUMNS)
        for preset in presets:
            table.add_row([
                str(preset['name']).strip(),
                str(preset['keyName']).strip(),
                str(preset['description']).strip()
            ])

    env.fout(table)
Exemple #12
0
 def __init__(self, client, ordering_manager=None):
     self.client = client
     self.account = client['Account']
     self.guest = client['Virtual_Guest']
     self.resolvers = [self._get_ids_from_ip, self._get_ids_from_hostname]
     if ordering_manager is None:
         self.ordering_manager = ordering.OrderingManager(client)
     else:
         self.ordering_manager = ordering_manager
Exemple #13
0
 def __init__(self, client, ordering_manager=None):
     self.client = client
     self.hardware = self.client['Hardware_Server']
     self.account = self.client['Account']
     self.resolvers = [self._get_ids_from_ip, self._get_ids_from_hostname]
     if ordering_manager is None:
         self.ordering_manager = ordering.OrderingManager(client)
     else:
         self.ordering_manager = ordering_manager
Exemple #14
0
 def datacenterList(self):
     """Prints a list of dcs and their ids"""
     om = ordering.OrderingManager(self.client)
     locations = om.package_locations(self.package_keyname)
     print("ID, name, longName")
     for region in locations:
         for location in region['locations']:
             if location['locationPackageDetails'][0]['isAvailable'] == 1:
                 dc = location['location']
                 print("%s, %s, %s" %
                       (dc['id'], dc['name'], dc['longName']))
Exemple #15
0
 def __init__(self, client, ordering_manager=None):
     self.client = client
     self.account = client['Account']
     self.guest = client['Virtual_Guest']
     self.package_svc = client['Product_Package']
     self.storage_iscsi = client['SoftLayer_Network_Storage_Iscsi']
     self.resolvers = [self._get_ids_from_ip, self._get_ids_from_hostname]
     if ordering_manager is None:
         self.ordering_manager = ordering.OrderingManager(client)
     else:
         self.ordering_manager = ordering_manager
Exemple #16
0
def cli(env, package_keyname, keyword, category):
    """List package items used for ordering.

    The items listed can be used with `slcli order place` to specify
    the items that are being ordered in the package.

    Package keynames can be retrieved using `slcli order package-list`

    \b
    Note:
        Items with a numbered category, like disk0 or gpu0, can be included
        multiple times in an order to match how many of the item you want to order.

    \b
    Example:
        # List all items in the VSI package
        slcli order item-list CLOUD_SERVER

    The --keyword option is used to filter items by name.

    The --category option is used to filter items by category.

    Both --keyword and --category can be used together.

    \b
    Example:
        # List Ubuntu OSes from the os category of the Bare Metal package
        slcli order item-list BARE_METAL_SERVER --category os --keyword ubuntu

    """
    table = formatting.Table(COLUMNS)
    manager = ordering.OrderingManager(env.client)

    _filter = {'items': {}}
    if keyword:
        _filter['items']['description'] = {'operation': '*= %s' % keyword}
    if category:
        _filter['items']['categories'] = {
            'categoryCode': {
                'operation': '_= %s' % category
            }
        }

    items = manager.list_items(package_keyname, filter=_filter)
    sorted_items = sort_items(items)

    categories = sorted_items.keys()
    for catname in sorted(categories):
        for item in sorted_items[catname]:
            table.add_row([
                catname, item['keyName'], item['description'],
                get_price(item)
            ])
    env.fout(table)
Exemple #17
0
    def order_lbaas(self,
                    datacenter,
                    name,
                    desc,
                    protocols,
                    subnet_id,
                    public=False,
                    verify=False):
        """Allows to order a Load Balancer

        :param datacenter: Shortname for the SoftLayer datacenter to order in.
        :param name: Identifier for the new LB.
        :param desc: Optional description for the lb.
        :param protocols:  https://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_LBaaS_Listener/
        :param subnet_id: Id of the subnet for this new LB to live on.
        :param public: Use Public side for the backend.
        :param verify: Don't actually order if True.
        """
        order_mgr = ordering.OrderingManager(self.client)

        package = order_mgr.get_package_by_key(
            self.package_keyname, mask='mask[id,keyName,itemPrices]')

        prices = []
        for price in package.get('itemPrices'):
            if not price.get('locationGroupId', False):
                prices.append(price.get('id'))

        # Build the configuration of the order
        order_data = {
            'complexType':
            'SoftLayer_Container_Product_Order_Network_LoadBalancer_AsAService',
            'name': name,
            'description': desc,
            'location': datacenter,
            'packageId': package.get('id'),
            'useHourlyPricing':
            True,  # Required since LBaaS is an hourly service
            'prices': [{
                'id': price_id
            } for price_id in prices],
            'protocolConfigurations': protocols,
            'subnets': [{
                'id': subnet_id
            }],
            'isPublic': public
        }

        if verify:
            response = self.client['Product_Order'].verifyOrder(order_data)
        else:
            response = self.client['Product_Order'].placeOrder(order_data)
        return response
Exemple #18
0
def cli(env, package_keyname, keyword, category, prices, location=None):
    """List package items used for ordering.

    The item keyNames listed can be used with `slcli order place` to specify
    the items that are being ordered in the package.

    .. Note::
        Items with a numbered category, like disk0 or gpu0, can be included
        multiple times in an order to match how many of the item you want to order.

    ::

        # List all items in the VSI package
        slcli order item-list CLOUD_SERVER

        # List Ubuntu OSes from the os category of the Bare Metal package
        slcli order item-list BARE_METAL_SERVER --category os --keyword ubuntu

    """
    manager = ordering.OrderingManager(env.client)

    tables = []

    _filter = {'items': {}}
    if keyword:
        _filter['items']['description'] = {'operation': '*= %s' % keyword}
    if category:
        _filter['items']['categories'] = {
            'categoryCode': {
                'operation': '_= %s' % category
            }
        }

    items = manager.list_items(package_keyname, filter=_filter)
    sorted_items = sort_items(items)

    categories = sorted_items.keys()
    if prices:
        _item_list_prices(categories, sorted_items, tables)
        if location:
            location_prices = manager.get_item_prices_by_location(
                location, package_keyname)
            _location_item_prices(location_prices, location, tables)
    else:
        table_items_detail = formatting.Table(COLUMNS)
        for category_name in sorted(categories):
            for item in sorted_items[category_name]:
                table_items_detail.add_row([
                    category_name, item['keyName'], item['description'],
                    get_price(item)
                ])
        tables.append(table_items_detail)
    env.fout(formatting.listing(tables, separator='\n'))
Exemple #19
0
    def create(self, datacenter, item_package):
        """Create a license

        :param string datacenter: the datacenter shortname
        :param string[] item_package: items array
        """
        complex_type = 'SoftLayer_Container_Product_Order_Software_License'
        ordering_manager = ordering.OrderingManager(self.client)
        return ordering_manager.place_order(
            package_keyname='SOFTWARE_LICENSE_PACKAGE',
            location=datacenter,
            item_keynames=item_package,
            complex_type=complex_type,
            hourly=False)
Exemple #20
0
    def orderVyattaHA(self, dc, pub_vlan='', prv_vlan=''):
        order_svc = self.client['Product_Order']
        om = ordering.OrderingManager(self.client)

        order_items = self.itemKeynameList()

        extras = {}
        extras['hardware'] = [
            self.generateHardwareEntry('vyatta1', 'test.com', pub_vlan,
                                       prv_vlan, 'vyatta1 Test'),
            self.generateHardwareEntry('vyatta2', 'test.com', pub_vlan,
                                       prv_vlan, 'vyatta2 Test')
        ]
        extras['storageGroups'] = [self.generateRaidEntry()]
        mySshKey = 87634
        extras['sshKeys'] = [{
            'sshKeyIds': [mySshKey]
        }, {
            'sshKeyIds': [mySshKey]
        }]
        # Each server needs a provision script
        extras['provisionScripts'] = [
            'https://raw.githubusercontent.com/softlayer/softlayer.github.io/master/provision-test.sh',
            'https://raw.githubusercontent.com/softlayer/softlayer.github.io/master/provision-test.sh'
        ]
        extras['clusterIdentifier'] = 'myTestClusterOfVyattas'

        vyatta_order = self.getOrderObject(dc, order_items, extras, 2)

        cluster_extras = {
            'clusterIdentifier': 'myTestClusterOfVyattas',
            "sshKeys": [{
                "sshKeyIds": [mySshKey]
            }]
        }
        cluster_type = "SoftLayer_Container_Product_Order_Gateway_Appliance_Cluster"
        cluster_object = om.generate_order('NETWORK_GATEWAY_APPLIANCE_CLUSTER',
                                           dc, ['GATEWAY_APPLIANCE_CLUSTER'],
                                           cluster_type, False, None,
                                           cluster_extras, 1)
        # the cluster order object is a bit special, and we need to remove these for it to work properly
        del cluster_object['location']
        del cluster_object['useHourlyPricing']
        order_object = {'orderContainers': [vyatta_order, cluster_object]}

        verify = order_svc.verifyOrder(order_object)
        # verify = order_svc.placeOrder(order_object)
        pp(verify)
        print("done")
Exemple #21
0
def cli(env, identifier, details):
    """Provides some details related to order owner, date order, cost information, initial invoice."""

    manager = ordering.OrderingManager(env.client)
    order = manager.get_order_detail(identifier)
    order_table = get_order_table(order)

    invoice = order.get('initialInvoice', {})
    top_items = invoice.get('invoiceTopLevelItems', [])
    invoice_id = invoice.get('id')
    invoice_table = get_invoice_table(invoice_id, top_items, details)

    order_table.add_row(['Initial Invoice', invoice_table])

    env.fout(order_table)
def cli(env, quote, **args):
    """View and Order a quote

    \f
    :note:
        The hostname and domain are split out from the fully qualified domain name.

        If you want to order multiple servers, you need to specify each FQDN. Postinstall, userdata, and
        sshkeys are applied to all servers in an order.

    ::

        slcli order quote 12345 --fqdn testing.tester.com \\
            --complex-type SoftLayer_Container_Product_Order_Virtual_Guest -k sshKeyNameLabel\\
            -i https://domain.com/runthis.sh --userdata DataGoesHere

    """
    table = formatting.Table(['Id', 'Name', 'Created', 'Expiration', 'Status'])
    create_args = _parse_create_args(env.client, args)

    manager = ordering.OrderingManager(env.client)
    quote_details = manager.get_quote_details(quote)

    package = quote_details['order']['items'][0]['package']
    create_args['packageId'] = package['id']

    if args.get('verify'):
        result = manager.verify_quote(quote, create_args)
        verify_table = formatting.Table(['keyName', 'description', 'cost'])
        verify_table.align['keyName'] = 'l'
        verify_table.align['description'] = 'l'
        for price in result['prices']:
            cost_key = 'hourlyRecurringFee' if result[
                'useHourlyPricing'] is True else 'recurringFee'
            verify_table.add_row([
                price['item']['keyName'], price['item']['description'],
                price[cost_key] if cost_key in price else formatting.blank()
            ])
        env.fout(verify_table)
    else:
        result = manager.order_quote(quote, create_args)
        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']])
        table.add_row(['status', result['placedOrder']['status']])
        env.fout(table)
Exemple #23
0
def cli(env, package_keyname):
    """List Datacenters a package can be ordered in.

    Use the location Key Name to place orders
    """
    manager = ordering.OrderingManager(env.client)
    table = formatting.Table(COLUMNS)

    locations = manager.package_locations(package_keyname)
    for region in locations:
        for datacenter in region['locations']:
            table.add_row([
                datacenter['location']['id'], datacenter['location']['name'],
                region['description'], region['keyname']
            ])
    env.fout(table)
Exemple #24
0
def cli(env, quote):
    """Save a quote"""

    manager = ordering.OrderingManager(env.client)
    result = manager.save_quote(quote)

    table = formatting.Table(['Id', 'Name', 'Created', 'Modified', 'Status'])
    table.align['Name'] = 'l'

    table.add_row([
        result.get('id'),
        result.get('name'),
        clean_time(result.get('createDate')),
        clean_time(result.get('modifyDate')),
        result.get('status'),
    ])

    env.fout(table)
Exemple #25
0
def cli(env, name, datacenter, pod, network, billing):
    """Order/create a VLAN instance."""

    item_package = ['PUBLIC_NETWORK_VLAN']
    complex_type = 'SoftLayer_Container_Product_Order_Network_Vlan'
    extras = {'name': name}
    if pod:
        datacenter = pod.split('.')[0]
        mgr = SoftLayer.NetworkManager(env.client)
        pods = mgr.get_pods()
        for router in pods:
            if router.get('name') == pod:
                if network == 'public':
                    extras['routerId'] = router.get('frontendRouterId')
                elif network == 'private':
                    extras['routerId'] = router.get('backendRouterId')
                break
        if not extras.get('routerId'):
            raise exceptions.CLIAbort(
                "Unable to find pod name: {}".format(pod))
    if network == 'private':
        item_package = ['PRIVATE_NETWORK_VLAN']

    ordering_manager = ordering.OrderingManager(env.client)
    result = ordering_manager.place_order(package_keyname='NETWORK_VLAN',
                                          location=datacenter,
                                          item_keynames=item_package,
                                          complex_type=complex_type,
                                          hourly=billing,
                                          extras=extras)
    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']])
    table.add_row(
        ['name', result['orderDetails']['orderContainers'][0]['name']])

    env.fout(table)
def cli(env, keyword, package_type):
    """List packages that can be ordered via the placeOrder API.

    \b
    Example:
        # List out all packages for ordering
        slcli order package-list


    Keywords can also be used for some simple filtering functionality
    to help find a package easier.

    \b
    Example:
        # List out all packages with "server" in the name
        slcli order package-list --keyword server

    Package types can be used to remove unwanted packages
    \b
    Example:
        slcli order package-list --package_type BARE_METAL_CPU
    """
    manager = ordering.OrderingManager(env.client)
    table = formatting.Table(COLUMNS)

    _filter = {'type': {'keyName': {'operation': '!= BLUEMIX_SERVICE'}}}
    if keyword:
        _filter['name'] = {'operation': '*= %s' % keyword}
    if package_type:
        _filter['type'] = {'keyName': {'operation': package_type}}

    packages = manager.list_packages(filter=_filter)

    for package in packages:
        table.add_row([
            package['id'], package['name'], package['keyName'],
            package['type']['keyName']
        ])
    env.fout(table)
def cli(env):
    """List all active quotes on an account"""
    table = formatting.Table([
        'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id'
    ])
    table.align['Name'] = 'l'
    table.align['Package Name'] = 'r'
    table.align['Package Id'] = 'l'

    manager = ordering.OrderingManager(env.client)
    items = manager.get_quotes()

    for item in items:
        package = item['order']['items'][0]['package']
        table.add_row([
            item.get('id'),
            item.get('name'),
            clean_time(item.get('createDate')),
            clean_time(item.get('modifyDate')),
            item.get('status'),
            package.get('keyName'),
            package.get('id')
        ])
    env.fout(table)
Exemple #28
0
def cli(env, package_keyname, location, preset, verify, billing, complex_type,
        quantity, extras, order_items):
    """Place or verify an order.

\b
1. Find the package keyName from `slcli order package-list`
2. Find the location from `slcli order package-locations PUBLIC_CLOUD_SERVER`
  If the package does not require a location, use 'NONE' instead.
3. Find the needed items `slcli order item-list PUBLIC_CLOUD_SERVER`
  Some packages, like PUBLIC_CLOUD_SERVER need presets, `slcli order preset-list PUBLIC_CLOUD_SERVER`
4. Find the complex type from https://sldn.softlayer.com/reference
5. Use that complex type to fill out any --extras

    Example::

        slcli order place --verify --preset B1_2X8X100 --billing hourly
        --complex-type SoftLayer_Container_Product_Order_Virtual_Guest
        --extras '{"virtualGuests": [{"hostname": "test", "domain": "ibm.com"}]}'
        PUBLIC_CLOUD_SERVER DALLAS13
        BANDWIDTH_0_GB_2 MONITORING_HOST_PING NOTIFICATION_EMAIL_AND_TICKET
        OS_DEBIAN_9_X_STRETCH_LAMP_64_BIT 1_IP_ADDRESS 1_IPV6_ADDRESS
        1_GBPS_PUBLIC_PRIVATE_NETWORK_UPLINKS REBOOT_REMOTE_CONSOLE
        AUTOMATED_NOTIFICATION UNLIMITED_SSL_VPN_USERS_1_PPTP_VPN_USER_PER_ACCOUNT

    """
    manager = ordering.OrderingManager(env.client)
    network = NetworkManager(env.client)

    pods = network.get_closed_pods()
    closure = []

    if extras:
        try:
            extras = json.loads(extras)
        except ValueError as err:
            raise exceptions.CLIAbort(
                "There was an error when parsing the --extras value: {}".
                format(err))

    args = (package_keyname, location, order_items)
    kwargs = {
        'preset_keyname': preset,
        'extras': extras,
        'quantity': quantity,
        'complex_type': complex_type,
        'hourly': bool(billing == 'hourly')
    }

    if verify:
        table = formatting.Table(COLUMNS)
        order_to_place = manager.verify_order(*args, **kwargs)
        for price in order_to_place['orderContainers'][0]['prices']:
            cost_key = 'hourlyRecurringFee' if billing == 'hourly' else 'recurringFee'
            table.add_row([
                price['item']['keyName'], price['item']['description'],
                price[cost_key] if cost_key in price else formatting.blank()
            ])

    else:
        for pod in pods:
            closure.append(pod['name'])
        click.secho(
            click.style('Warning: Closed soon: %s' % (', '.join(closure)),
                        fg='yellow'))
        if not (env.skip_confirmations or formatting.confirm(
                "This action will incur charges on your account. Continue?")):
            raise exceptions.CLIAbort("Aborting order.")

        order = manager.place_order(*args, **kwargs)

        table = formatting.KeyValueTable(['name', 'value'])
        table.align['name'] = 'r'
        table.align['value'] = 'l'
        table.add_row(['id', order['orderId']])
        table.add_row(['created', order['orderDate']])
        table.add_row(['status', order['placedOrder']['status']])
    env.fout(table)
def cli(env, package_keyname, location, preset, name, send_email, complex_type,
        extras, order_items):
    """Place a quote.

    This CLI command is used for creating  a quote of the specified package in
    the given location (denoted by a datacenter's long name). Orders made via the CLI
    can then be converted to be made programmatically by calling
    SoftLayer.OrderingManager.place_quote() with the same keynames.

    Packages for ordering can be retrieved from `slcli order package-list`
    Presets for ordering can be retrieved from `slcli order preset-list` (not all packages
    have presets)

    Items can be retrieved from `slcli order item-list`. In order to find required
    items for the order, use `slcli order category-list`, and then provide the
    --category option for each category code in `slcli order item-list`.


    Example::

        # Place quote a VSI with 4 CPU, 16 GB RAM, 100 GB SAN disk,
        # Ubuntu 16.04, and 1 Gbps public & private uplink in dal13
        slcli order place-quote --name "foobar" --send-email CLOUD_SERVER DALLAS13 \\
            GUEST_CORES_4 \\
            RAM_16_GB \\
            REBOOT_REMOTE_CONSOLE \\
            1_GBPS_PUBLIC_PRIVATE_NETWORK_UPLINKS \\
            BANDWIDTH_0_GB_2 \\
            1_IP_ADDRESS \\
            GUEST_DISK_100_GB_SAN \\
            OS_UBUNTU_16_04_LTS_XENIAL_XERUS_MINIMAL_64_BIT_FOR_VSI \\
            MONITORING_HOST_PING \\
            NOTIFICATION_EMAIL_AND_TICKET \\
            AUTOMATED_NOTIFICATION \\
            UNLIMITED_SSL_VPN_USERS_1_PPTP_VPN_USER_PER_ACCOUNT \\
            --extras '{"virtualGuests": [{"hostname": "test", "domain": "softlayer.com"}]}' \\
            --complex-type SoftLayer_Container_Product_Order_Virtual_Guest

    """
    manager = ordering.OrderingManager(env.client)

    if extras:
        try:
            extras = json.loads(extras)
        except ValueError as err:
            raise exceptions.CLIAbort("There was an error when parsing the --extras value: {}".format(err))

    args = (package_keyname, location, order_items)
    kwargs = {'preset_keyname': preset,
              'extras': extras,
              'quantity': 1,
              'quote_name': name,
              'send_email': send_email,
              'complex_type': complex_type}

    order = manager.place_quote(*args, **kwargs)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'
    table.add_row(['id', order['quote']['id']])
    table.add_row(['name', order['quote']['name']])
    table.add_row(['created', order['orderDate']])
    table.add_row(['expires', order['quote']['expirationDate']])
    table.add_row(['status', order['quote']['status']])
    env.fout(table)
Exemple #30
0
def cli(env, package_keyname, location, preset, verify, billing, complex_type,
        extras, order_items):
    """Place or verify an order.

    This CLI command is used for placing/verifying an order of the specified package in
    the given location (denoted by a datacenter's long name). Orders made via the CLI
    can then be converted to be made programmatically by calling
    SoftLayer.OrderingManager.place_order() with the same keynames.

    Packages for ordering can be retrived from `slcli order package-list`
    Presets for ordering can be retrieved from `slcli order preset-list` (not all packages
    have presets)

    Items can be retrieved from `slcli order item-list`. In order to find required
    items for the order, use `slcli order category-list`, and then provide the
    --category option for each category code in `slcli order item-list`.

    \b
    Example:
        # Order an hourly VSI with 4 CPU, 16 GB RAM, 100 GB SAN disk,
        # Ubuntu 16.04, and 1 Gbps public & private uplink in dal13
        slcli order place --billing hourly CLOUD_SERVER DALLAS13 \\
            GUEST_CORES_4 \\
            RAM_16_GB \\
            REBOOT_REMOTE_CONSOLE \\
            1_GBPS_PUBLIC_PRIVATE_NETWORK_UPLINKS \\
            BANDWIDTH_0_GB_2 \\
            1_IP_ADDRESS \\
            GUEST_DISK_100_GB_SAN \\
            OS_UBUNTU_16_04_LTS_XENIAL_XERUS_MINIMAL_64_BIT_FOR_VSI \\
            MONITORING_HOST_PING \\
            NOTIFICATION_EMAIL_AND_TICKET \\
            AUTOMATED_NOTIFICATION \\
            UNLIMITED_SSL_VPN_USERS_1_PPTP_VPN_USER_PER_ACCOUNT \\
            NESSUS_VULNERABILITY_ASSESSMENT_REPORTING \\
            --extras '{"virtualGuests": [{"hostname": "test", "domain": "softlayer.com"}]}' \\
            --complex-type SoftLayer_Container_Product_Order_Virtual_Guest

    """
    manager = ordering.OrderingManager(env.client)

    if extras:
        extras = json.loads(extras)

    args = (package_keyname, location, order_items)
    kwargs = {
        'preset_keyname': preset,
        'extras': extras,
        'quantity': 1,
        'complex_type': complex_type,
        'hourly': True if billing == 'hourly' else False
    }

    if verify:
        table = formatting.Table(COLUMNS)
        order_to_place = manager.verify_order(*args, **kwargs)
        for price in order_to_place['orderContainers'][0]['prices']:
            cost_key = 'hourlyRecurringFee' if billing == 'hourly' else 'recurringFee'
            table.add_row([
                price['item']['keyName'], price['item']['description'],
                price[cost_key] if cost_key in price else formatting.blank()
            ])

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

        order = manager.place_order(*args, **kwargs)

        table = formatting.KeyValueTable(['name', 'value'])
        table.align['name'] = 'r'
        table.align['value'] = 'l'
        table.add_row(['id', order['orderId']])
        table.add_row(['created', order['orderDate']])
        table.add_row(['status', order['placedOrder']['status']])
    env.fout(table)