def cli(env, volume_id, reason, immediate): """Cancel an existing block storage volume.""" block_storage_manager = SoftLayer.BlockStorageManager(env.client) if not (env.skip_confirmations or formatting.no_going_back(volume_id)): raise exceptions.CLIAbort('Aborted') block_storage_manager.cancel_block_volume(volume_id, reason, immediate)
def cli(env, billing_id, datacenter): """Adds a load balancer given the id returned from create-options.""" mgr = SoftLayer.LoadBalancerManager(env.client) if not formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.CLIAbort('Aborted.') mgr.add_local_lb(billing_id, datacenter=datacenter) return "Load balancer is being created!"
def cli(env, identifier, label, note): """Edits an SSH key.""" mgr = SoftLayer.SshKeyManager(env.client) key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey') if not mgr.edit_key(key_id, label=label, notes=note): raise exceptions.CLIAbort('Failed to edit SSH key')
def cli(env, datacenter, network): """Ping the SoftLayer Message Queue service.""" manager = SoftLayer.MessagingManager(env.client) okay = manager.ping(datacenter=datacenter, network=network) if okay: return 'OK' else: exceptions.CLIAbort('Ping failed')
def cli(env, identifier): """Cancel virtual servers.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not (env.skip_confirmations or formatting.no_going_back(vs_id)): raise exceptions.CLIAbort('Aborted') vsi.cancel_instance(vs_id)
def execute(self, args): vsi = SoftLayer.VSManager(self.client) vs_id = helpers.resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') if args['--really'] or formatting.no_going_back(vs_id): vsi.cancel_instance(vs_id) else: raise exceptions.CLIAbort('Aborted')
def cli(env, identifier): """Permanently removes an SSH key.""" mgr = SoftLayer.SshKeyManager(env.client) key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey') if not (env.skip_confirmations or formatting.no_going_back(key_id)): raise exceptions.CLIAbort('Aborted') mgr.delete_key(key_id)
def cli(env, record_id): """Remove resource record.""" manager = SoftLayer.DNSManager(env.client) if not (env.skip_confirmations or formatting.no_going_back('yes')): raise exceptions.CLIAbort("Aborted.") manager.delete_record(record_id)
def cli(env, identifier, username_storage): """Authorize File or Block Storage to a Hardware Server.""" hardware = SoftLayer.HardwareManager(env.client) hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, 'hardware') if not hardware.authorize_storage(hardware_id, username_storage): raise exceptions.CLIAbort('Authorize Storage Failed') env.fout('Successfully Storage Added.')
def cli(env, identifier, domain, userfile, tag, hostname, userdata, public_speed, private_speed, redundant, degraded): """Edit hardware details.""" if userdata and userfile: raise exceptions.ArgumentError( '[-u | --userdata] not allowed with [-F | --userfile]') data = { 'hostname': hostname, 'domain': domain, } if userdata: data['userdata'] = userdata elif userfile: with open(userfile, 'r', encoding="utf-8") as userfile_obj: data['userdata'] = userfile_obj.read() if tag: data['tags'] = ','.join(tag) mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not mgr.edit(hw_id, **data): raise exceptions.CLIAbort("Failed to update hardware") if public_speed is not None: if redundant: mgr.change_port_speed(hw_id, True, int(public_speed), 'redundant') if degraded: mgr.change_port_speed(hw_id, True, int(public_speed), 'degraded') if not redundant and not degraded: raise exceptions.CLIAbort("Failed to update hardwar") if private_speed is not None: if redundant: mgr.change_port_speed(hw_id, False, int(private_speed), 'redundant') if degraded: mgr.change_port_speed(hw_id, False, int(private_speed), 'degraded') if not redundant and not degraded: raise exceptions.CLIAbort("Failed to update hardware")
def cli(env, identifier, purge): """Delete a placement group. Placement Group MUST be empty before you can delete it. IDENTIFIER can be either the Name or Id of the placement group you want to view """ manager = PlacementManager(env.client) group_id = helpers.resolve_id(manager.resolve_ids, identifier, 'placement_group') if purge: placement_group = manager.get_object(group_id) guest_list = ', '.join([ guest['fullyQualifiedDomainName'] for guest in placement_group['guests'] ]) if len(placement_group['guests']) < 1: raise exceptions.CLIAbort( 'No virtual servers were found in placement group %s' % identifier) click.secho("You are about to delete the following guests!\n%s" % guest_list, fg='red') if not (env.skip_confirmations or formatting.confirm( "This action will cancel all guests! Continue?")): raise exceptions.CLIAbort('Aborting virtual server order.') vm_manager = VSManager(env.client) for guest in placement_group['guests']: click.secho("Deleting %s..." % guest['fullyQualifiedDomainName']) vm_manager.cancel_instance(guest['id']) return click.secho("You are about to delete the following placement group! %s" % identifier, fg='red') if not (env.skip_confirmations or formatting.confirm( "This action will cancel the placement group! Continue?")): raise exceptions.CLIAbort('Aborting virtual server order.') cancel_result = manager.delete(group_id) if cancel_result: click.secho("Placement Group %s has been canceld." % identifier, fg='green')
def cli(env, identifier): """Cancels a firewall.""" mgr = SoftLayer.FirewallManager(env.client) firewall_type, firewall_id = firewall.parse_id(identifier) if not (env.skip_confirmations or formatting.confirm( "This action will cancel a firewall from your " "account. Continue?")): raise exceptions.CLIAbort('Aborted.') if firewall_type in ['vs', 'server']: mgr.cancel_firewall(firewall_id, dedicated=False) elif firewall_type == 'vlan': mgr.cancel_firewall(firewall_id, dedicated=True) else: raise exceptions.CLIAbort('Unknown firewall type: %s' % firewall_type) return 'Firewall with id %s is being cancelled!' % identifier
def cli(env, identifier, wait): """Check if a virtual server is ready.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') ready = vsi.wait_for_ready(vs_id, wait) if ready: env.fout("READY") else: raise exceptions.CLIAbort("Instance %s not ready" % vs_id)
def execute(self, args): mgr = SoftLayer.HardwareManager(self.client) hw_id = helpers.resolve_id(mgr.resolve_ids, args.get('<identifier>'), 'hardware') if args['--really'] or formatting.confirm('This will power off the ' 'server with id %s ' 'Continue?' % hw_id): self.client['Hardware_Server'].powerOff(id=hw_id) else: raise exceptions.CLIAbort('Aborted.')
def execute(self, args): manager = SoftLayer.DNSManager(self.client) zone_id = helpers.resolve_id(manager.resolve_ids, args['<zone>'], name='zone') if args['--really'] or formatting.no_going_back(args['<zone>']): manager.delete_zone(zone_id) else: raise exceptions.CLIAbort("Aborted.")
def execute(self, args): mgr = SoftLayer.NetworkManager(self.client) global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, args.get('<identifier>'), name='global ip') if args['--really'] or formatting.no_going_back(global_ip_id): mgr.cancel_global_ip(global_ip_id) else: raise exceptions.CLIAbort('Aborted')
def _get_price_id_from_options(ds_options, option, value, item_id=False): """Returns a price_id for a given option and value.""" for _, options in server.get_create_options(ds_options, option, False): for item_options in options: if item_options[0] == value: if not item_id: return item_options[1] return item_options[2] raise exceptions.CLIAbort('No price found for %s' % option)
def cli(env, zone): """Delete zone.""" manager = SoftLayer.DNSManager(env.client) zone_id = helpers.resolve_id(manager.resolve_ids, zone, name='zone') if not (env.skip_confirmations or formatting.no_going_back(zone)): raise exceptions.CLIAbort("Aborted.") manager.delete_zone(zone_id)
def cli(env, identifier, reason, immediate): """Cancel an existing iSCSI account.""" iscsi_mgr = SoftLayer.ISCSIManager(env.client) iscsi_id = helpers.resolve_id(iscsi_mgr.resolve_ids, identifier, 'iSCSI') if env.skip_confirmations or formatting.no_going_back(iscsi_id): iscsi_mgr.cancel_iscsi(iscsi_id, reason, immediate) else: raise exceptions.CLIAbort('Aborted')
def cli(env, identifier, immediate, comment, reason): """Cancel a dedicated server.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.no_going_back(hw_id)): raise exceptions.CLIAbort('Aborted') mgr.cancel_hardware(hw_id, reason, comment, immediate)
def rescue(env, identifier): """Reboot into a rescue image.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not (env.skip_confirmations or formatting.confirm("This action will reboot this VSI. Continue?")): raise exceptions.CLIAbort('Aborted') vsi.rescue(vs_id)
def execute(self, args): mgr = SoftLayer.LoadBalancerManager(self.client) input_id = helpers.resolve_id(mgr.resolve_ids, args.get('<identifier>'), 'load_balancer') if not formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.CLIAbort('Aborted.') mgr.add_local_lb(input_id, datacenter=args['--datacenter']) return "Load balancer is being created!"
def cli(env): """Setup the ~/.softlayer file with username and apikey. Set the username to 'apikey' for cloud.ibm.com accounts. """ username, secret, endpoint_url, timeout = get_user_input(env) new_client = SoftLayer.Client(username=username, api_key=secret, endpoint_url=endpoint_url, timeout=timeout) api_key = get_api_key(new_client, username, secret) path = '~/.softlayer' if env.config_file: path = env.config_file config_path = os.path.expanduser(path) env.out( env.fmt( config.config_table({ 'username': username, 'api_key': api_key, 'endpoint_url': endpoint_url, 'timeout': timeout }))) if not formatting.confirm('Are you sure you want to write settings ' 'to "%s"?' % config_path, default=True): raise exceptions.CLIAbort('Aborted.') # Persist the config file. Read the target config file in before # setting the values to avoid clobbering settings parsed_config = configparser.RawConfigParser() parsed_config.read(config_path) try: parsed_config.add_section('softlayer') except configparser.DuplicateSectionError: pass parsed_config.set('softlayer', 'username', username) parsed_config.set('softlayer', 'api_key', api_key) parsed_config.set('softlayer', 'endpoint_url', endpoint_url) parsed_config.set('softlayer', 'timeout', timeout) config_fd = os.fdopen( os.open(config_path, (os.O_WRONLY | os.O_CREAT | os.O_TRUNC), 0o600), 'w') try: parsed_config.write(config_fd) finally: config_fd.close() env.fout("Configuration Updated Successfully")
def cli(env, service, method, parameters, _id, _filters, mask, limit, offset, output_python=False, json_filter=None): """Call arbitrary API endpoints with the given SERVICE and METHOD. For parameters that require a datatype, use a JSON string for that parameter. Example:: slcli call-api Account getObject slcli call-api Account getVirtualGuests --limit=10 --mask=id,hostname slcli call-api Virtual_Guest getObject --id=12345 slcli call-api Metric_Tracking_Object getBandwidthData --id=1234 \\ "2015-01-01 00:00:00" "2015-01-1 12:00:00" public slcli call-api Account getVirtualGuests \\ -f 'virtualGuests.datacenter.name=dal05' \\ -f 'virtualGuests.maxCpu=4' \\ --mask=id,hostname,datacenter.name,maxCpu slcli call-api Account getVirtualGuests \\ -f 'virtualGuests.datacenter.name IN dal05,sng01' slcli call-api Account getVirtualGuests \\ --json-filter '{"virtualGuests":{"hostname":{"operation":"^= test"}}}' --limit=10 slcli -v call-api SoftLayer_User_Customer addBulkPortalPermission --id=1234567 \\ '[{"keyName": "NETWORK_MESSAGE_DELIVERY_MANAGE"}]' """ if _filters and json_filter: raise exceptions.CLIAbort( "--filter and --json-filter cannot be used together.") object_filter = _build_filters(_filters) if json_filter: object_filter.update(json_filter) args = [service, method] + list(parameters) kwargs = { 'id': _id, 'filter': object_filter, 'mask': mask, 'limit': limit, 'offset': offset, } if output_python: env.out(_build_python_example(args, kwargs)) else: result = env.client.call(*args, **kwargs) env.fout(formatting.iter_to_table(result))
def cli(env, username, email, password, from_user, template, api_key): """Creates a user Users. :Example: slcli user create [email protected] -e [email protected] -p generate -a -t '{"firstName": "Test", "lastName": "Testerson"}' Remember to set the permissions and access for this new user. """ mgr = SoftLayer.UserManager(env.client) user_mask = ("mask[id, firstName, lastName, email, companyName, address1, city, country, postalCode, " "state, userStatusId, timezoneId]") from_user_id = None if from_user is None: user_template = mgr.get_current_user(objectmask=user_mask) from_user_id = user_template['id'] else: from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username') user_template = mgr.get_user(from_user_id, objectmask=user_mask) # If we send the ID back to the API, an exception will be thrown del user_template['id'] if template is not None: try: template_object = json.loads(template) for key in template_object: user_template[key] = template_object[key] except ValueError as ex: raise exceptions.ArgumentError("Unable to parse --template. %s" % ex) user_template['username'] = username if password == 'generate': password = generate_password() user_template['email'] = email if not env.skip_confirmations: table = formatting.KeyValueTable(['name', 'value']) for key in user_template: table.add_row([key, user_template[key]]) table.add_row(['password', password]) click.secho("You are about to create the following user...", fg='green') env.fout(table) if not formatting.confirm("Do you wish to continue?"): raise exceptions.CLIAbort("Canceling creation!") result = mgr.create_user(user_template, password) new_api_key = None if api_key: click.secho("Adding API key...", fg='green') new_api_key = mgr.add_api_authentication_key(result['id']) table = formatting.Table(['Username', 'Email', 'Password', 'API Key']) table.add_row([result['username'], result['email'], password, new_api_key]) env.fout(table)
def cli(env, identifier, cpu, private, memory, network, flavor, add_disk, resize_disk): """Upgrade a virtual server.""" vsi = SoftLayer.VSManager(env.client) if not any([cpu, memory, network, flavor, resize_disk, add_disk]): raise exceptions.ArgumentError( "Must provide [--cpu]," " [--memory], [--network], [--flavor], [--resize-disk], or [--add] to upgrade" ) if private and not cpu: raise exceptions.ArgumentError( "Must specify [--cpu] when using [--private]") vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not (env.skip_confirmations or formatting.confirm( "This action will incur charges on your account. Continue?")): raise exceptions.CLIAbort('Aborted') disk_json = list() if memory: memory = int(memory / 1024) if resize_disk: for guest_disk in resize_disk: disks = {'capacity': guest_disk[0], 'number': guest_disk[1]} disk_json.append(disks) elif add_disk: for guest_disk in add_disk: disks = {'capacity': guest_disk, 'number': -1} disk_json.append(disks) if not vsi.upgrade(vs_id, cpus=cpu, memory=memory, nic_speed=network, public=not private, preset=flavor, disk=disk_json): raise exceptions.CLIAbort('VS Upgrade Failed')
def cli(env, identifier, cpu, private, memory, network, flavor): """Upgrade a virtual server.""" vsi = SoftLayer.VSManager(env.client) if not any([cpu, memory, network, flavor]): raise exceptions.ArgumentError("Must provide [--cpu], [--memory], [--network], or [--flavor] to upgrade") if private and not cpu: raise exceptions.ArgumentError("Must specify [--cpu] when using [--private]") vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not (env.skip_confirmations or formatting.confirm("This action will incur charges on your account. Continue?")): raise exceptions.CLIAbort('Aborted') if memory: memory = int(memory / 1024) if not vsi.upgrade(vs_id, cpus=cpu, memory=memory, nic_speed=network, public=not private, preset=flavor): raise exceptions.CLIAbort('VS Upgrade Failed')
def power_off(env, identifier): """Power off an active server.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if env.skip_confirmations or formatting.confirm('This will power off the ' 'server with id %s ' 'Continue?' % hw_id): env.client['Hardware_Server'].powerOff(id=hw_id) else: raise exceptions.CLIAbort('Aborted.')
def cli(env, group_id, name, description): """Edit details of a security group.""" mgr = SoftLayer.NetworkManager(env.client) data = {} if name: data['name'] = name if description: data['description'] = description if not mgr.edit_securitygroup(group_id, **data): raise exceptions.CLIAbort("Failed to edit security group")
def pause(env, identifier): """Pauses an active virtual server.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not (env.skip_confirmations or formatting.confirm( 'This will pause the VS with id %s. Continue?' % vs_id)): raise exceptions.CLIAbort('Aborted.') env.client['Virtual_Guest'].pause(id=vs_id)