def execute(client, args):
        mgr = NetworkManager(client)

        version = 4
        if args.get('--v6'):
            version = 6
        if not args.get('--test') and not args['--really']:
            if not confirm("This action will incur charges on your account."
                           "Continue?"):
                raise CLIAbort('Cancelling order.')
        result = mgr.add_global_ip(version=version,
                                   test_order=args.get('--test'))
        if not result:
            return 'Unable to place order: No valid price IDs found.'
        t = Table(['Item', 'cost'])
        t.align['Item'] = 'r'
        t.align['cost'] = 'r'

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

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

        t.add_row(['Total monthly cost', "%.2f" % total])
        output = SequentialOutput()
        output.append(t)
        output.append(FormattedItem(
            '',
            ' -- ! Prices reflected here are retail and do not '
            'take account level discounts and are not guarenteed.')
        )
        return t
    def execute(self, args):
        update_with_template_args(args)
        mgr = HardwareManager(self.client)

        # Disks will be a comma-separated list. Let's make it a real list.
        if isinstance(args.get('--disk'), str):
            args['--disk'] = args.get('--disk').split(',')

        # Do the same thing for SSH keys
        if isinstance(args.get('--key'), str):
            args['--key'] = args.get('--key').split(',')

        self._validate_args(args)

        bmi_options = mgr.get_bare_metal_create_options()

        order = {
            'hostname': args['--hostname'],
            'domain': args['--domain'],
            'bare_metal': True,
        }

        # Validate the CPU/Memory combination and get the price ID
        server_core = self._get_cpu_and_memory_price_ids(bmi_options,
                                                         args['--cpu'],
                                                         args['--memory'])

        if server_core:
            order['server'] = server_core
        else:
            raise CLIAbort('Invalid CPU/memory combination specified.')

        order['hourly'] = args['--hourly']

        # Convert the OS code back into a price ID
        os_price = self._get_price_id_from_options(bmi_options, 'os',
                                                   args['--os'])

        if os_price:
            order['os'] = os_price
        else:
            raise CLIAbort('Invalid operating system specified.')

        order['location'] = args['--datacenter'] or 'FIRST_AVAILABLE'

        # Set the disk size
        disk_prices = []
        for disk in args.get('--disk'):
            disk_price = self._get_price_id_from_options(bmi_options, 'disk',
                                                         disk)

            if disk_price:
                disk_prices.append(disk_price)

        if not disk_prices:
            disk_prices.append(self._get_default_value(bmi_options, 'disk0'))

        order['disks'] = disk_prices

        # Set the port speed
        port_speed = args.get('--network') or 100

        nic_price = self._get_price_id_from_options(bmi_options, 'nic',
                                                    str(port_speed))

        if nic_price:
            order['port_speed'] = nic_price
        else:
            raise CLIAbort('Invalid network speed specified.')

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

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

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

        # Begin output
        table = Table(['Item', 'cost'])
        table.align['Item'] = 'r'
        table.align['cost'] = 'r'

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

            total_monthly = 0.0
            total_hourly = 0.0
            for price in result['prices']:
                monthly_fee = float(price.get('recurringFee', 0.0))
                hourly_fee = float(price.get('hourlyRecurringFee', 0.0))

                total_monthly += monthly_fee
                total_hourly += hourly_fee
                if args.get('--hourly'):
                    rate = "%.2f" % hourly_fee
                else:
                    rate = "%.2f" % monthly_fee

                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 = SequentialOutput()
            output.append(table)
            output.append(FormattedItem(
                '',
                ' -- ! Prices reflected here are retail and do not '
                'take account level discounts and are not guaranteed.')
            )
        elif args['--really'] or confirm(
                "This action will incur charges on your account. Continue?"):
            result = mgr.place_order(**order)

            table = 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 CLIAbort('Aborting bare metal instance order.')

        return output
