def test_confirmation(self, prompt_mock): prompt_mock.return_value = 'Y' res = formatting.confirm('Confirm?', default=False) self.assertTrue(res) prompt_mock.return_value = 'N' res = formatting.confirm('Confirm?', default=False) self.assertFalse(res) prompt_mock.return_value = '' res = formatting.confirm('Confirm?', default=True) self.assertTrue(res)
def test_confirmation(self, raw_input_mock): raw_input_mock.return_value = 'Y' res = formatting.confirm('Confirm?', default=False) self.assertTrue(res) raw_input_mock.return_value = 'N' res = formatting.confirm('Confirm?', default=False) self.assertFalse(res) raw_input_mock.return_value = '' res = formatting.confirm('Confirm?', default=True) self.assertTrue(res)
def test_confirmation(self, raw_input_mock): raw_input_mock.return_value = "Y" res = formatting.confirm("Confirm?", default=False) self.assertTrue(res) raw_input_mock.return_value = "N" res = formatting.confirm("Confirm?", default=False) self.assertFalse(res) raw_input_mock.return_value = "" res = formatting.confirm("Confirm?", default=True) self.assertTrue(res)
def cli(env, **args): """Order/create virtual servers.""" vsi = SoftLayer.VSManager(env.client) _validate_args(env, args) create_args = _parse_create_args(env.client, args) test = args.get('test', False) do_create = not (args.get('export') or test) if do_create: if not (env.skip_confirmations or formatting.confirm( "This action will incur charges on your account. Continue?")): raise exceptions.CLIAbort('Aborting virtual server order.') if args.get('export'): export_file = args.pop('export') template.export_to_template(export_file, args, exclude=['wait', 'test']) env.fout('Successfully exported options to a template file.') else: result = vsi.order_guest(create_args, test) output = _build_receipt_table(result, args.get('billing'), test) if do_create: env.fout(_build_guest_table(result)) env.fout(output) if args.get('wait'): virtual_guests = utils.lookup(result, 'orderDetails', 'virtualGuests') guest_id = virtual_guests[0]['id'] click.secho("Waiting for %s to finish provisioning..." % guest_id, fg='green') ready = vsi.wait_for_ready(guest_id, args.get('wait') or 1) if ready is False: env.out(env.fmt(output)) raise exceptions.CLIHalt(code=1)
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 = [] 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 execute(self, args): mgr = SoftLayer.NetworkManager(self.client) version = 4 if args.get('--v6'): version = 6 if not args.get('--test') and not args['--really']: if not formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.CLIAbort('Cancelling order.') result = mgr.add_global_ip(version=version, test_order=args.get('--test')) table = formatting.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
def execute(self, args): mgr = SoftLayer.FirewallManager(self.client) input_id = helpers.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 formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.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!"
def execute(self, args): mgr = SoftLayer.NetworkManager(self.client) _type = 'private' if args['public']: _type = 'public' version = 4 if args.get('--v6'): version = 6 if not args.get('--test') and not args['--really']: if not formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.CLIAbort('Cancelling order.') result = mgr.add_subnet(_type, quantity=args['<quantity>'], vlan_id=args['<vlan>'], version=version, test_order=args.get('--test')) if not result: return 'Unable to place order: No valid price IDs found.' table = formatting.Table(['Item', 'cost']) table.align['Item'] = 'r' table.align['cost'] = 'r' total = 0.0 if 'prices' in result: for price in result['prices']: total += float(price.get('recurringFee', 0.0)) rate = "%.2f" % float(price['recurringFee']) table.add_row([price['item']['description'], rate]) table.add_row(['Total monthly cost', "%.2f" % total]) return table
def cli(env, target, firewall_type, high_availability): """Create new firewall.""" mgr = SoftLayer.FirewallManager(env.client) if not env.skip_confirmations: if firewall_type == 'vlan': pkg = mgr.get_dedicated_package(ha_enabled=high_availability) elif firewall_type == 'vs': pkg = mgr.get_standard_package(target, is_virt=True) elif firewall_type == 'server': pkg = mgr.get_standard_package(target, is_virt=False) if not pkg: return "Unable to add firewall - Is network public enabled?" env.out("******************") env.out("Product: %s" % pkg[0]['description']) env.out("Price: $%s monthly" % pkg[0]['prices'][0]['recurringFee']) env.out("******************") if not formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.CLIAbort('Aborted.') if firewall_type == 'vlan': mgr.add_vlan_firewall(target, ha_enabled=high_availability) elif firewall_type == 'vs': mgr.add_standard_firewall(target, is_virt=True) elif firewall_type == 'server': mgr.add_standard_firewall(target, is_virt=False) return "Firewall is being created!"
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 cli(env, identifier, memory, network, drive_controller, public_bandwidth, add_disk, resize_disk, test): """Upgrade a Hardware Server.""" mgr = SoftLayer.HardwareManager(env.client) if not any([memory, network, drive_controller, public_bandwidth, add_disk, resize_disk]): raise exceptions.ArgumentError("Must provide " " [--memory], [--network], [--drive-controller], [--public-bandwidth]," "[--add-disk] or [--resize-disk]") hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'Hardware') if not test: if not (env.skip_confirmations or formatting.confirm( "This action will incur charges on your account. Continue?")): raise exceptions.CLIAbort('Aborted') disk_list = list() if add_disk: for guest_disk in add_disk: disks = {'description': 'add_disk', 'capacity': guest_disk[0], 'number': guest_disk[1]} disk_list.append(disks) if resize_disk: for guest_disk in resize_disk: disks = {'description': 'resize_disk', 'capacity': guest_disk[0], 'number': guest_disk[1]} disk_list.append(disks) if not mgr.upgrade(hw_id, memory=memory, nic_speed=network, drive_controller=drive_controller, public_bandwidth=public_bandwidth, disk=disk_list, test=test): raise exceptions.CLIAbort('Hardware Server Upgrade Failed') env.fout('Successfully Upgraded.')
def cli(env, ipv6, test): """Creates a global IP.""" mgr = SoftLayer.NetworkManager(env.client) version = 4 if ipv6: version = 6 if not (test or env.skip_confirmations): if not formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.CLIAbort("Cancelling order.") result = mgr.add_global_ip(version=version, test_order=test) table = formatting.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]) env.fout(table)
def cli(env, ipv6, test): """Creates a global IP.""" mgr = SoftLayer.NetworkManager(env.client) version = 4 if ipv6: version = 6 if not (test or env.skip_confirmations): if not formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.CLIAbort('Cancelling order.') result = mgr.add_global_ip(version=version, test_order=test) table = formatting.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]) env.fout(table)
def cli(env, identifier, cpu, private, memory, network): """Upgrade a virtual server.""" vsi = SoftLayer.VSManager(env.client) if not any([cpu, memory, network]): raise exceptions.ArgumentError( "Must provide [--cpu], [--memory], or [--network] 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): raise exceptions.CLIAbort('VS Upgrade Failed')
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, **args): """Order/create a dedicated server.""" template.update_with_template_args(args, list_args=['disk', 'key']) mgr = SoftLayer.HardwareManager(env.client) ds_options = mgr.get_dedicated_server_create_options(args['chassis']) order = _process_args(env, args, ds_options) # Do not create hardware server with --test or --export do_create = not (args['export'] or args['test']) output = None if args.get('test'): result = mgr.verify_order(**order) table = formatting.Table(['Item', 'cost']) table.align['Item'] = 'r' table.align['cost'] = 'r' total = 0.0 for price in result['prices']: total += float(price.get('recurringFee', 0.0)) rate = "%.2f" % float(price['recurringFee']) table.add_row([price['item']['description'], rate]) table.add_row(['Total monthly cost', "%.2f" % total]) output = [] output.append(table) output.append( formatting.FormattedItem( '', ' -- ! Prices reflected here are retail and do not ' 'take account level discounts and are not guaranteed.')) if args['export']: export_file = args.pop('export') template.export_to_template(export_file, args, exclude=['wait', 'test']) return 'Successfully exported options to a template file.' if do_create: if env.skip_confirmations or formatting.confirm( "This action will incur charges on your account. " "Continue?"): result = mgr.place_order(**order) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', result['orderId']]) table.add_row(['created', result['orderDate']]) output = table else: raise exceptions.CLIAbort('Aborting dedicated server order.') return output
def 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) env.fout("Load balancer is being created!")
def cli(env, **args): """Order/create a dedicated server.""" template.update_with_template_args(args, list_args=['disk', 'key']) mgr = SoftLayer.HardwareManager(env.client) ds_options = mgr.get_dedicated_server_create_options(args['chassis']) order = _process_args(env, args, ds_options) # Do not create hardware server with --test or --export do_create = not (args['export'] or args['test']) output = None if args.get('test'): result = mgr.verify_order(**order) table = formatting.Table(['Item', 'cost']) table.align['Item'] = 'r' table.align['cost'] = 'r' total = 0.0 for price in result['prices']: total += float(price.get('recurringFee', 0.0)) rate = "%.2f" % float(price['recurringFee']) table.add_row([price['item']['description'], rate]) table.add_row(['Total monthly cost', "%.2f" % total]) output = [] output.append(table) output.append(formatting.FormattedItem( '', ' -- ! Prices reflected here are retail and do not ' 'take account level discounts and are not guaranteed.')) if args['export']: export_file = args.pop('export') template.export_to_template(export_file, args, exclude=['wait', 'test']) return 'Successfully exported options to a template file.' if do_create: if env.skip_confirmations or formatting.confirm( "This action will incur charges on your account. " "Continue?"): result = mgr.place_order(**order) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', result['orderId']]) table.add_row(['created', result['orderDate']]) output = table else: raise exceptions.CLIAbort('Aborting dedicated server order.') return output
def cli(env, network, quantity, endpoint_id, ipv6, test): """Add a new subnet to your account. Valid quantities vary by type. \b IPv4 static - 1, 2, 4, 8, 16, 32, 64, 128, 256 public - 4, 8, 16, 32, 64, 128, 256 private - 4, 8, 16, 32, 64, 128, 256 \b IPv6 static - 64 public - 64 \b endpoint-id static - Network_Subnet_IpAddress identifier. public - Network_Vlan identifier private - Network_Vlan identifier """ mgr = SoftLayer.NetworkManager(env.client) if not (test or env.skip_confirmations): if not formatting.confirm("This action will incur charges on your " "account. Continue?"): raise exceptions.CLIAbort('Cancelling order.') version = 4 if ipv6: version = 6 try: result = mgr.add_subnet(network, quantity=quantity, endpoint_id=endpoint_id, version=version, test_order=test) except SoftLayer.SoftLayerAPIError as error: raise exceptions.CLIAbort( 'Unable to order {} {} ipv{} , error: {}'.format( quantity, network, version, error.faultString)) table = formatting.Table(['Item', 'cost']) table.align['Item'] = 'r' table.align['cost'] = 'r' total = 0.0 if 'prices' in result: for price in result['prices']: total += float(price.get('recurringFee', 0.0)) rate = "%.2f" % float(price['recurringFee']) table.add_row([price['item']['description'], rate]) table.add_row(['Total monthly cost', "%.2f" % total]) env.fout(table)
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) env.fout("Load balancer is being created!")
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, 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 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 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.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 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, 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): """Reflash server firmware.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This will power off the server with id %s and ' 'reflash device firmware. Continue?' % hw_id)): raise exceptions.CLIAbort('Aborted.') mgr.reflash_firmware(hw_id)
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)
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 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.confirm( "This action will reboot this VSI. " "Continue?"): vsi.rescue(vs_id) else: raise exceptions.CLIAbort('Aborted')
def cli(env, identifier): """Update server firmware.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm( 'This will power off the server with id %s and ' 'update device firmware. Continue?' % hw_id)): raise exceptions.CLIAbort('Aborted.') mgr.update_firmware(hw_id)
def cli(env, identifier): """Edit firewall rules.""" mgr = SoftLayer.FirewallManager(env.client) firewall_type, firewall_id = firewall.parse_id(identifier) if firewall_type == '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) env.out(edited_rules) if formatting.confirm("Would you like to submit the rules. " "Continue?"): while True: try: rules = parse_rules(edited_rules) if firewall_type == 'vlan': rules = mgr.edit_dedicated_fwl_rules(firewall_id, rules) else: rules = mgr.edit_standard_fwl_rules(firewall_id, rules) break except (SoftLayer.SoftLayerError, ValueError) as error: env.out("Unexpected error({%s})" % (error)) if formatting.confirm("Would you like to continue editing " "the rules. Continue?"): edited_rules = open_editor(content=edited_rules) env.out(edited_rules) if formatting.confirm("Would you like to submit the " "rules. Continue?"): continue else: raise exceptions.CLIAbort('Aborted.') else: raise exceptions.CLIAbort('Aborted.') env.fout('Firewall updated!') else: raise exceptions.CLIAbort('Aborted.')
def execute(self, args): mgr = SoftLayer.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 formatting.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 (SoftLayer.SoftLayerError, ValueError) as error: print("Unexpected error({%s})" % (error)) if formatting.confirm("Would you like to continue editing " "the rules. Continue?"): edited_rules = open_editor(content=edited_rules) print(edited_rules) if formatting.confirm("Would you like to submit the " "rules. Continue?"): continue else: raise exceptions.CLIAbort('Aborted.') else: raise exceptions.CLIAbort('Aborted.') return 'Firewall updated!' else: raise exceptions.CLIAbort('Aborted.')
def rescue(env, identifier): """Reboot server into a rescue image.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm( "This action will reboot this server. Continue?")): raise exceptions.CLIAbort('Aborted') env.client['Hardware_Server'].bootToRescueLayer(id=hw_id)
def power_cycle(env, identifier): """Power on a server.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This will power off the server with id %s. ' 'Continue?' % hw_id)): raise exceptions.CLIAbort('Aborted.') env.client['Hardware_Server'].powerCycle(id=hw_id)
def execute(self, args): server = SoftLayer.HardwareManager(self.client) server_id = helpers.resolve_id(server.resolve_ids, args.get('<identifier>'), 'hardware') if args['--really'] or formatting.confirm( "This action will reboot this server. " "Continue?"): server.rescue(server_id) else: raise exceptions.CLIAbort('Aborted')
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)
def rescue(env, identifier): """Reboot server into a rescue image.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm("This action will reboot this server. Continue?")): raise exceptions.CLIAbort('Aborted') env.client['Hardware_Server'].bootToRescueLayer(id=hw_id)
def power_cycle(env, identifier): """Power cycle a server.""" mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This will power off the server with id %s. ' 'Continue?' % hw_id)): raise exceptions.CLIAbort('Aborted.') env.client['Hardware_Server'].powerCycle(id=hw_id)
def execute(self, args): virtual_guest = self.client['Virtual_Guest'] vsi = SoftLayer.VSManager(self.client) vs_id = helpers.resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') if args['--really'] or formatting.confirm( 'This will pause the VS ' 'with id %s. Continue?' % vs_id): virtual_guest.pause(id=vs_id) else: raise exceptions.CLIAbort('Aborted.')
def cli(env, identifier): """Deletes an existing load balancer service group.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, group_id = loadbal.parse_id(identifier) if not (env.skip_confirmations or formatting.confirm("This action will cancel a service group. " "Continue?")): raise exceptions.CLIAbort('Aborted.') mgr.delete_service_group(group_id) env.fout('Service group %s is being deleted!' % identifier)
def cli(env, identifier): """Toggle the status of an existing load balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, service_id = loadbal.parse_id(identifier) if not (env.skip_confirmations or formatting.confirm("This action will toggle the status on the " "service. Continue?")): raise exceptions.CLIAbort('Aborted.') mgr.toggle_service_status(service_id) env.fout('Load balancer service %s status updated!' % identifier)
def cli(env, identifier): """Deletes an existing load balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, service_id = loadbal.parse_id(identifier) if not (env.skip_confirmations or formatting.confirm("This action will cancel a service from your " "load balancer. Continue?")): raise exceptions.CLIAbort('Aborted.') mgr.delete_service(service_id) env.fout('Load balancer service %s is being cancelled!' % service_id)
def cli(env, identifier): """Toggle the status of an existing load balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, service_id = loadbal.parse_id(identifier) if not (env.skip_confirmations or formatting.confirm("This action will toggle the status on the " "service. Continue?")): raise exceptions.CLIAbort('Aborted.') mgr.toggle_service_status(service_id) return 'Load balancer service %s status updated!' % identifier
def test_confirmation(self, prompt_mock): prompt_mock.return_value = 'Y' res = formatting.confirm('Confirm?', default=False) self.assertTrue(res) prompt_mock.return_value = 'N' res = formatting.confirm('Confirm?', default=False) self.assertFalse(res) prompt_mock.return_value = 'Y' res = formatting.confirm('Confirm?', default=True) self.assertTrue(res) prompt_mock.assert_called_with('Confirm? [Y/n]', default='y', show_default=False) prompt_mock.return_value = 'N' res = formatting.confirm('Confirm?', default=False) self.assertFalse(res) prompt_mock.assert_called_with('Confirm? [y/N]', default='n', show_default=False)
def execute(self, args): virtual_guest = self.client['Virtual_Guest'] vsi = SoftLayer.VSManager(self.client) vs_id = helpers.resolve_id(vsi.resolve_ids, args.get('<identifier>'), 'VS') if args['--really'] or formatting.confirm('This will pause the VS ' 'with id %s. Continue?' % vs_id): virtual_guest.pause(id=vs_id) else: raise exceptions.CLIAbort('Aborted.')