Ejemplo n.º 1
0
    def execute(self, args):
        mgr = NetworkManager(self.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.'
        table = Table(['Item', 'cost'])
        table.align['Item'] = 'r'
        table.align['cost'] = 'r'

        total = 0.0
        for price in result['orderDetails']['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])
        return table
Ejemplo n.º 2
0
    def execute(self, args):
        mgr = FirewallManager(self.client)
        input_id = resolve_id(
            mgr.resolve_ids, args.get('<identifier>'), 'firewall')
        ha_support = args.get('--ha', False)
        if not args['--really']:
            if args['--vlan']:
                pkg = mgr.get_dedicated_package(ha_enabled=ha_support)
            elif args['--cci']:
                pkg = mgr.get_standard_package(input_id)
            elif args['--server']:
                pkg = mgr.get_standard_package(input_id, is_cci=False)

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

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

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

        return "Firewall is being created!"
Ejemplo n.º 3
0
    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(cls, client, args):
        username = cls.env.input('Username: '******'API Key: ')
        endpoint_url = cls.env.input(
            'Endpoint URL [%s]: ' % cls.env.config['endpoint_url'])
        if not endpoint_url:
            endpoint_url = cls.env.config['endpoint_url']

        path = '~/.softlayer'
        if args.get('--config'):
            path = args.get('--config')

        config_path = os.path.expanduser(path)
        c = confirm(
            'Are you sure you want to write settings to "%s"?' % config_path)

        if not c:
            raise CLIAbort('Aborted.')

        config = ConfigParser.RawConfigParser()
        config.add_section('softlayer')
        if username:
            config.set('softlayer', 'username', username)

        if api_key:
            config.set('softlayer', 'api_key', api_key)

        if endpoint_url:
            config.set('softlayer', 'endpoint_url', endpoint_url)

        f = open(config_path, 'w')
        try:
            config.write(f)
        finally:
            f.close()
Ejemplo n.º 5
0
 def execute(self, args):
     mgr = LoadBalancerManager(self.client)
     input_id = resolve_id(
         mgr.resolve_ids, args.get('<identifier>'), 'load_balancer')
     if not confirm("This action will incur charges on your account. "
                    "Continue?"):
         raise CLIAbort('Aborted.')
     mgr.add_local_lb(input_id, datacenter=args['--datacenter'])
     return "Load balancer is being created!"
Ejemplo n.º 6
0
    def execute(self, args):
        virtual_guest = self.client['Virtual_Guest']
        cci = CCIManager(self.client)
        cci_id = resolve_id(cci.resolve_ids, args.get('<identifier>'), 'CCI')

        if args['--really'] or confirm('This will pause the CCI with id '
                                       '%s. Continue?' % cci_id):
            virtual_guest.pause(id=cci_id)
        else:
            raise CLIAbort('Aborted.')
Ejemplo n.º 7
0
    def execute(self, args):
        virtual_guest = self.client['Virtual_Guest']
        vsi = VSManager(self.client)
        vs_id = resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS')

        if args['--really'] or confirm('This will pause the VS with id '
                                       '%s. Continue?' % vs_id):
            virtual_guest.pause(id=vs_id)
        else:
            raise CLIAbort('Aborted.')
Ejemplo n.º 8
0
    def execute(self, args):
        mgr = FirewallManager(self.client)
        input_id = args.get('<identifier>')

        key_value = get_ids(input_id)
        firewall_id = int(key_value[1])
        if key_value[0] == 'vlan':
            orig_rules = mgr.get_dedicated_fwl_rules(firewall_id)
        else:
            orig_rules = mgr.get_standard_fwl_rules(firewall_id)
        # open an editor for the user to enter their rules
        edited_rules = open_editor(rules=orig_rules)
        print(edited_rules)
        if confirm("Would you like to submit the rules. "
                   "Continue?"):
            while True:
                try:
                    rules = parse_rules(edited_rules)
                    if key_value[0] == 'vlan':
                        rules = mgr.edit_dedicated_fwl_rules(firewall_id,
                                                             rules)
                    else:
                        rules = mgr.edit_standard_fwl_rules(firewall_id,
                                                            rules)
                    break
                except (SoftLayerError, ValueError) as error:
                    print("Unexpected error({%s})" % (error))
                    if confirm("Would you like to continue editing the rules"
                               ". Continue?"):
                        edited_rules = open_editor(content=edited_rules)
                        print(edited_rules)
                        if confirm("Would you like to submit the rules. "
                                   "Continue?"):
                            continue
                        else:
                            raise CLIAbort('Aborted.')
                    else:
                        raise CLIAbort('Aborted.')
                    return 'Firewall updated!'
        else:
            raise CLIAbort('Aborted.')
Ejemplo n.º 9
0
 def execute(self, args):
     vg = self.client['Virtual_Guest']
     cci = CCIManager(self.client)
     cci_id = resolve_id(cci.resolve_ids, args.get('<identifier>'), 'CCI')
     if args['--really'] or confirm('This will power off the CCI with id '
                                    '%s. Continue?' % cci_id):
         if args['--hard']:
             vg.powerOff(id=cci_id)
         else:
             vg.powerOffSoft(id=cci_id)
     else:
         raise CLIAbort('Aborted.')
Ejemplo n.º 10
0
    def execute(self, args):
        mgr = LoadBalancerManager(self.client)
        input_id = args.get('<identifier>')

        key_value = get_ids(input_id)
        service_id = int(key_value[1])

        if args['--really'] or confirm("This action will toggle the service "
                                       "status on the service. Continue?"):
            mgr.toggle_service_status(service_id)
            return 'Load balancer service %s status updated!' % input_id
        else:
            raise CLIAbort('Aborted.')
Ejemplo n.º 11
0
    def execute(self, args):
        mgr = LoadBalancerManager(self.client)
        input_id = args.get('<identifier>')

        key_value = get_ids(input_id)
        loadbal_id = int(key_value[1])

        if args['--really'] or confirm("This action will cancel a load "
                                       "balancer. Continue?"):
            mgr.cancel_lb(loadbal_id)
            return 'Load Balancer with id %s is being cancelled!' % input_id
        else:
            raise CLIAbort('Aborted.')
Ejemplo n.º 12
0
    def execute(self, args):
        mgr = LoadBalancerManager(self.client)
        input_id = args.get('<identifier>')

        key_value = get_ids(input_id)
        group_id = int(key_value[1])

        if args['--really'] or confirm("This action will cancel a service"
                                       " group. Continue?"):
            mgr.delete_service_group(group_id)
            return 'Service group %s is being deleted!' % input_id
        else:
            raise CLIAbort('Aborted.')
Ejemplo n.º 13
0
 def execute(self, args):
     virtual_guest = self.client['Virtual_Guest']
     cci = CCIManager(self.client)
     cci_id = resolve_id(cci.resolve_ids, args.get('<identifier>'), 'CCI')
     if args['--really'] or confirm('This will reboot the CCI with id '
                                    '%s. Continue?' % cci_id):
         if args['--hard']:
             virtual_guest.rebootHard(id=cci_id)
         elif args['--soft']:
             virtual_guest.rebootSoft(id=cci_id)
         else:
             virtual_guest.rebootDefault(id=cci_id)
     else:
         raise CLIAbort('Aborted.')
Ejemplo n.º 14
0
    def execute(self, args):
        mgr = FirewallManager(self.client)
        input_id = args.get('<identifier>')
        key_value = get_ids(input_id)
        firewall_id = int(key_value[1])

        if args['--really'] or confirm("This action will cancel a firewall"
                                       " from your account. Continue?"):
            if key_value[0] in ['cci', 'server']:
                mgr.cancel_firewall(firewall_id, dedicated=False)
            elif key_value[0] == 'vlan':
                mgr.cancel_firewall(firewall_id, dedicated=True)
            return 'Firewall with id %s is being cancelled!' % input_id
        else:
            raise CLIAbort('Aborted.')
Ejemplo n.º 15
0
 def execute(self, args):
     cci = CCIManager(self.client)
     data = {}
     data['cpus'] = args.get('--cpu')
     data['memory'] = args.get('--memory')
     data['nic_speed'] = args.get('--network')
     data['public'] = True
     if args.get('--private'):
         data['public'] = False
     data = self.verify_upgrade_parameters(data)
     cci_id = resolve_id(cci.resolve_ids, args.get('<identifier>'), 'CCI')
     if args['--really'] or confirm(
             "This action will incur charges on your account. "
             "Continue?"):
         if not cci.upgrade(cci_id, **data):
             raise CLIAbort('CCI Upgrade Failed')
Ejemplo n.º 16
0
    def execute(self, args):
        settings = get_settings_from_client(self.client)

        # User Input
        # Ask for username
        while True:
            username = self.env.input("Username [%s]: " % settings["username"]) or settings["username"]
            if username:
                break

        # Ask for 'secret' which can be api_key or their password
        while True:
            secret = self.env.getpass("API Key or Password [%s]: " % settings["api_key"]) or settings["api_key"]
            if secret:
                break

        # Ask for which endpoint they want to use
        while True:
            endpoint_type = self.env.input("Endpoint (public|private|custom): ")
            endpoint_type = endpoint_type.lower()
            if not endpoint_type:
                endpoint_url = API_PUBLIC_ENDPOINT
                break
            if endpoint_type == "public":
                endpoint_url = API_PUBLIC_ENDPOINT
                break
            elif endpoint_type == "private":
                endpoint_url = API_PRIVATE_ENDPOINT
                break
            elif endpoint_type == "custom":
                endpoint_url = (
                    self.env.input("Endpoint URL [%s]: " % settings["endpoint_url"]) or settings["endpoint_url"]
                )
                break

        api_key = get_api_key(username, secret, endpoint_url=endpoint_url)

        settings["username"] = username
        settings["api_key"] = api_key
        settings["endpoint_url"] = endpoint_url

        path = "~/.softlayer"
        if args.get("--config"):
            path = args.get("--config")
        config_path = os.path.expanduser(path)

        self.env.out(format_output(config_table(settings)))

        if not confirm('Are you sure you want to write settings to "%s"?' % config_path, default=True):
            raise CLIAbort("Aborted.")

        # Persist the config file. Read the target config file in before
        # setting the values to avoid clobbering settings
        config = configparser.RawConfigParser()
        config.read(config_path)
        try:
            config.add_section("softlayer")
        except configparser.DuplicateSectionError:
            pass

        config.set("softlayer", "username", settings["username"])
        config.set("softlayer", "api_key", settings["api_key"])
        config.set("softlayer", "endpoint_url", settings["endpoint_url"])

        config_file = os.fdopen(os.open(config_path, (os.O_WRONLY | os.O_CREAT), 0o600), "w")
        try:
            config.write(config_file)
        finally:
            config_file.close()

        return "Configuration Updated Successfully"
Ejemplo n.º 17
0
    def execute(cls, client, args):
        settings = get_settings_from_client(client)

        # User Input
        # Ask for username
        while True:
            username = cls.env.input(
                'Username [%s]: ' % settings['username']) \
                or settings['username']
            if username:
                break

        # Ask for 'secret' which can be api_key or their password
        while True:
            secret = cls.env.getpass(
                'API Key or Password [%s]: ' % settings['api_key']) \
                or settings['api_key']
            if secret:
                break

        # Ask for which endpoint they want to use
        while True:
            endpoint_type = cls.env.input('Endpoint (public|private|custom): ')
            endpoint_type = endpoint_type.lower()
            if not endpoint_type:
                endpoint_url = API_PUBLIC_ENDPOINT
                break
            if endpoint_type == 'public':
                endpoint_url = API_PUBLIC_ENDPOINT
                break
            elif endpoint_type == 'private':
                endpoint_url = API_PRIVATE_ENDPOINT
                break
            elif endpoint_type == 'custom':
                endpoint_url = cls.env.input(
                    'Endpoint URL [%s]: ' % settings['endpoint_url']
                ) or settings['endpoint_url']
                break

        api_key = get_api_key(username, secret, endpoint_url=endpoint_url)

        settings['username'] = username
        settings['api_key'] = api_key
        settings['endpoint_url'] = endpoint_url

        path = '~/.softlayer'
        if args.get('--config'):
            path = args.get('--config')
        config_path = os.path.expanduser(path)

        cls.env.out(format_output(config_table(settings)))

        if not confirm('Are you sure you want to write settings to "%s"?'
                       % config_path, default=True):
            raise CLIAbort('Aborted.')

        # Persist the config file. Read the target config file in before
        # setting the values to avoid clobbering settings
        config = ConfigParser.RawConfigParser()
        config.read(config_path)
        try:
            config.add_section('softlayer')
        except ConfigParser.DuplicateSectionError:
            pass

        config.set('softlayer', 'username', settings['username'])
        config.set('softlayer', 'api_key', settings['api_key'])
        config.set('softlayer', 'endpoint_url', settings['endpoint_url'])

        f = os.fdopen(os.open(
            config_path, (os.O_WRONLY | os.O_CREAT), 0600), 'w')
        try:
            config.write(f)
        finally:
            f.close()

        return "Configuration Updated Successfully"
Ejemplo n.º 18
0
    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
Ejemplo n.º 19
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
        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
Ejemplo n.º 20
0
    def dns_sync(self, args):
        """ Sync DNS records to match the FQDN of the CCI """
        dns = DNSManager(self.client)
        cci = CCIManager(self.client)

        cci_id = resolve_id(cci.resolve_ids, args.get('<identifier>'), 'CCI')
        instance = cci.get_instance(cci_id)
        zone_id = resolve_id(dns.resolve_ids, instance['domain'], name='zone')

        def sync_a_record():
            """ Sync A record """
            records = dns.get_records(
                zone_id,
                host=instance['hostname'],
            )

            if not records:
                # don't have a record, lets add one to the base zone
                dns.create_record(
                    zone['id'],
                    instance['hostname'],
                    'a',
                    instance['primaryIpAddress'],
                    ttl=args['--ttl'])
            else:
                recs = [x for x in records if x['type'].lower() == 'a']
                if len(recs) != 1:
                    raise CLIAbort("Aborting A record sync, found %d "
                                   "A record exists!" % len(recs))
                rec = recs[0]
                rec['data'] = instance['primaryIpAddress']
                rec['ttl'] = args['--ttl']
                dns.edit_record(rec)

        def sync_ptr_record():
            """ Sync PTR record """
            host_rec = instance['primaryIpAddress'].split('.')[-1]
            ptr_domains = self.client['Virtual_Guest'].\
                getReverseDomainRecords(id=instance['id'])[0]
            edit_ptr = None
            for ptr in ptr_domains['resourceRecords']:
                if ptr['host'] == host_rec:
                    ptr['ttl'] = args['--ttl']
                    edit_ptr = ptr
                    break

            if edit_ptr:
                edit_ptr['data'] = instance['fullyQualifiedDomainName']
                dns.edit_record(edit_ptr)
            else:
                dns.create_record(
                    ptr_domains['id'],
                    host_rec,
                    'ptr',
                    instance['fullyQualifiedDomainName'],
                    ttl=args['--ttl'])

        if not instance['primaryIpAddress']:
            raise CLIAbort('No primary IP address associated with this CCI')

        try:
            zone = dns.get_zone(zone_id)
        except DNSZoneNotFound:
            raise CLIAbort("Unable to create A record, "
                           "no zone found matching: %s" % instance['domain'])

        go_for_it = args['--really'] or confirm(
            "Attempt to update DNS records for %s"
            % instance['fullyQualifiedDomainName'])

        if not go_for_it:
            raise CLIAbort("Aborting DNS sync")

        both = False
        if not args['--ptr'] and not args['-a']:
            both = True

        if both or args['-a']:
            sync_a_record()

        if both or args['--ptr']:
            sync_ptr_record()
Ejemplo n.º 21
0
    def dns_sync(client, args):
        from SoftLayer.DNS import DNSManager, DNSZoneNotFound
        dns = DNSManager(client)
        cci = CCIManager(client)

        def sync_a_record():
            #hostname = instance['fullyQualifiedDomainName']
            records = dns.search_record(
                instance['domain'],
                instance['hostname'],
            )

            if not records:
                # don't have a record, lets add one to the base zone
                dns.create_record(
                    zone['id'],
                    instance['hostname'],
                    'a',
                    instance['primaryIpAddress'],
                    ttl=7200)
            else:
                recs = filter(lambda x: x['type'].lower() == 'a', records)
                if len(recs) != 1:
                    raise CLIAbort("Aborting A record sync, found %d "
                                   "A record exists!" % len(recs))
                rec = recs[0]
                rec['data'] = instance['primaryIpAddress']
                dns.edit_record(rec)

        def sync_ptr_record():
            host_rec = instance['primaryIpAddress'].split('.')[-1]
            ptr_domains = client['Virtual_Guest'].\
                getReverseDomainRecords(id=instance['id'])[0]
            edit_ptr = None
            for ptr in ptr_domains['resourceRecords']:
                if ptr['host'] == host_rec:
                    edit_ptr = ptr
                    break

            if edit_ptr:
                edit_ptr['data'] = instance['fullyQualifiedDomainName']
                dns.edit_record(edit_ptr)
            else:
                dns.create_record(
                    ptr_domains['id'],
                    host_rec,
                    'ptr',
                    instance['fullyQualifiedDomainName'],
                    ttl=7200)

        cci_id = resolve_id(cci, args.get('<identifier>'))
        instance = cci.get_instance(cci_id)

        if not instance['primaryIpAddress']:
            raise CLIAbort('No primary IP address associated with this CCI')

        try:
            zone = dns.get_zone(instance['domain'])
        except DNSZoneNotFound:
            raise CLIAbort("Unable to create A record, "
                           "no zone found matching: %s" % instance['domain'])

        go_for_it = args['--really'] or confirm(
            "Attempt to update DNS records for %s"
            % instance['fullyQualifiedDomainName'])

        if not go_for_it:
            raise CLIAbort("Aborting DNS sync")

        both = False
        if not args.get('--PTR') and not args.get('-A'):
            both = True

        if both or args.get('-A'):
            sync_a_record()

        if both or args.get('--PTR'):
            sync_ptr_record()
Ejemplo n.º 22
0
    def execute(self, args):
        update_with_template_args(args)
        cci = CCIManager(self.client)
        self._update_with_like_args(args)

        # 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(',')

        # SSH keys may be a comma-separated list. Let's make it a real list.
        if isinstance(args.get('--key'), str):
            args['--key'] = args.get('--key').split(',')

        self._validate_args(args)

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

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

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

            table = 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(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')
            export_to_template(export_file, args, exclude=['--wait', '--test'])
            return 'Successfully exported options to a template file.'

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

                table = 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 = cci.wait_for_ready(
                        result['id'], int(args.get('--wait') or 1))
                    table.add_row(['ready', ready])
            else:
                raise CLIAbort('Aborting CCI order.')

        return output
Ejemplo n.º 23
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