Exemple #3
0
    def execute(self, args):
        update_with_template_args(args)
        mgr = HardwareManager(self.client)

        # Disks will be a comma-separated list. Let's make it a real list.
        if isinstance(args.get("--disk"), str):
            args["--disk"] = args.get("--disk").split(",")

        # Do the same thing for SSH keys
        if isinstance(args.get("--key"), str):
            args["--key"] = args.get("--key").split(",")

        self._validate_args(args)

        bmi_options = mgr.get_bare_metal_create_options()

        order = {"hostname": args["--hostname"], "domain": args["--domain"], "bare_metal": True}

        # Validate the CPU/Memory combination and get the price ID
        server_core = self._get_cpu_and_memory_price_ids(bmi_options, args["--cpu"], args["--memory"])

        if server_core:
            order["server"] = server_core
        else:
            raise CLIAbort("Invalid CPU/memory combination specified.")

        order["hourly"] = args["--hourly"]

        # Convert the OS code back into a price ID
        os_price = self._get_price_id_from_options(bmi_options, "os", args["--os"])

        if os_price:
            order["os"] = os_price
        else:
            raise CLIAbort("Invalid operating system specified.")

        order["location"] = args["--datacenter"] or "FIRST_AVAILABLE"

        # Set the disk size
        disk_prices = []
        for disk in args.get("--disk"):
            disk_price = self._get_price_id_from_options(bmi_options, "disk", disk)

            if disk_price:
                disk_prices.append(disk_price)

        if not disk_prices:
            disk_prices.append(self._get_default_value(bmi_options, "disk0"))

        order["disks"] = disk_prices

        # Set the port speed
        port_speed = args.get("--network") or 100

        nic_price = self._get_price_id_from_options(bmi_options, "nic", str(port_speed))

        if nic_price:
            order["port_speed"] = nic_price
        else:
            raise CLIAbort("Invalid network speed specified.")

        # Get the SSH keys
        if args.get("--key"):
            keys = []
            for key in args.get("--key"):
                key_id = resolve_id(SshKeyManager(self.client).resolve_ids, key, "SshKey")
                keys.append(key_id)
            order["ssh_keys"] = keys

        if args.get("--vlan_public"):
            order["public_vlan"] = args["--vlan_public"]

        if args.get("--vlan_private"):
            order["private_vlan"] = args["--vlan_private"]

        # Begin output
        t = Table(["Item", "cost"])
        t.align["Item"] = "r"
        t.align["cost"] = "r"

        if args.get("--test"):
            result = mgr.verify_order(**order)

            total_monthly = 0.0
            total_hourly = 0.0
            for price in result["prices"]:
                monthly_fee = float(price.get("recurringFee", 0.0))
                hourly_fee = float(price.get("hourlyRecurringFee", 0.0))

                total_monthly += monthly_fee
                total_hourly += hourly_fee
                if args.get("--hourly"):
                    rate = "%.2f" % hourly_fee
                else:
                    rate = "%.2f" % monthly_fee

                t.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"
            t.add_row(["Total %s cost" % billing_rate, "%.2f" % total])
            output = SequentialOutput()
            output.append(t)
            output.append(
                FormattedItem(
                    "",
                    " -- ! Prices reflected here are retail and do not "
                    "take account level discounts and are not guaranteed.",
                )
            )
        elif args["--really"] or confirm("This action will incur charges on your account. Continue?"):
            result = mgr.place_order(**order)

            t = KeyValueTable(["name", "value"])
            t.align["name"] = "r"
            t.align["value"] = "l"
            t.add_row(["id", result["orderId"]])
            t.add_row(["created", result["orderDate"]])
            output = t
        else:
            raise CLIAbort("Aborting bare metal instance order.")

        return output
    def execute(client, args):
        cci = CCIManager(client)

        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'])

        data = {
            "hourly": args['--hourly'],
            "cpus": args['--cpu'],
            "domain": args['--domain'],
            "hostname": args['--hostname'],
            "private": args['--private'],
            "local_disk": True,
        }

        try:
            memory = int(args['--memory'])
            if memory < 1024:
                memory = memory * 1024
        except ValueError:
            unit = args['--memory'][-1]
            memory = int(args['--memory'][0:-1])
            if unit in ['G', 'g']:
                memory = memory * 1024
            if unit in ['T', 'r']:
                memory = memory * 1024 * 1024

        data["memory"] = memory

        if args['--monthly']:
            data["hourly"] = False

        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'):
            f = open(args['--userfile'], 'r')
            try:
                data['userdata'] = f.read()
            finally:
                f.close()

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

        if args.get('--test'):
            result = cci.verify_create_instance(**data)
            total_monthly = 0.0
            total_hourly = 0.0
            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'])

                t.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'
            t.add_row(['Total %s cost' % billing_rate, "%.2f" % total])
            output = SequentialOutput(blanks=False)
            output.append(t)
            output.append(FormattedItem(
                '',
                ' -- ! Prices reflected here are retail and do not '
                'take account level discounts and are not guarenteed.')
            )

        elif args['--really'] or confirm(
                "This action will incur charges on your account. Continue?"):
            result = cci.create_instance(**data)

            t = Table(['name', 'value'])
            t.align['name'] = 'r'
            t.align['value'] = 'l'
            t.add_row(['id', result['id']])
            t.add_row(['created', result['createDate']])
            t.add_row(['guid', result['globalIdentifier']])
            output = t
        else:
            raise CLIAbort('Aborting CCI order.')

        if args.get('--wait') or 0 and not args.get('--test'):
            ready = cci.wait_for_transaction(
                result['id'], int(args.get('--wait') or 1))
            t.add_row(['ready', ready])

        return output