repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
39
1.84M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.out
def out(self, output, newline=True): """Outputs a string to the console (stdout).""" click.echo(output, nl=newline)
python
def out(self, output, newline=True): click.echo(output, nl=newline)
[ "def", "out", "(", "self", ",", "output", ",", "newline", "=", "True", ")", ":", "click", ".", "echo", "(", "output", ",", "nl", "=", "newline", ")" ]
Outputs a string to the console (stdout).
[ "Outputs", "a", "string", "to", "the", "console", "(", "stdout", ")", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L41-L43
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.err
def err(self, output, newline=True): """Outputs an error string to the console (stderr).""" click.echo(output, nl=newline, err=True)
python
def err(self, output, newline=True): click.echo(output, nl=newline, err=True)
[ "def", "err", "(", "self", ",", "output", ",", "newline", "=", "True", ")", ":", "click", ".", "echo", "(", "output", ",", "nl", "=", "newline", ",", "err", "=", "True", ")" ]
Outputs an error string to the console (stderr).
[ "Outputs", "an", "error", "string", "to", "the", "console", "(", "stderr", ")", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L45-L47
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.fout
def fout(self, output, newline=True): """Format the input and output to the console (stdout).""" if output is not None: self.out(self.fmt(output), newline=newline)
python
def fout(self, output, newline=True): if output is not None: self.out(self.fmt(output), newline=newline)
[ "def", "fout", "(", "self", ",", "output", ",", "newline", "=", "True", ")", ":", "if", "output", "is", "not", "None", ":", "self", ".", "out", "(", "self", ".", "fmt", "(", "output", ")", ",", "newline", "=", "newline", ")" ]
Format the input and output to the console (stdout).
[ "Format", "the", "input", "and", "output", "to", "the", "console", "(", "stdout", ")", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L53-L56
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.input
def input(self, prompt, default=None, show_default=True): """Provide a command prompt.""" return click.prompt(prompt, default=default, show_default=show_default)
python
def input(self, prompt, default=None, show_default=True): return click.prompt(prompt, default=default, show_default=show_default)
[ "def", "input", "(", "self", ",", "prompt", ",", "default", "=", "None", ",", "show_default", "=", "True", ")", ":", "return", "click", ".", "prompt", "(", "prompt", ",", "default", "=", "default", ",", "show_default", "=", "show_default", ")" ]
Provide a command prompt.
[ "Provide", "a", "command", "prompt", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L58-L60
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.getpass
def getpass(self, prompt, default=None): """Provide a password prompt.""" return click.prompt(prompt, hide_input=True, default=default)
python
def getpass(self, prompt, default=None): return click.prompt(prompt, hide_input=True, default=default)
[ "def", "getpass", "(", "self", ",", "prompt", ",", "default", "=", "None", ")", ":", "return", "click", ".", "prompt", "(", "prompt", ",", "hide_input", "=", "True", ",", "default", "=", "default", ")" ]
Provide a password prompt.
[ "Provide", "a", "password", "prompt", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L62-L64
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.list_commands
def list_commands(self, *path): """Command listing.""" path_str = ':'.join(path) commands = [] for command in self.commands: # Filter based on prefix and the segment length if all([command.startswith(path_str), len(path) == command.count(":")]): # offset is used to exclude the path that the caller requested. offset = len(path_str) + 1 if path_str else 0 commands.append(command[offset:]) return sorted(commands)
python
def list_commands(self, *path): path_str = ':'.join(path) commands = [] for command in self.commands: if all([command.startswith(path_str), len(path) == command.count(":")]): offset = len(path_str) + 1 if path_str else 0 commands.append(command[offset:]) return sorted(commands)
[ "def", "list_commands", "(", "self", ",", "*", "path", ")", ":", "path_str", "=", "':'", ".", "join", "(", "path", ")", "commands", "=", "[", "]", "for", "command", "in", "self", ".", "commands", ":", "# Filter based on prefix and the segment length", "if", "all", "(", "[", "command", ".", "startswith", "(", "path_str", ")", ",", "len", "(", "path", ")", "==", "command", ".", "count", "(", "\":\"", ")", "]", ")", ":", "# offset is used to exclude the path that the caller requested.", "offset", "=", "len", "(", "path_str", ")", "+", "1", "if", "path_str", "else", "0", "commands", ".", "append", "(", "command", "[", "offset", ":", "]", ")", "return", "sorted", "(", "commands", ")" ]
Command listing.
[ "Command", "listing", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L67-L82
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.get_command
def get_command(self, *path): """Return command at the given path or raise error.""" path_str = ':'.join(path) if path_str in self.commands: return self.commands[path_str].load() return None
python
def get_command(self, *path): path_str = ':'.join(path) if path_str in self.commands: return self.commands[path_str].load() return None
[ "def", "get_command", "(", "self", ",", "*", "path", ")", ":", "path_str", "=", "':'", ".", "join", "(", "path", ")", "if", "path_str", "in", "self", ".", "commands", ":", "return", "self", ".", "commands", "[", "path_str", "]", ".", "load", "(", ")", "return", "None" ]
Return command at the given path or raise error.
[ "Return", "command", "at", "the", "given", "path", "or", "raise", "error", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L84-L91
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.resolve_alias
def resolve_alias(self, path_str): """Returns the actual command name. Uses the alias mapping.""" if path_str in self.aliases: return self.aliases[path_str] return path_str
python
def resolve_alias(self, path_str): if path_str in self.aliases: return self.aliases[path_str] return path_str
[ "def", "resolve_alias", "(", "self", ",", "path_str", ")", ":", "if", "path_str", "in", "self", ".", "aliases", ":", "return", "self", ".", "aliases", "[", "path_str", "]", "return", "path_str" ]
Returns the actual command name. Uses the alias mapping.
[ "Returns", "the", "actual", "command", "name", ".", "Uses", "the", "alias", "mapping", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L93-L97
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.load
def load(self): """Loads all modules.""" if self._modules_loaded is True: return self.load_modules_from_python(routes.ALL_ROUTES) self.aliases.update(routes.ALL_ALIASES) self._load_modules_from_entry_points('softlayer.cli') self._modules_loaded = True
python
def load(self): if self._modules_loaded is True: return self.load_modules_from_python(routes.ALL_ROUTES) self.aliases.update(routes.ALL_ALIASES) self._load_modules_from_entry_points('softlayer.cli') self._modules_loaded = True
[ "def", "load", "(", "self", ")", ":", "if", "self", ".", "_modules_loaded", "is", "True", ":", "return", "self", ".", "load_modules_from_python", "(", "routes", ".", "ALL_ROUTES", ")", "self", ".", "aliases", ".", "update", "(", "routes", ".", "ALL_ALIASES", ")", "self", ".", "_load_modules_from_entry_points", "(", "'softlayer.cli'", ")", "self", ".", "_modules_loaded", "=", "True" ]
Loads all modules.
[ "Loads", "all", "modules", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L99-L108
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.load_modules_from_python
def load_modules_from_python(self, route_list): """Load modules from the native python source.""" for name, modpath in route_list: if ':' in modpath: path, attr = modpath.split(':', 1) else: path, attr = modpath, None self.commands[name] = ModuleLoader(path, attr=attr)
python
def load_modules_from_python(self, route_list): for name, modpath in route_list: if ':' in modpath: path, attr = modpath.split(':', 1) else: path, attr = modpath, None self.commands[name] = ModuleLoader(path, attr=attr)
[ "def", "load_modules_from_python", "(", "self", ",", "route_list", ")", ":", "for", "name", ",", "modpath", "in", "route_list", ":", "if", "':'", "in", "modpath", ":", "path", ",", "attr", "=", "modpath", ".", "split", "(", "':'", ",", "1", ")", "else", ":", "path", ",", "attr", "=", "modpath", ",", "None", "self", ".", "commands", "[", "name", "]", "=", "ModuleLoader", "(", "path", ",", "attr", "=", "attr", ")" ]
Load modules from the native python source.
[ "Load", "modules", "from", "the", "native", "python", "source", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L110-L117
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment._load_modules_from_entry_points
def _load_modules_from_entry_points(self, entry_point_group): """Load modules from the entry_points (slower). Entry points can be used to add new commands to the CLI. Usage: entry_points={'softlayer.cli': ['new-cmd = mymodule.new_cmd.cli']} """ for obj in pkg_resources.iter_entry_points(group=entry_point_group, name=None): self.commands[obj.name] = obj
python
def _load_modules_from_entry_points(self, entry_point_group): for obj in pkg_resources.iter_entry_points(group=entry_point_group, name=None): self.commands[obj.name] = obj
[ "def", "_load_modules_from_entry_points", "(", "self", ",", "entry_point_group", ")", ":", "for", "obj", "in", "pkg_resources", ".", "iter_entry_points", "(", "group", "=", "entry_point_group", ",", "name", "=", "None", ")", ":", "self", ".", "commands", "[", "obj", ".", "name", "]", "=", "obj" ]
Load modules from the entry_points (slower). Entry points can be used to add new commands to the CLI. Usage: entry_points={'softlayer.cli': ['new-cmd = mymodule.new_cmd.cli']}
[ "Load", "modules", "from", "the", "entry_points", "(", "slower", ")", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L119-L131
softlayer/softlayer-python
SoftLayer/CLI/environment.py
Environment.ensure_client
def ensure_client(self, config_file=None, is_demo=False, proxy=None): """Create a new SLAPI client to the environment. This will be a no-op if there is already a client in this environment. """ if self.client is not None: return # Environment can be passed in explicitly. This is used for testing if is_demo: client = SoftLayer.BaseClient( transport=SoftLayer.FixtureTransport(), auth=None, ) else: # Create SL Client client = SoftLayer.create_client_from_env( proxy=proxy, config_file=config_file, ) self.client = client
python
def ensure_client(self, config_file=None, is_demo=False, proxy=None): if self.client is not None: return if is_demo: client = SoftLayer.BaseClient( transport=SoftLayer.FixtureTransport(), auth=None, ) else: client = SoftLayer.create_client_from_env( proxy=proxy, config_file=config_file, ) self.client = client
[ "def", "ensure_client", "(", "self", ",", "config_file", "=", "None", ",", "is_demo", "=", "False", ",", "proxy", "=", "None", ")", ":", "if", "self", ".", "client", "is", "not", "None", ":", "return", "# Environment can be passed in explicitly. This is used for testing", "if", "is_demo", ":", "client", "=", "SoftLayer", ".", "BaseClient", "(", "transport", "=", "SoftLayer", ".", "FixtureTransport", "(", ")", ",", "auth", "=", "None", ",", ")", "else", ":", "# Create SL Client", "client", "=", "SoftLayer", ".", "create_client_from_env", "(", "proxy", "=", "proxy", ",", "config_file", "=", "config_file", ",", ")", "self", ".", "client", "=", "client" ]
Create a new SLAPI client to the environment. This will be a no-op if there is already a client in this environment.
[ "Create", "a", "new", "SLAPI", "client", "to", "the", "environment", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L133-L153
softlayer/softlayer-python
SoftLayer/CLI/environment.py
ModuleLoader.load
def load(self): """load and return the module/attribute.""" module = importlib.import_module(self.import_path) if self.attr: return getattr(module, self.attr) return module
python
def load(self): module = importlib.import_module(self.import_path) if self.attr: return getattr(module, self.attr) return module
[ "def", "load", "(", "self", ")", ":", "module", "=", "importlib", ".", "import_module", "(", "self", ".", "import_path", ")", "if", "self", ".", "attr", ":", "return", "getattr", "(", "module", ",", "self", ".", "attr", ")", "return", "module" ]
load and return the module/attribute.
[ "load", "and", "return", "the", "module", "/", "attribute", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/environment.py#L163-L168
softlayer/softlayer-python
SoftLayer/CLI/dns/zone_delete.py
cli
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)
python
def cli(env, 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", ",", "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", ")" ]
Delete zone.
[ "Delete", "zone", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dns/zone_delete.py#L16-L25
softlayer/softlayer-python
SoftLayer/CLI/helpers.py
multi_option
def multi_option(*param_decls, **attrs): """modify help text and indicate option is permitted multiple times :param param_decls: :param attrs: :return: """ attrhelp = attrs.get('help', None) if attrhelp is not None: newhelp = attrhelp + " (multiple occurrence permitted)" attrs['help'] = newhelp attrs['multiple'] = True return click.option(*param_decls, **attrs)
python
def multi_option(*param_decls, **attrs): attrhelp = attrs.get('help', None) if attrhelp is not None: newhelp = attrhelp + " (multiple occurrence permitted)" attrs['help'] = newhelp attrs['multiple'] = True return click.option(*param_decls, **attrs)
[ "def", "multi_option", "(", "*", "param_decls", ",", "*", "*", "attrs", ")", ":", "attrhelp", "=", "attrs", ".", "get", "(", "'help'", ",", "None", ")", "if", "attrhelp", "is", "not", "None", ":", "newhelp", "=", "attrhelp", "+", "\" (multiple occurrence permitted)\"", "attrs", "[", "'help'", "]", "=", "newhelp", "attrs", "[", "'multiple'", "]", "=", "True", "return", "click", ".", "option", "(", "*", "param_decls", ",", "*", "*", "attrs", ")" ]
modify help text and indicate option is permitted multiple times :param param_decls: :param attrs: :return:
[ "modify", "help", "text", "and", "indicate", "option", "is", "permitted", "multiple", "times" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/helpers.py#L14-L27
softlayer/softlayer-python
SoftLayer/CLI/helpers.py
resolve_id
def resolve_id(resolver, identifier, name='object'): """Resolves a single id using a resolver function. :param resolver: function that resolves ids. Should return None or a list of ids. :param string identifier: a string identifier used to resolve ids :param string name: the object type, to be used in error messages """ try: return int(identifier) except ValueError: pass # It was worth a shot ids = resolver(identifier) if len(ids) == 0: raise exceptions.CLIAbort("Error: Unable to find %s '%s'" % (name, identifier)) if len(ids) > 1: raise exceptions.CLIAbort( "Error: Multiple %s found for '%s': %s" % (name, identifier, ', '.join([str(_id) for _id in ids]))) return ids[0]
python
def resolve_id(resolver, identifier, name='object'): try: return int(identifier) except ValueError: pass ids = resolver(identifier) if len(ids) == 0: raise exceptions.CLIAbort("Error: Unable to find %s '%s'" % (name, identifier)) if len(ids) > 1: raise exceptions.CLIAbort( "Error: Multiple %s found for '%s': %s" % (name, identifier, ', '.join([str(_id) for _id in ids]))) return ids[0]
[ "def", "resolve_id", "(", "resolver", ",", "identifier", ",", "name", "=", "'object'", ")", ":", "try", ":", "return", "int", "(", "identifier", ")", "except", "ValueError", ":", "pass", "# It was worth a shot", "ids", "=", "resolver", "(", "identifier", ")", "if", "len", "(", "ids", ")", "==", "0", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Error: Unable to find %s '%s'\"", "%", "(", "name", ",", "identifier", ")", ")", "if", "len", "(", "ids", ")", ">", "1", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Error: Multiple %s found for '%s': %s\"", "%", "(", "name", ",", "identifier", ",", "', '", ".", "join", "(", "[", "str", "(", "_id", ")", "for", "_id", "in", "ids", "]", ")", ")", ")", "return", "ids", "[", "0", "]" ]
Resolves a single id using a resolver function. :param resolver: function that resolves ids. Should return None or a list of ids. :param string identifier: a string identifier used to resolve ids :param string name: the object type, to be used in error messages
[ "Resolves", "a", "single", "id", "using", "a", "resolver", "function", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/helpers.py#L30-L53
softlayer/softlayer-python
SoftLayer/CLI/ssl/remove.py
cli
def cli(env, identifier): """Remove SSL certificate.""" manager = SoftLayer.SSLManager(env.client) if not (env.skip_confirmations or formatting.no_going_back('yes')): raise exceptions.CLIAbort("Aborted.") manager.remove_certificate(identifier)
python
def cli(env, identifier): manager = SoftLayer.SSLManager(env.client) if not (env.skip_confirmations or formatting.no_going_back('yes')): raise exceptions.CLIAbort("Aborted.") manager.remove_certificate(identifier)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "manager", "=", "SoftLayer", ".", "SSLManager", "(", "env", ".", "client", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "no_going_back", "(", "'yes'", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Aborted.\"", ")", "manager", ".", "remove_certificate", "(", "identifier", ")" ]
Remove SSL certificate.
[ "Remove", "SSL", "certificate", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ssl/remove.py#L15-L22
softlayer/softlayer-python
SoftLayer/CLI/file/snapshot/order.py
cli
def cli(env, volume_id, capacity, tier, upgrade): """Order snapshot space for a file storage volume.""" file_manager = SoftLayer.FileStorageManager(env.client) if tier is not None: tier = float(tier) try: order = file_manager.order_snapshot_space( volume_id, capacity=capacity, tier=tier, upgrade=upgrade ) except ValueError as ex: raise exceptions.ArgumentError(str(ex)) if 'placedOrder' in order.keys(): click.echo("Order #{0} placed successfully!".format( order['placedOrder']['id'])) for item in order['placedOrder']['items']: click.echo(" > %s" % item['description']) if 'status' in order['placedOrder'].keys(): click.echo(" > Order status: %s" % order['placedOrder']['status']) else: click.echo("Order could not be placed! Please verify your options " + "and try again.")
python
def cli(env, volume_id, capacity, tier, upgrade): file_manager = SoftLayer.FileStorageManager(env.client) if tier is not None: tier = float(tier) try: order = file_manager.order_snapshot_space( volume_id, capacity=capacity, tier=tier, upgrade=upgrade ) except ValueError as ex: raise exceptions.ArgumentError(str(ex)) if 'placedOrder' in order.keys(): click.echo("Order order['placedOrder']['id'])) for item in order['placedOrder']['items']: click.echo(" > %s" % item['description']) if 'status' in order['placedOrder'].keys(): click.echo(" > Order status: %s" % order['placedOrder']['status']) else: click.echo("Order could not be placed! Please verify your options " + "and try again.")
[ "def", "cli", "(", "env", ",", "volume_id", ",", "capacity", ",", "tier", ",", "upgrade", ")", ":", "file_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "if", "tier", "is", "not", "None", ":", "tier", "=", "float", "(", "tier", ")", "try", ":", "order", "=", "file_manager", ".", "order_snapshot_space", "(", "volume_id", ",", "capacity", "=", "capacity", ",", "tier", "=", "tier", ",", "upgrade", "=", "upgrade", ")", "except", "ValueError", "as", "ex", ":", "raise", "exceptions", ".", "ArgumentError", "(", "str", "(", "ex", ")", ")", "if", "'placedOrder'", "in", "order", ".", "keys", "(", ")", ":", "click", ".", "echo", "(", "\"Order #{0} placed successfully!\"", ".", "format", "(", "order", "[", "'placedOrder'", "]", "[", "'id'", "]", ")", ")", "for", "item", "in", "order", "[", "'placedOrder'", "]", "[", "'items'", "]", ":", "click", ".", "echo", "(", "\" > %s\"", "%", "item", "[", "'description'", "]", ")", "if", "'status'", "in", "order", "[", "'placedOrder'", "]", ".", "keys", "(", ")", ":", "click", ".", "echo", "(", "\" > Order status: %s\"", "%", "order", "[", "'placedOrder'", "]", "[", "'status'", "]", ")", "else", ":", "click", ".", "echo", "(", "\"Order could not be placed! Please verify your options \"", "+", "\"and try again.\"", ")" ]
Order snapshot space for a file storage volume.
[ "Order", "snapshot", "space", "for", "a", "file", "storage", "volume", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/order.py#L27-L53
softlayer/softlayer-python
SoftLayer/CLI/virt/edit.py
cli
def cli(env, identifier, domain, userfile, tag, hostname, userdata, public_speed, private_speed): """Edit a virtual server's details.""" if userdata and userfile: raise exceptions.ArgumentError( '[-u | --userdata] not allowed with [-F | --userfile]') data = {} if userdata: data['userdata'] = userdata elif userfile: with open(userfile, 'r') as userfile_obj: data['userdata'] = userfile_obj.read() data['hostname'] = hostname data['domain'] = domain if tag: data['tags'] = ','.join(tag) vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not vsi.edit(vs_id, **data): raise exceptions.CLIAbort("Failed to update virtual server") if public_speed is not None: vsi.change_port_speed(vs_id, True, int(public_speed)) if private_speed is not None: vsi.change_port_speed(vs_id, False, int(private_speed))
python
def cli(env, identifier, domain, userfile, tag, hostname, userdata, public_speed, private_speed): if userdata and userfile: raise exceptions.ArgumentError( '[-u | --userdata] not allowed with [-F | --userfile]') data = {} if userdata: data['userdata'] = userdata elif userfile: with open(userfile, 'r') as userfile_obj: data['userdata'] = userfile_obj.read() data['hostname'] = hostname data['domain'] = domain if tag: data['tags'] = ','.join(tag) vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') if not vsi.edit(vs_id, **data): raise exceptions.CLIAbort("Failed to update virtual server") if public_speed is not None: vsi.change_port_speed(vs_id, True, int(public_speed)) if private_speed is not None: vsi.change_port_speed(vs_id, False, int(private_speed))
[ "def", "cli", "(", "env", ",", "identifier", ",", "domain", ",", "userfile", ",", "tag", ",", "hostname", ",", "userdata", ",", "public_speed", ",", "private_speed", ")", ":", "if", "userdata", "and", "userfile", ":", "raise", "exceptions", ".", "ArgumentError", "(", "'[-u | --userdata] not allowed with [-F | --userfile]'", ")", "data", "=", "{", "}", "if", "userdata", ":", "data", "[", "'userdata'", "]", "=", "userdata", "elif", "userfile", ":", "with", "open", "(", "userfile", ",", "'r'", ")", "as", "userfile_obj", ":", "data", "[", "'userdata'", "]", "=", "userfile_obj", ".", "read", "(", ")", "data", "[", "'hostname'", "]", "=", "hostname", "data", "[", "'domain'", "]", "=", "domain", "if", "tag", ":", "data", "[", "'tags'", "]", "=", "','", ".", "join", "(", "tag", ")", "vsi", "=", "SoftLayer", ".", "VSManager", "(", "env", ".", "client", ")", "vs_id", "=", "helpers", ".", "resolve_id", "(", "vsi", ".", "resolve_ids", ",", "identifier", ",", "'VS'", ")", "if", "not", "vsi", ".", "edit", "(", "vs_id", ",", "*", "*", "data", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Failed to update virtual server\"", ")", "if", "public_speed", "is", "not", "None", ":", "vsi", ".", "change_port_speed", "(", "vs_id", ",", "True", ",", "int", "(", "public_speed", ")", ")", "if", "private_speed", "is", "not", "None", ":", "vsi", ".", "change_port_speed", "(", "vs_id", ",", "False", ",", "int", "(", "private_speed", ")", ")" ]
Edit a virtual server's details.
[ "Edit", "a", "virtual", "server", "s", "details", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/edit.py#L33-L64
softlayer/softlayer-python
SoftLayer/CLI/file/replication/order.py
cli
def cli(env, volume_id, snapshot_schedule, location, tier): """Order a file storage replica volume.""" file_manager = SoftLayer.FileStorageManager(env.client) if tier is not None: tier = float(tier) try: order = file_manager.order_replicant_volume( volume_id, snapshot_schedule=snapshot_schedule, location=location, tier=tier, ) except ValueError as ex: raise exceptions.ArgumentError(str(ex)) if 'placedOrder' in order.keys(): click.echo("Order #{0} placed successfully!".format( order['placedOrder']['id'])) for item in order['placedOrder']['items']: click.echo(" > %s" % item['description']) else: click.echo("Order could not be placed! Please verify your options " + "and try again.")
python
def cli(env, volume_id, snapshot_schedule, location, tier): file_manager = SoftLayer.FileStorageManager(env.client) if tier is not None: tier = float(tier) try: order = file_manager.order_replicant_volume( volume_id, snapshot_schedule=snapshot_schedule, location=location, tier=tier, ) except ValueError as ex: raise exceptions.ArgumentError(str(ex)) if 'placedOrder' in order.keys(): click.echo("Order order['placedOrder']['id'])) for item in order['placedOrder']['items']: click.echo(" > %s" % item['description']) else: click.echo("Order could not be placed! Please verify your options " + "and try again.")
[ "def", "cli", "(", "env", ",", "volume_id", ",", "snapshot_schedule", ",", "location", ",", "tier", ")", ":", "file_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "if", "tier", "is", "not", "None", ":", "tier", "=", "float", "(", "tier", ")", "try", ":", "order", "=", "file_manager", ".", "order_replicant_volume", "(", "volume_id", ",", "snapshot_schedule", "=", "snapshot_schedule", ",", "location", "=", "location", ",", "tier", "=", "tier", ",", ")", "except", "ValueError", "as", "ex", ":", "raise", "exceptions", ".", "ArgumentError", "(", "str", "(", "ex", ")", ")", "if", "'placedOrder'", "in", "order", ".", "keys", "(", ")", ":", "click", ".", "echo", "(", "\"Order #{0} placed successfully!\"", ".", "format", "(", "order", "[", "'placedOrder'", "]", "[", "'id'", "]", ")", ")", "for", "item", "in", "order", "[", "'placedOrder'", "]", "[", "'items'", "]", ":", "click", ".", "echo", "(", "\" > %s\"", "%", "item", "[", "'description'", "]", ")", "else", ":", "click", ".", "echo", "(", "\"Order could not be placed! Please verify your options \"", "+", "\"and try again.\"", ")" ]
Order a file storage replica volume.
[ "Order", "a", "file", "storage", "replica", "volume", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/replication/order.py#L29-L53
softlayer/softlayer-python
SoftLayer/CLI/block/replication/failback.py
cli
def cli(env, volume_id, replicant_id): """Failback a block volume from the given replicant volume.""" block_storage_manager = SoftLayer.BlockStorageManager(env.client) success = block_storage_manager.failback_from_replicant( volume_id, replicant_id ) if success: click.echo("Failback from replicant is now in progress.") else: click.echo("Failback operation could not be initiated.")
python
def cli(env, volume_id, replicant_id): block_storage_manager = SoftLayer.BlockStorageManager(env.client) success = block_storage_manager.failback_from_replicant( volume_id, replicant_id ) if success: click.echo("Failback from replicant is now in progress.") else: click.echo("Failback operation could not be initiated.")
[ "def", "cli", "(", "env", ",", "volume_id", ",", "replicant_id", ")", ":", "block_storage_manager", "=", "SoftLayer", ".", "BlockStorageManager", "(", "env", ".", "client", ")", "success", "=", "block_storage_manager", ".", "failback_from_replicant", "(", "volume_id", ",", "replicant_id", ")", "if", "success", ":", "click", ".", "echo", "(", "\"Failback from replicant is now in progress.\"", ")", "else", ":", "click", ".", "echo", "(", "\"Failback operation could not be initiated.\"", ")" ]
Failback a block volume from the given replicant volume.
[ "Failback", "a", "block", "volume", "from", "the", "given", "replicant", "volume", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/replication/failback.py#L13-L25
softlayer/softlayer-python
SoftLayer/CLI/virt/placementgroup/detail.py
cli
def cli(env, identifier): """View details of a placement group. 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') result = manager.get_object(group_id) table = formatting.Table(["Id", "Name", "Backend Router", "Rule", "Created"]) table.add_row([ result['id'], result['name'], result['backendRouter']['hostname'], result['rule']['name'], result['createDate'] ]) guest_table = formatting.Table([ "Id", "FQDN", "Primary IP", "Backend IP", "CPU", "Memory", "Provisioned", "Transaction" ]) for guest in result['guests']: guest_table.add_row([ guest.get('id'), guest.get('fullyQualifiedDomainName'), guest.get('primaryIpAddress'), guest.get('primaryBackendIpAddress'), guest.get('maxCpu'), guest.get('maxMemory'), guest.get('provisionDate'), formatting.active_txn(guest) ]) env.fout(table) env.fout(guest_table)
python
def cli(env, identifier): manager = PlacementManager(env.client) group_id = helpers.resolve_id(manager.resolve_ids, identifier, 'placement_group') result = manager.get_object(group_id) table = formatting.Table(["Id", "Name", "Backend Router", "Rule", "Created"]) table.add_row([ result['id'], result['name'], result['backendRouter']['hostname'], result['rule']['name'], result['createDate'] ]) guest_table = formatting.Table([ "Id", "FQDN", "Primary IP", "Backend IP", "CPU", "Memory", "Provisioned", "Transaction" ]) for guest in result['guests']: guest_table.add_row([ guest.get('id'), guest.get('fullyQualifiedDomainName'), guest.get('primaryIpAddress'), guest.get('primaryBackendIpAddress'), guest.get('maxCpu'), guest.get('maxMemory'), guest.get('provisionDate'), formatting.active_txn(guest) ]) env.fout(table) env.fout(guest_table)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "manager", "=", "PlacementManager", "(", "env", ".", "client", ")", "group_id", "=", "helpers", ".", "resolve_id", "(", "manager", ".", "resolve_ids", ",", "identifier", ",", "'placement_group'", ")", "result", "=", "manager", ".", "get_object", "(", "group_id", ")", "table", "=", "formatting", ".", "Table", "(", "[", "\"Id\"", ",", "\"Name\"", ",", "\"Backend Router\"", ",", "\"Rule\"", ",", "\"Created\"", "]", ")", "table", ".", "add_row", "(", "[", "result", "[", "'id'", "]", ",", "result", "[", "'name'", "]", ",", "result", "[", "'backendRouter'", "]", "[", "'hostname'", "]", ",", "result", "[", "'rule'", "]", "[", "'name'", "]", ",", "result", "[", "'createDate'", "]", "]", ")", "guest_table", "=", "formatting", ".", "Table", "(", "[", "\"Id\"", ",", "\"FQDN\"", ",", "\"Primary IP\"", ",", "\"Backend IP\"", ",", "\"CPU\"", ",", "\"Memory\"", ",", "\"Provisioned\"", ",", "\"Transaction\"", "]", ")", "for", "guest", "in", "result", "[", "'guests'", "]", ":", "guest_table", ".", "add_row", "(", "[", "guest", ".", "get", "(", "'id'", ")", ",", "guest", ".", "get", "(", "'fullyQualifiedDomainName'", ")", ",", "guest", ".", "get", "(", "'primaryIpAddress'", ")", ",", "guest", ".", "get", "(", "'primaryBackendIpAddress'", ")", ",", "guest", ".", "get", "(", "'maxCpu'", ")", ",", "guest", ".", "get", "(", "'maxMemory'", ")", ",", "guest", ".", "get", "(", "'provisionDate'", ")", ",", "formatting", ".", "active_txn", "(", "guest", ")", "]", ")", "env", ".", "fout", "(", "table", ")", "env", ".", "fout", "(", "guest_table", ")" ]
View details of a placement group. IDENTIFIER can be either the Name or Id of the placement group you want to view
[ "View", "details", "of", "a", "placement", "group", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/placementgroup/detail.py#L14-L54
softlayer/softlayer-python
SoftLayer/CLI/user/list.py
cli
def cli(env, columns): """List Users.""" mgr = SoftLayer.UserManager(env.client) users = mgr.list_users() table = formatting.Table(columns.columns) for user in users: table.add_row([value or formatting.blank() for value in columns.row(user)]) env.fout(table)
python
def cli(env, columns): mgr = SoftLayer.UserManager(env.client) users = mgr.list_users() table = formatting.Table(columns.columns) for user in users: table.add_row([value or formatting.blank() for value in columns.row(user)]) env.fout(table)
[ "def", "cli", "(", "env", ",", "columns", ")", ":", "mgr", "=", "SoftLayer", ".", "UserManager", "(", "env", ".", "client", ")", "users", "=", "mgr", ".", "list_users", "(", ")", "table", "=", "formatting", ".", "Table", "(", "columns", ".", "columns", ")", "for", "user", "in", "users", ":", "table", ".", "add_row", "(", "[", "value", "or", "formatting", ".", "blank", "(", ")", "for", "value", "in", "columns", ".", "row", "(", "user", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List Users.
[ "List", "Users", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/user/list.py#L37-L48
softlayer/softlayer-python
SoftLayer/CLI/ticket/update.py
cli
def cli(env, identifier, body): """Adds an update to an existing ticket.""" mgr = SoftLayer.TicketManager(env.client) ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket') if body is None: body = click.edit('\n\n' + ticket.TEMPLATE_MSG) mgr.update_ticket(ticket_id=ticket_id, body=body) env.fout("Ticket Updated!")
python
def cli(env, identifier, body): mgr = SoftLayer.TicketManager(env.client) ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket') if body is None: body = click.edit('\n\n' + ticket.TEMPLATE_MSG) mgr.update_ticket(ticket_id=ticket_id, body=body) env.fout("Ticket Updated!")
[ "def", "cli", "(", "env", ",", "identifier", ",", "body", ")", ":", "mgr", "=", "SoftLayer", ".", "TicketManager", "(", "env", ".", "client", ")", "ticket_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_ids", ",", "identifier", ",", "'ticket'", ")", "if", "body", "is", "None", ":", "body", "=", "click", ".", "edit", "(", "'\\n\\n'", "+", "ticket", ".", "TEMPLATE_MSG", ")", "mgr", ".", "update_ticket", "(", "ticket_id", "=", "ticket_id", ",", "body", "=", "body", ")", "env", ".", "fout", "(", "\"Ticket Updated!\"", ")" ]
Adds an update to an existing ticket.
[ "Adds", "an", "update", "to", "an", "existing", "ticket", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/ticket/update.py#L16-L26
softlayer/softlayer-python
SoftLayer/CLI/order/quote_detail.py
cli
def cli(env, quote): """View a quote""" manager = ordering.OrderingManager(env.client) result = manager.get_quote_details(quote) package = result['order']['items'][0]['package'] title = "{} - Package: {}, Id {}".format(result.get('name'), package['keyName'], package['id']) table = formatting.Table([ 'Category', 'Description', 'Quantity', 'Recurring', 'One Time' ], title=title) table.align['Category'] = 'l' table.align['Description'] = 'l' items = lookup(result, 'order', 'items') for item in items: table.add_row([ item.get('categoryCode'), item.get('description'), item.get('quantity'), item.get('recurringFee'), item.get('oneTimeFee') ]) env.fout(table)
python
def cli(env, quote): manager = ordering.OrderingManager(env.client) result = manager.get_quote_details(quote) package = result['order']['items'][0]['package'] title = "{} - Package: {}, Id {}".format(result.get('name'), package['keyName'], package['id']) table = formatting.Table([ 'Category', 'Description', 'Quantity', 'Recurring', 'One Time' ], title=title) table.align['Category'] = 'l' table.align['Description'] = 'l' items = lookup(result, 'order', 'items') for item in items: table.add_row([ item.get('categoryCode'), item.get('description'), item.get('quantity'), item.get('recurringFee'), item.get('oneTimeFee') ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "quote", ")", ":", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "result", "=", "manager", ".", "get_quote_details", "(", "quote", ")", "package", "=", "result", "[", "'order'", "]", "[", "'items'", "]", "[", "0", "]", "[", "'package'", "]", "title", "=", "\"{} - Package: {}, Id {}\"", ".", "format", "(", "result", ".", "get", "(", "'name'", ")", ",", "package", "[", "'keyName'", "]", ",", "package", "[", "'id'", "]", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'Category'", ",", "'Description'", ",", "'Quantity'", ",", "'Recurring'", ",", "'One Time'", "]", ",", "title", "=", "title", ")", "table", ".", "align", "[", "'Category'", "]", "=", "'l'", "table", ".", "align", "[", "'Description'", "]", "=", "'l'", "items", "=", "lookup", "(", "result", ",", "'order'", ",", "'items'", ")", "for", "item", "in", "items", ":", "table", ".", "add_row", "(", "[", "item", ".", "get", "(", "'categoryCode'", ")", ",", "item", ".", "get", "(", "'description'", ")", ",", "item", ".", "get", "(", "'quantity'", ")", ",", "item", ".", "get", "(", "'recurringFee'", ")", ",", "item", ".", "get", "(", "'oneTimeFee'", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
View a quote
[ "View", "a", "quote" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/quote_detail.py#L14-L38
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/list.py
cli
def cli(env, sortby, limit): """List security groups.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby sgs = mgr.list_securitygroups(limit=limit) for secgroup in sgs: table.add_row([ secgroup['id'], secgroup.get('name') or formatting.blank(), secgroup.get('description') or formatting.blank(), ]) env.fout(table)
python
def cli(env, sortby, limit): mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby sgs = mgr.list_securitygroups(limit=limit) for secgroup in sgs: table.add_row([ secgroup['id'], secgroup.get('name') or formatting.blank(), secgroup.get('description') or formatting.blank(), ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "sortby", ",", "limit", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "table", ".", "sortby", "=", "sortby", "sgs", "=", "mgr", ".", "list_securitygroups", "(", "limit", "=", "limit", ")", "for", "secgroup", "in", "sgs", ":", "table", ".", "add_row", "(", "[", "secgroup", "[", "'id'", "]", ",", "secgroup", ".", "get", "(", "'name'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "secgroup", ".", "get", "(", "'description'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List security groups.
[ "List", "security", "groups", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/list.py#L24-L40
softlayer/softlayer-python
SoftLayer/CLI/firewall/edit.py
parse_rules
def parse_rules(content=None): """Helper to parse the input from the user into a list of rules. :param string content: the content of the editor :returns: a list of rules """ rules = content.split(DELIMITER) parsed_rules = list() order = 1 for rule in rules: if rule.strip() == '': continue parsed_rule = {} lines = rule.split("\n") parsed_rule['orderValue'] = order order += 1 for line in lines: if line.strip() == '': continue key_value = line.strip().split(':') key = key_value[0].strip() value = key_value[1].strip() if key == 'action': parsed_rule['action'] = value elif key == 'protocol': parsed_rule['protocol'] = value elif key == 'source_ip_address': parsed_rule['sourceIpAddress'] = value elif key == 'source_ip_subnet_mask': parsed_rule['sourceIpSubnetMask'] = value elif key == 'destination_ip_address': parsed_rule['destinationIpAddress'] = value elif key == 'destination_ip_subnet_mask': parsed_rule['destinationIpSubnetMask'] = value elif key == 'destination_port_range_start': parsed_rule['destinationPortRangeStart'] = int(value) elif key == 'destination_port_range_end': parsed_rule['destinationPortRangeEnd'] = int(value) elif key == 'version': parsed_rule['version'] = int(value) parsed_rules.append(parsed_rule) return parsed_rules
python
def parse_rules(content=None): rules = content.split(DELIMITER) parsed_rules = list() order = 1 for rule in rules: if rule.strip() == '': continue parsed_rule = {} lines = rule.split("\n") parsed_rule['orderValue'] = order order += 1 for line in lines: if line.strip() == '': continue key_value = line.strip().split(':') key = key_value[0].strip() value = key_value[1].strip() if key == 'action': parsed_rule['action'] = value elif key == 'protocol': parsed_rule['protocol'] = value elif key == 'source_ip_address': parsed_rule['sourceIpAddress'] = value elif key == 'source_ip_subnet_mask': parsed_rule['sourceIpSubnetMask'] = value elif key == 'destination_ip_address': parsed_rule['destinationIpAddress'] = value elif key == 'destination_ip_subnet_mask': parsed_rule['destinationIpSubnetMask'] = value elif key == 'destination_port_range_start': parsed_rule['destinationPortRangeStart'] = int(value) elif key == 'destination_port_range_end': parsed_rule['destinationPortRangeEnd'] = int(value) elif key == 'version': parsed_rule['version'] = int(value) parsed_rules.append(parsed_rule) return parsed_rules
[ "def", "parse_rules", "(", "content", "=", "None", ")", ":", "rules", "=", "content", ".", "split", "(", "DELIMITER", ")", "parsed_rules", "=", "list", "(", ")", "order", "=", "1", "for", "rule", "in", "rules", ":", "if", "rule", ".", "strip", "(", ")", "==", "''", ":", "continue", "parsed_rule", "=", "{", "}", "lines", "=", "rule", ".", "split", "(", "\"\\n\"", ")", "parsed_rule", "[", "'orderValue'", "]", "=", "order", "order", "+=", "1", "for", "line", "in", "lines", ":", "if", "line", ".", "strip", "(", ")", "==", "''", ":", "continue", "key_value", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "':'", ")", "key", "=", "key_value", "[", "0", "]", ".", "strip", "(", ")", "value", "=", "key_value", "[", "1", "]", ".", "strip", "(", ")", "if", "key", "==", "'action'", ":", "parsed_rule", "[", "'action'", "]", "=", "value", "elif", "key", "==", "'protocol'", ":", "parsed_rule", "[", "'protocol'", "]", "=", "value", "elif", "key", "==", "'source_ip_address'", ":", "parsed_rule", "[", "'sourceIpAddress'", "]", "=", "value", "elif", "key", "==", "'source_ip_subnet_mask'", ":", "parsed_rule", "[", "'sourceIpSubnetMask'", "]", "=", "value", "elif", "key", "==", "'destination_ip_address'", ":", "parsed_rule", "[", "'destinationIpAddress'", "]", "=", "value", "elif", "key", "==", "'destination_ip_subnet_mask'", ":", "parsed_rule", "[", "'destinationIpSubnetMask'", "]", "=", "value", "elif", "key", "==", "'destination_port_range_start'", ":", "parsed_rule", "[", "'destinationPortRangeStart'", "]", "=", "int", "(", "value", ")", "elif", "key", "==", "'destination_port_range_end'", ":", "parsed_rule", "[", "'destinationPortRangeEnd'", "]", "=", "int", "(", "value", ")", "elif", "key", "==", "'version'", ":", "parsed_rule", "[", "'version'", "]", "=", "int", "(", "value", ")", "parsed_rules", ".", "append", "(", "parsed_rule", ")", "return", "parsed_rules" ]
Helper to parse the input from the user into a list of rules. :param string content: the content of the editor :returns: a list of rules
[ "Helper", "to", "parse", "the", "input", "from", "the", "user", "into", "a", "list", "of", "rules", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/edit.py#L19-L60
softlayer/softlayer-python
SoftLayer/CLI/firewall/edit.py
open_editor
def open_editor(rules=None, content=None): """Helper to open an editor for editing the firewall rules. This method takes two parameters, if content is provided, that means that submitting the rules failed and we are allowing the user to re-edit what they provided. If content is not provided, the rules retrieved from the firewall will be displayed to the user. :param list rules: A list containing the rules of the firewall :param string content: the content that the user provided in the editor :returns: a formatted string that get be pushed into the editor """ # Let's get the default EDITOR of the environment, # use nano if none is specified editor = os.environ.get('EDITOR', 'nano') with tempfile.NamedTemporaryFile(suffix=".tmp") as tfile: if content: # if content is provided, just display it as is tfile.write(content) tfile.flush() subprocess.call([editor, tfile.name]) tfile.seek(0) data = tfile.read() return data if not rules: # if the firewall has no rules, provide a template tfile.write(DELIMITER) tfile.write(get_formatted_rule()) else: # if the firewall has rules, display those to the user for rule in rules: tfile.write(DELIMITER) tfile.write(get_formatted_rule(rule)) tfile.write(DELIMITER) tfile.flush() subprocess.call([editor, tfile.name]) tfile.seek(0) data = tfile.read() return data
python
def open_editor(rules=None, content=None): editor = os.environ.get('EDITOR', 'nano') with tempfile.NamedTemporaryFile(suffix=".tmp") as tfile: if content: tfile.write(content) tfile.flush() subprocess.call([editor, tfile.name]) tfile.seek(0) data = tfile.read() return data if not rules: tfile.write(DELIMITER) tfile.write(get_formatted_rule()) else: for rule in rules: tfile.write(DELIMITER) tfile.write(get_formatted_rule(rule)) tfile.write(DELIMITER) tfile.flush() subprocess.call([editor, tfile.name]) tfile.seek(0) data = tfile.read() return data
[ "def", "open_editor", "(", "rules", "=", "None", ",", "content", "=", "None", ")", ":", "# Let's get the default EDITOR of the environment,", "# use nano if none is specified", "editor", "=", "os", ".", "environ", ".", "get", "(", "'EDITOR'", ",", "'nano'", ")", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "\".tmp\"", ")", "as", "tfile", ":", "if", "content", ":", "# if content is provided, just display it as is", "tfile", ".", "write", "(", "content", ")", "tfile", ".", "flush", "(", ")", "subprocess", ".", "call", "(", "[", "editor", ",", "tfile", ".", "name", "]", ")", "tfile", ".", "seek", "(", "0", ")", "data", "=", "tfile", ".", "read", "(", ")", "return", "data", "if", "not", "rules", ":", "# if the firewall has no rules, provide a template", "tfile", ".", "write", "(", "DELIMITER", ")", "tfile", ".", "write", "(", "get_formatted_rule", "(", ")", ")", "else", ":", "# if the firewall has rules, display those to the user", "for", "rule", "in", "rules", ":", "tfile", ".", "write", "(", "DELIMITER", ")", "tfile", ".", "write", "(", "get_formatted_rule", "(", "rule", ")", ")", "tfile", ".", "write", "(", "DELIMITER", ")", "tfile", ".", "flush", "(", ")", "subprocess", ".", "call", "(", "[", "editor", ",", "tfile", ".", "name", "]", ")", "tfile", ".", "seek", "(", "0", ")", "data", "=", "tfile", ".", "read", "(", ")", "return", "data" ]
Helper to open an editor for editing the firewall rules. This method takes two parameters, if content is provided, that means that submitting the rules failed and we are allowing the user to re-edit what they provided. If content is not provided, the rules retrieved from the firewall will be displayed to the user. :param list rules: A list containing the rules of the firewall :param string content: the content that the user provided in the editor :returns: a formatted string that get be pushed into the editor
[ "Helper", "to", "open", "an", "editor", "for", "editing", "the", "firewall", "rules", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/edit.py#L63-L105
softlayer/softlayer-python
SoftLayer/CLI/firewall/edit.py
get_formatted_rule
def get_formatted_rule(rule=None): """Helper to format the rule into a user friendly format. :param dict rule: A dict containing one rule of the firewall :returns: a formatted string that get be pushed into the editor """ rule = rule or {} return ('action: %s\n' 'protocol: %s\n' 'source_ip_address: %s\n' 'source_ip_subnet_mask: %s\n' 'destination_ip_address: %s\n' 'destination_ip_subnet_mask: %s\n' 'destination_port_range_start: %s\n' 'destination_port_range_end: %s\n' 'version: %s\n' % (rule.get('action', 'permit'), rule.get('protocol', 'tcp'), rule.get('sourceIpAddress', 'any'), rule.get('sourceIpSubnetMask', '255.255.255.255'), rule.get('destinationIpAddress', 'any'), rule.get('destinationIpSubnetMask', '255.255.255.255'), rule.get('destinationPortRangeStart', 1), rule.get('destinationPortRangeEnd', 1), rule.get('version', 4)))
python
def get_formatted_rule(rule=None): rule = rule or {} return ('action: %s\n' 'protocol: %s\n' 'source_ip_address: %s\n' 'source_ip_subnet_mask: %s\n' 'destination_ip_address: %s\n' 'destination_ip_subnet_mask: %s\n' 'destination_port_range_start: %s\n' 'destination_port_range_end: %s\n' 'version: %s\n' % (rule.get('action', 'permit'), rule.get('protocol', 'tcp'), rule.get('sourceIpAddress', 'any'), rule.get('sourceIpSubnetMask', '255.255.255.255'), rule.get('destinationIpAddress', 'any'), rule.get('destinationIpSubnetMask', '255.255.255.255'), rule.get('destinationPortRangeStart', 1), rule.get('destinationPortRangeEnd', 1), rule.get('version', 4)))
[ "def", "get_formatted_rule", "(", "rule", "=", "None", ")", ":", "rule", "=", "rule", "or", "{", "}", "return", "(", "'action: %s\\n'", "'protocol: %s\\n'", "'source_ip_address: %s\\n'", "'source_ip_subnet_mask: %s\\n'", "'destination_ip_address: %s\\n'", "'destination_ip_subnet_mask: %s\\n'", "'destination_port_range_start: %s\\n'", "'destination_port_range_end: %s\\n'", "'version: %s\\n'", "%", "(", "rule", ".", "get", "(", "'action'", ",", "'permit'", ")", ",", "rule", ".", "get", "(", "'protocol'", ",", "'tcp'", ")", ",", "rule", ".", "get", "(", "'sourceIpAddress'", ",", "'any'", ")", ",", "rule", ".", "get", "(", "'sourceIpSubnetMask'", ",", "'255.255.255.255'", ")", ",", "rule", ".", "get", "(", "'destinationIpAddress'", ",", "'any'", ")", ",", "rule", ".", "get", "(", "'destinationIpSubnetMask'", ",", "'255.255.255.255'", ")", ",", "rule", ".", "get", "(", "'destinationPortRangeStart'", ",", "1", ")", ",", "rule", ".", "get", "(", "'destinationPortRangeEnd'", ",", "1", ")", ",", "rule", ".", "get", "(", "'version'", ",", "4", ")", ")", ")" ]
Helper to format the rule into a user friendly format. :param dict rule: A dict containing one rule of the firewall :returns: a formatted string that get be pushed into the editor
[ "Helper", "to", "format", "the", "rule", "into", "a", "user", "friendly", "format", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/edit.py#L108-L132
softlayer/softlayer-python
SoftLayer/CLI/firewall/edit.py
cli
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.')
python
def cli(env, identifier): 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) 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", "cli", "(", "env", ",", "identifier", ")", ":", "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.'", ")" ]
Edit firewall rules.
[ "Edit", "firewall", "rules", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/edit.py#L138-L178
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/rule.py
rule_list
def rule_list(env, securitygroup_id, sortby): """List security group rules.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby rules = mgr.list_securitygroup_rules(securitygroup_id) for rule in rules: port_min = rule.get('portRangeMin') port_max = rule.get('portRangeMax') if port_min is None: port_min = formatting.blank() if port_max is None: port_max = formatting.blank() table.add_row([ rule['id'], rule.get('remoteIp') or formatting.blank(), rule.get('remoteGroupId') or formatting.blank(), rule['direction'], rule.get('ethertype') or formatting.blank(), port_min, port_max, rule.get('protocol') or formatting.blank(), rule.get('createDate') or formatting.blank(), rule.get('modifyDate') or formatting.blank() ]) env.fout(table)
python
def rule_list(env, securitygroup_id, sortby): mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby rules = mgr.list_securitygroup_rules(securitygroup_id) for rule in rules: port_min = rule.get('portRangeMin') port_max = rule.get('portRangeMax') if port_min is None: port_min = formatting.blank() if port_max is None: port_max = formatting.blank() table.add_row([ rule['id'], rule.get('remoteIp') or formatting.blank(), rule.get('remoteGroupId') or formatting.blank(), rule['direction'], rule.get('ethertype') or formatting.blank(), port_min, port_max, rule.get('protocol') or formatting.blank(), rule.get('createDate') or formatting.blank(), rule.get('modifyDate') or formatting.blank() ]) env.fout(table)
[ "def", "rule_list", "(", "env", ",", "securitygroup_id", ",", "sortby", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "table", ".", "sortby", "=", "sortby", "rules", "=", "mgr", ".", "list_securitygroup_rules", "(", "securitygroup_id", ")", "for", "rule", "in", "rules", ":", "port_min", "=", "rule", ".", "get", "(", "'portRangeMin'", ")", "port_max", "=", "rule", ".", "get", "(", "'portRangeMax'", ")", "if", "port_min", "is", "None", ":", "port_min", "=", "formatting", ".", "blank", "(", ")", "if", "port_max", "is", "None", ":", "port_max", "=", "formatting", ".", "blank", "(", ")", "table", ".", "add_row", "(", "[", "rule", "[", "'id'", "]", ",", "rule", ".", "get", "(", "'remoteIp'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "rule", ".", "get", "(", "'remoteGroupId'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "rule", "[", "'direction'", "]", ",", "rule", ".", "get", "(", "'ethertype'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "port_min", ",", "port_max", ",", "rule", ".", "get", "(", "'protocol'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "rule", ".", "get", "(", "'createDate'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "rule", ".", "get", "(", "'modifyDate'", ")", "or", "formatting", ".", "blank", "(", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List security group rules.
[ "List", "security", "group", "rules", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/rule.py#L32-L62
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/rule.py
add
def add(env, securitygroup_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol): """Add a security group rule to a security group. \b Examples: # Add an SSH rule (TCP port 22) to a security group slcli sg rule-add 384727 \\ --direction ingress \\ --protocol tcp \\ --port-min 22 \\ --port-max 22 \b # Add a ping rule (ICMP type 8 code 0) to a security group slcli sg rule-add 384727 \\ --direction ingress \\ --protocol icmp \\ --port-min 8 \\ --port-max 0 """ mgr = SoftLayer.NetworkManager(env.client) ret = mgr.add_securitygroup_rule(securitygroup_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol) if not ret: raise exceptions.CLIAbort("Failed to add security group rule") table = formatting.Table(REQUEST_RULES_COLUMNS) table.add_row([ret['requestId'], str(ret['rules'])]) env.fout(table)
python
def add(env, securitygroup_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol): mgr = SoftLayer.NetworkManager(env.client) ret = mgr.add_securitygroup_rule(securitygroup_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol) if not ret: raise exceptions.CLIAbort("Failed to add security group rule") table = formatting.Table(REQUEST_RULES_COLUMNS) table.add_row([ret['requestId'], str(ret['rules'])]) env.fout(table)
[ "def", "add", "(", "env", ",", "securitygroup_id", ",", "remote_ip", ",", "remote_group", ",", "direction", ",", "ethertype", ",", "port_max", ",", "port_min", ",", "protocol", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "ret", "=", "mgr", ".", "add_securitygroup_rule", "(", "securitygroup_id", ",", "remote_ip", ",", "remote_group", ",", "direction", ",", "ethertype", ",", "port_max", ",", "port_min", ",", "protocol", ")", "if", "not", "ret", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Failed to add security group rule\"", ")", "table", "=", "formatting", ".", "Table", "(", "REQUEST_RULES_COLUMNS", ")", "table", ".", "add_row", "(", "[", "ret", "[", "'requestId'", "]", ",", "str", "(", "ret", "[", "'rules'", "]", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Add a security group rule to a security group. \b Examples: # Add an SSH rule (TCP port 22) to a security group slcli sg rule-add 384727 \\ --direction ingress \\ --protocol tcp \\ --port-min 22 \\ --port-max 22 \b # Add a ping rule (ICMP type 8 code 0) to a security group slcli sg rule-add 384727 \\ --direction ingress \\ --protocol icmp \\ --port-min 8 \\ --port-max 0
[ "Add", "a", "security", "group", "rule", "to", "a", "security", "group", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/rule.py#L85-L118
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/rule.py
edit
def edit(env, securitygroup_id, rule_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol): """Edit a security group rule in a security group.""" mgr = SoftLayer.NetworkManager(env.client) data = {} if remote_ip: data['remote_ip'] = remote_ip if remote_group: data['remote_group'] = remote_group if direction: data['direction'] = direction if ethertype: data['ethertype'] = ethertype if port_max is not None: data['port_max'] = port_max if port_min is not None: data['port_min'] = port_min if protocol: data['protocol'] = protocol ret = mgr.edit_securitygroup_rule(securitygroup_id, rule_id, **data) if not ret: raise exceptions.CLIAbort("Failed to edit security group rule") table = formatting.Table(REQUEST_BOOL_COLUMNS) table.add_row([ret['requestId']]) env.fout(table)
python
def edit(env, securitygroup_id, rule_id, remote_ip, remote_group, direction, ethertype, port_max, port_min, protocol): mgr = SoftLayer.NetworkManager(env.client) data = {} if remote_ip: data['remote_ip'] = remote_ip if remote_group: data['remote_group'] = remote_group if direction: data['direction'] = direction if ethertype: data['ethertype'] = ethertype if port_max is not None: data['port_max'] = port_max if port_min is not None: data['port_min'] = port_min if protocol: data['protocol'] = protocol ret = mgr.edit_securitygroup_rule(securitygroup_id, rule_id, **data) if not ret: raise exceptions.CLIAbort("Failed to edit security group rule") table = formatting.Table(REQUEST_BOOL_COLUMNS) table.add_row([ret['requestId']]) env.fout(table)
[ "def", "edit", "(", "env", ",", "securitygroup_id", ",", "rule_id", ",", "remote_ip", ",", "remote_group", ",", "direction", ",", "ethertype", ",", "port_max", ",", "port_min", ",", "protocol", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "data", "=", "{", "}", "if", "remote_ip", ":", "data", "[", "'remote_ip'", "]", "=", "remote_ip", "if", "remote_group", ":", "data", "[", "'remote_group'", "]", "=", "remote_group", "if", "direction", ":", "data", "[", "'direction'", "]", "=", "direction", "if", "ethertype", ":", "data", "[", "'ethertype'", "]", "=", "ethertype", "if", "port_max", "is", "not", "None", ":", "data", "[", "'port_max'", "]", "=", "port_max", "if", "port_min", "is", "not", "None", ":", "data", "[", "'port_min'", "]", "=", "port_min", "if", "protocol", ":", "data", "[", "'protocol'", "]", "=", "protocol", "ret", "=", "mgr", ".", "edit_securitygroup_rule", "(", "securitygroup_id", ",", "rule_id", ",", "*", "*", "data", ")", "if", "not", "ret", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Failed to edit security group rule\"", ")", "table", "=", "formatting", ".", "Table", "(", "REQUEST_BOOL_COLUMNS", ")", "table", ".", "add_row", "(", "[", "ret", "[", "'requestId'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Edit a security group rule in a security group.
[ "Edit", "a", "security", "group", "rule", "in", "a", "security", "group", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/rule.py#L139-L168
softlayer/softlayer-python
SoftLayer/CLI/securitygroup/rule.py
remove
def remove(env, securitygroup_id, rule_id): """Remove a rule from a security group.""" mgr = SoftLayer.NetworkManager(env.client) ret = mgr.remove_securitygroup_rule(securitygroup_id, rule_id) if not ret: raise exceptions.CLIAbort("Failed to remove security group rule") table = formatting.Table(REQUEST_BOOL_COLUMNS) table.add_row([ret['requestId']]) env.fout(table)
python
def remove(env, securitygroup_id, rule_id): mgr = SoftLayer.NetworkManager(env.client) ret = mgr.remove_securitygroup_rule(securitygroup_id, rule_id) if not ret: raise exceptions.CLIAbort("Failed to remove security group rule") table = formatting.Table(REQUEST_BOOL_COLUMNS) table.add_row([ret['requestId']]) env.fout(table)
[ "def", "remove", "(", "env", ",", "securitygroup_id", ",", "rule_id", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "ret", "=", "mgr", ".", "remove_securitygroup_rule", "(", "securitygroup_id", ",", "rule_id", ")", "if", "not", "ret", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"Failed to remove security group rule\"", ")", "table", "=", "formatting", ".", "Table", "(", "REQUEST_BOOL_COLUMNS", ")", "table", ".", "add_row", "(", "[", "ret", "[", "'requestId'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Remove a rule from a security group.
[ "Remove", "a", "rule", "from", "a", "security", "group", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/securitygroup/rule.py#L175-L187
softlayer/softlayer-python
SoftLayer/CLI/deprecated.py
main
def main(): """Main function for the deprecated 'sl' command.""" print("ERROR: Use the 'slcli' command instead.", file=sys.stderr) print("> slcli %s" % ' '.join(sys.argv[1:]), file=sys.stderr) exit(-1)
python
def main(): print("ERROR: Use the 'slcli' command instead.", file=sys.stderr) print("> slcli %s" % ' '.join(sys.argv[1:]), file=sys.stderr) exit(-1)
[ "def", "main", "(", ")", ":", "print", "(", "\"ERROR: Use the 'slcli' command instead.\"", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "\"> slcli %s\"", "%", "' '", ".", "join", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", ",", "file", "=", "sys", ".", "stderr", ")", "exit", "(", "-", "1", ")" ]
Main function for the deprecated 'sl' command.
[ "Main", "function", "for", "the", "deprecated", "sl", "command", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/deprecated.py#L11-L15
softlayer/softlayer-python
SoftLayer/CLI/loadbal/group_edit.py
cli
def cli(env, identifier, allocation, port, routing_type, routing_method): """Edit an existing load balancer service group.""" mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, group_id = loadbal.parse_id(identifier) # check if any input is provided if not any([allocation, port, routing_type, routing_method]): raise exceptions.CLIAbort( 'At least one property is required to be changed!') mgr.edit_service_group(loadbal_id, group_id, allocation=allocation, port=port, routing_type=routing_type, routing_method=routing_method) env.fout('Load balancer service group %s is being updated!' % identifier)
python
def cli(env, identifier, allocation, port, routing_type, routing_method): mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, group_id = loadbal.parse_id(identifier) if not any([allocation, port, routing_type, routing_method]): raise exceptions.CLIAbort( 'At least one property is required to be changed!') mgr.edit_service_group(loadbal_id, group_id, allocation=allocation, port=port, routing_type=routing_type, routing_method=routing_method) env.fout('Load balancer service group %s is being updated!' % identifier)
[ "def", "cli", "(", "env", ",", "identifier", ",", "allocation", ",", "port", ",", "routing_type", ",", "routing_method", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "loadbal_id", ",", "group_id", "=", "loadbal", ".", "parse_id", "(", "identifier", ")", "# check if any input is provided", "if", "not", "any", "(", "[", "allocation", ",", "port", ",", "routing_type", ",", "routing_method", "]", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'At least one property is required to be changed!'", ")", "mgr", ".", "edit_service_group", "(", "loadbal_id", ",", "group_id", ",", "allocation", "=", "allocation", ",", "port", "=", "port", ",", "routing_type", "=", "routing_type", ",", "routing_method", "=", "routing_method", ")", "env", ".", "fout", "(", "'Load balancer service group %s is being updated!'", "%", "identifier", ")" ]
Edit an existing load balancer service group.
[ "Edit", "an", "existing", "load", "balancer", "service", "group", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/group_edit.py#L25-L43
softlayer/softlayer-python
SoftLayer/CLI/account/event_detail.py
cli
def cli(env, identifier, ack): """Details of a specific event, and ability to acknowledge event.""" # Print a list of all on going maintenance manager = AccountManager(env.client) event = manager.get_event(identifier) if ack: manager.ack_event(identifier) env.fout(basic_event_table(event)) env.fout(impacted_table(event)) env.fout(update_table(event))
python
def cli(env, identifier, ack): manager = AccountManager(env.client) event = manager.get_event(identifier) if ack: manager.ack_event(identifier) env.fout(basic_event_table(event)) env.fout(impacted_table(event)) env.fout(update_table(event))
[ "def", "cli", "(", "env", ",", "identifier", ",", "ack", ")", ":", "# Print a list of all on going maintenance", "manager", "=", "AccountManager", "(", "env", ".", "client", ")", "event", "=", "manager", ".", "get_event", "(", "identifier", ")", "if", "ack", ":", "manager", ".", "ack_event", "(", "identifier", ")", "env", ".", "fout", "(", "basic_event_table", "(", "event", ")", ")", "env", ".", "fout", "(", "impacted_table", "(", "event", ")", ")", "env", ".", "fout", "(", "update_table", "(", "event", ")", ")" ]
Details of a specific event, and ability to acknowledge event.
[ "Details", "of", "a", "specific", "event", "and", "ability", "to", "acknowledge", "event", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/event_detail.py#L17-L29
softlayer/softlayer-python
SoftLayer/CLI/account/event_detail.py
basic_event_table
def basic_event_table(event): """Formats a basic event table""" table = formatting.Table(["Id", "Status", "Type", "Start", "End"], title=utils.clean_splitlines(event.get('subject'))) table.add_row([ event.get('id'), utils.lookup(event, 'statusCode', 'name'), utils.lookup(event, 'notificationOccurrenceEventType', 'keyName'), utils.clean_time(event.get('startDate')), utils.clean_time(event.get('endDate')) ]) return table
python
def basic_event_table(event): table = formatting.Table(["Id", "Status", "Type", "Start", "End"], title=utils.clean_splitlines(event.get('subject'))) table.add_row([ event.get('id'), utils.lookup(event, 'statusCode', 'name'), utils.lookup(event, 'notificationOccurrenceEventType', 'keyName'), utils.clean_time(event.get('startDate')), utils.clean_time(event.get('endDate')) ]) return table
[ "def", "basic_event_table", "(", "event", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "\"Id\"", ",", "\"Status\"", ",", "\"Type\"", ",", "\"Start\"", ",", "\"End\"", "]", ",", "title", "=", "utils", ".", "clean_splitlines", "(", "event", ".", "get", "(", "'subject'", ")", ")", ")", "table", ".", "add_row", "(", "[", "event", ".", "get", "(", "'id'", ")", ",", "utils", ".", "lookup", "(", "event", ",", "'statusCode'", ",", "'name'", ")", ",", "utils", ".", "lookup", "(", "event", ",", "'notificationOccurrenceEventType'", ",", "'keyName'", ")", ",", "utils", ".", "clean_time", "(", "event", ".", "get", "(", "'startDate'", ")", ")", ",", "utils", ".", "clean_time", "(", "event", ".", "get", "(", "'endDate'", ")", ")", "]", ")", "return", "table" ]
Formats a basic event table
[ "Formats", "a", "basic", "event", "table" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/event_detail.py#L32-L45
softlayer/softlayer-python
SoftLayer/CLI/account/event_detail.py
impacted_table
def impacted_table(event): """Formats a basic impacted resources table""" table = formatting.Table([ "Type", "Id", "Hostname", "PrivateIp", "Label" ]) for item in event.get('impactedResources', []): table.add_row([ item.get('resourceType'), item.get('resourceTableId'), item.get('hostname'), item.get('privateIp'), item.get('filterLabel') ]) return table
python
def impacted_table(event): table = formatting.Table([ "Type", "Id", "Hostname", "PrivateIp", "Label" ]) for item in event.get('impactedResources', []): table.add_row([ item.get('resourceType'), item.get('resourceTableId'), item.get('hostname'), item.get('privateIp'), item.get('filterLabel') ]) return table
[ "def", "impacted_table", "(", "event", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "\"Type\"", ",", "\"Id\"", ",", "\"Hostname\"", ",", "\"PrivateIp\"", ",", "\"Label\"", "]", ")", "for", "item", "in", "event", ".", "get", "(", "'impactedResources'", ",", "[", "]", ")", ":", "table", ".", "add_row", "(", "[", "item", ".", "get", "(", "'resourceType'", ")", ",", "item", ".", "get", "(", "'resourceTableId'", ")", ",", "item", ".", "get", "(", "'hostname'", ")", ",", "item", ".", "get", "(", "'privateIp'", ")", ",", "item", ".", "get", "(", "'filterLabel'", ")", "]", ")", "return", "table" ]
Formats a basic impacted resources table
[ "Formats", "a", "basic", "impacted", "resources", "table" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/event_detail.py#L48-L61
softlayer/softlayer-python
SoftLayer/CLI/account/event_detail.py
update_table
def update_table(event): """Formats a basic event update table""" update_number = 0 for update in event.get('updates', []): header = "======= Update #%s on %s =======" % (update_number, utils.clean_time(update.get('startDate'))) click.secho(header, fg='green') update_number = update_number + 1 text = update.get('contents') # deals with all the \r\n from the API click.secho(utils.clean_splitlines(text))
python
def update_table(event): update_number = 0 for update in event.get('updates', []): header = "======= Update click.secho(header, fg='green') update_number = update_number + 1 text = update.get('contents') click.secho(utils.clean_splitlines(text))
[ "def", "update_table", "(", "event", ")", ":", "update_number", "=", "0", "for", "update", "in", "event", ".", "get", "(", "'updates'", ",", "[", "]", ")", ":", "header", "=", "\"======= Update #%s on %s =======\"", "%", "(", "update_number", ",", "utils", ".", "clean_time", "(", "update", ".", "get", "(", "'startDate'", ")", ")", ")", "click", ".", "secho", "(", "header", ",", "fg", "=", "'green'", ")", "update_number", "=", "update_number", "+", "1", "text", "=", "update", ".", "get", "(", "'contents'", ")", "# deals with all the \\r\\n from the API", "click", ".", "secho", "(", "utils", ".", "clean_splitlines", "(", "text", ")", ")" ]
Formats a basic event update table
[ "Formats", "a", "basic", "event", "update", "table" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/event_detail.py#L64-L73
softlayer/softlayer-python
SoftLayer/CLI/block/list.py
cli
def cli(env, sortby, columns, datacenter, username, storage_type): """List block storage.""" block_manager = SoftLayer.BlockStorageManager(env.client) block_volumes = block_manager.list_block_volumes(datacenter=datacenter, username=username, storage_type=storage_type, mask=columns.mask()) table = formatting.Table(columns.columns) table.sortby = sortby for block_volume in block_volumes: table.add_row([value or formatting.blank() for value in columns.row(block_volume)]) env.fout(table)
python
def cli(env, sortby, columns, datacenter, username, storage_type): block_manager = SoftLayer.BlockStorageManager(env.client) block_volumes = block_manager.list_block_volumes(datacenter=datacenter, username=username, storage_type=storage_type, mask=columns.mask()) table = formatting.Table(columns.columns) table.sortby = sortby for block_volume in block_volumes: table.add_row([value or formatting.blank() for value in columns.row(block_volume)]) env.fout(table)
[ "def", "cli", "(", "env", ",", "sortby", ",", "columns", ",", "datacenter", ",", "username", ",", "storage_type", ")", ":", "block_manager", "=", "SoftLayer", ".", "BlockStorageManager", "(", "env", ".", "client", ")", "block_volumes", "=", "block_manager", ".", "list_block_volumes", "(", "datacenter", "=", "datacenter", ",", "username", "=", "username", ",", "storage_type", "=", "storage_type", ",", "mask", "=", "columns", ".", "mask", "(", ")", ")", "table", "=", "formatting", ".", "Table", "(", "columns", ".", "columns", ")", "table", ".", "sortby", "=", "sortby", "for", "block_volume", "in", "block_volumes", ":", "table", ".", "add_row", "(", "[", "value", "or", "formatting", ".", "blank", "(", ")", "for", "value", "in", "columns", ".", "row", "(", "block_volume", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List block storage.
[ "List", "block", "storage", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/list.py#L67-L82
softlayer/softlayer-python
SoftLayer/CLI/object_storage/list_endpoints.py
cli
def cli(env): """List object storage endpoints.""" mgr = SoftLayer.ObjectStorageManager(env.client) endpoints = mgr.list_endpoints() table = formatting.Table(['datacenter', 'public', 'private']) for endpoint in endpoints: table.add_row([ endpoint['datacenter']['name'], endpoint['public'], endpoint['private'], ]) env.fout(table)
python
def cli(env): mgr = SoftLayer.ObjectStorageManager(env.client) endpoints = mgr.list_endpoints() table = formatting.Table(['datacenter', 'public', 'private']) for endpoint in endpoints: table.add_row([ endpoint['datacenter']['name'], endpoint['public'], endpoint['private'], ]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "mgr", "=", "SoftLayer", ".", "ObjectStorageManager", "(", "env", ".", "client", ")", "endpoints", "=", "mgr", ".", "list_endpoints", "(", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'datacenter'", ",", "'public'", ",", "'private'", "]", ")", "for", "endpoint", "in", "endpoints", ":", "table", ".", "add_row", "(", "[", "endpoint", "[", "'datacenter'", "]", "[", "'name'", "]", ",", "endpoint", "[", "'public'", "]", ",", "endpoint", "[", "'private'", "]", ",", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List object storage endpoints.
[ "List", "object", "storage", "endpoints", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/object_storage/list_endpoints.py#L13-L27
softlayer/softlayer-python
SoftLayer/CLI/virt/cancel.py
cli
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)
python
def cli(env, identifier): 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", "cli", "(", "env", ",", "identifier", ")", ":", "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", ")" ]
Cancel virtual servers.
[ "Cancel", "virtual", "servers", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/cancel.py#L16-L24
softlayer/softlayer-python
SoftLayer/CLI/hardware/reflash_firmware.py
cli
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)
python
def cli(env, identifier): 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", "cli", "(", "env", ",", "identifier", ")", ":", "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", ")" ]
Reflash server firmware.
[ "Reflash", "server", "firmware", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/reflash_firmware.py#L16-L26
softlayer/softlayer-python
SoftLayer/CLI/file/snapshot/schedule_list.py
cli
def cli(env, volume_id): """Lists snapshot schedules for a given volume""" file_manager = SoftLayer.FileStorageManager(env.client) snapshot_schedules = file_manager.list_volume_schedules(volume_id) table = formatting.Table(['id', 'active', 'type', 'replication', 'date_created', 'minute', 'hour', 'day', 'week', 'day_of_week', 'date_of_month', 'month_of_year', 'maximum_snapshots']) for schedule in snapshot_schedules: if 'REPLICATION' in schedule['type']['keyname']: replication = '*' else: replication = formatting.blank() file_schedule_type = schedule['type']['keyname'].replace('REPLICATION_', '') file_schedule_type = file_schedule_type.replace('SNAPSHOT_', '') property_list = ['MINUTE', 'HOUR', 'DAY', 'WEEK', 'DAY_OF_WEEK', 'DAY_OF_MONTH', 'MONTH_OF_YEAR', 'SNAPSHOT_LIMIT'] schedule_properties = [] for prop_key in property_list: item = formatting.blank() for schedule_property in schedule.get('properties', []): if schedule_property['type']['keyname'] == prop_key: if schedule_property['value'] == '-1': item = '*' else: item = schedule_property['value'] break schedule_properties.append(item) table_row = [ schedule['id'], '*' if schedule.get('active', '') else '', file_schedule_type, replication, schedule.get('createDate', '') ] table_row.extend(schedule_properties) table.add_row(table_row) env.fout(table)
python
def cli(env, volume_id): file_manager = SoftLayer.FileStorageManager(env.client) snapshot_schedules = file_manager.list_volume_schedules(volume_id) table = formatting.Table(['id', 'active', 'type', 'replication', 'date_created', 'minute', 'hour', 'day', 'week', 'day_of_week', 'date_of_month', 'month_of_year', 'maximum_snapshots']) for schedule in snapshot_schedules: if 'REPLICATION' in schedule['type']['keyname']: replication = '*' else: replication = formatting.blank() file_schedule_type = schedule['type']['keyname'].replace('REPLICATION_', '') file_schedule_type = file_schedule_type.replace('SNAPSHOT_', '') property_list = ['MINUTE', 'HOUR', 'DAY', 'WEEK', 'DAY_OF_WEEK', 'DAY_OF_MONTH', 'MONTH_OF_YEAR', 'SNAPSHOT_LIMIT'] schedule_properties = [] for prop_key in property_list: item = formatting.blank() for schedule_property in schedule.get('properties', []): if schedule_property['type']['keyname'] == prop_key: if schedule_property['value'] == '-1': item = '*' else: item = schedule_property['value'] break schedule_properties.append(item) table_row = [ schedule['id'], '*' if schedule.get('active', '') else '', file_schedule_type, replication, schedule.get('createDate', '') ] table_row.extend(schedule_properties) table.add_row(table_row) env.fout(table)
[ "def", "cli", "(", "env", ",", "volume_id", ")", ":", "file_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "snapshot_schedules", "=", "file_manager", ".", "list_volume_schedules", "(", "volume_id", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'active'", ",", "'type'", ",", "'replication'", ",", "'date_created'", ",", "'minute'", ",", "'hour'", ",", "'day'", ",", "'week'", ",", "'day_of_week'", ",", "'date_of_month'", ",", "'month_of_year'", ",", "'maximum_snapshots'", "]", ")", "for", "schedule", "in", "snapshot_schedules", ":", "if", "'REPLICATION'", "in", "schedule", "[", "'type'", "]", "[", "'keyname'", "]", ":", "replication", "=", "'*'", "else", ":", "replication", "=", "formatting", ".", "blank", "(", ")", "file_schedule_type", "=", "schedule", "[", "'type'", "]", "[", "'keyname'", "]", ".", "replace", "(", "'REPLICATION_'", ",", "''", ")", "file_schedule_type", "=", "file_schedule_type", ".", "replace", "(", "'SNAPSHOT_'", ",", "''", ")", "property_list", "=", "[", "'MINUTE'", ",", "'HOUR'", ",", "'DAY'", ",", "'WEEK'", ",", "'DAY_OF_WEEK'", ",", "'DAY_OF_MONTH'", ",", "'MONTH_OF_YEAR'", ",", "'SNAPSHOT_LIMIT'", "]", "schedule_properties", "=", "[", "]", "for", "prop_key", "in", "property_list", ":", "item", "=", "formatting", ".", "blank", "(", ")", "for", "schedule_property", "in", "schedule", ".", "get", "(", "'properties'", ",", "[", "]", ")", ":", "if", "schedule_property", "[", "'type'", "]", "[", "'keyname'", "]", "==", "prop_key", ":", "if", "schedule_property", "[", "'value'", "]", "==", "'-1'", ":", "item", "=", "'*'", "else", ":", "item", "=", "schedule_property", "[", "'value'", "]", "break", "schedule_properties", ".", "append", "(", "item", ")", "table_row", "=", "[", "schedule", "[", "'id'", "]", ",", "'*'", "if", "schedule", ".", "get", "(", "'active'", ",", "''", ")", "else", "''", ",", "file_schedule_type", ",", "replication", ",", "schedule", ".", "get", "(", "'createDate'", ",", "''", ")", "]", "table_row", ".", "extend", "(", "schedule_properties", ")", "table", ".", "add_row", "(", "table_row", ")", "env", ".", "fout", "(", "table", ")" ]
Lists snapshot schedules for a given volume
[ "Lists", "snapshot", "schedules", "for", "a", "given", "volume" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/schedule_list.py#L13-L70
softlayer/softlayer-python
SoftLayer/CLI/firewall/list.py
cli
def cli(env): """List firewalls.""" mgr = SoftLayer.FirewallManager(env.client) table = formatting.Table(['firewall id', 'type', 'features', 'server/vlan id']) fwvlans = mgr.get_firewalls() dedicated_firewalls = [firewall for firewall in fwvlans if firewall['dedicatedFirewallFlag']] for vlan in dedicated_firewalls: features = [] if vlan['highAvailabilityFirewallFlag']: features.append('HA') if features: feature_list = formatting.listing(features, separator=',') else: feature_list = formatting.blank() table.add_row([ 'vlan:%s' % vlan['networkVlanFirewall']['id'], 'VLAN - dedicated', feature_list, vlan['id'] ]) shared_vlan = [firewall for firewall in fwvlans if not firewall['dedicatedFirewallFlag']] for vlan in shared_vlan: vs_firewalls = [guest for guest in vlan['firewallGuestNetworkComponents'] if has_firewall_component(guest)] for firewall in vs_firewalls: table.add_row([ 'vs:%s' % firewall['id'], 'Virtual Server - standard', '-', firewall['guestNetworkComponent']['guest']['id'] ]) server_firewalls = [server for server in vlan['firewallNetworkComponents'] if has_firewall_component(server)] for firewall in server_firewalls: table.add_row([ 'server:%s' % firewall['id'], 'Server - standard', '-', utils.lookup(firewall, 'networkComponent', 'downlinkComponent', 'hardwareId') ]) env.fout(table)
python
def cli(env): mgr = SoftLayer.FirewallManager(env.client) table = formatting.Table(['firewall id', 'type', 'features', 'server/vlan id']) fwvlans = mgr.get_firewalls() dedicated_firewalls = [firewall for firewall in fwvlans if firewall['dedicatedFirewallFlag']] for vlan in dedicated_firewalls: features = [] if vlan['highAvailabilityFirewallFlag']: features.append('HA') if features: feature_list = formatting.listing(features, separator=',') else: feature_list = formatting.blank() table.add_row([ 'vlan:%s' % vlan['networkVlanFirewall']['id'], 'VLAN - dedicated', feature_list, vlan['id'] ]) shared_vlan = [firewall for firewall in fwvlans if not firewall['dedicatedFirewallFlag']] for vlan in shared_vlan: vs_firewalls = [guest for guest in vlan['firewallGuestNetworkComponents'] if has_firewall_component(guest)] for firewall in vs_firewalls: table.add_row([ 'vs:%s' % firewall['id'], 'Virtual Server - standard', '-', firewall['guestNetworkComponent']['guest']['id'] ]) server_firewalls = [server for server in vlan['firewallNetworkComponents'] if has_firewall_component(server)] for firewall in server_firewalls: table.add_row([ 'server:%s' % firewall['id'], 'Server - standard', '-', utils.lookup(firewall, 'networkComponent', 'downlinkComponent', 'hardwareId') ]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "mgr", "=", "SoftLayer", ".", "FirewallManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'firewall id'", ",", "'type'", ",", "'features'", ",", "'server/vlan id'", "]", ")", "fwvlans", "=", "mgr", ".", "get_firewalls", "(", ")", "dedicated_firewalls", "=", "[", "firewall", "for", "firewall", "in", "fwvlans", "if", "firewall", "[", "'dedicatedFirewallFlag'", "]", "]", "for", "vlan", "in", "dedicated_firewalls", ":", "features", "=", "[", "]", "if", "vlan", "[", "'highAvailabilityFirewallFlag'", "]", ":", "features", ".", "append", "(", "'HA'", ")", "if", "features", ":", "feature_list", "=", "formatting", ".", "listing", "(", "features", ",", "separator", "=", "','", ")", "else", ":", "feature_list", "=", "formatting", ".", "blank", "(", ")", "table", ".", "add_row", "(", "[", "'vlan:%s'", "%", "vlan", "[", "'networkVlanFirewall'", "]", "[", "'id'", "]", ",", "'VLAN - dedicated'", ",", "feature_list", ",", "vlan", "[", "'id'", "]", "]", ")", "shared_vlan", "=", "[", "firewall", "for", "firewall", "in", "fwvlans", "if", "not", "firewall", "[", "'dedicatedFirewallFlag'", "]", "]", "for", "vlan", "in", "shared_vlan", ":", "vs_firewalls", "=", "[", "guest", "for", "guest", "in", "vlan", "[", "'firewallGuestNetworkComponents'", "]", "if", "has_firewall_component", "(", "guest", ")", "]", "for", "firewall", "in", "vs_firewalls", ":", "table", ".", "add_row", "(", "[", "'vs:%s'", "%", "firewall", "[", "'id'", "]", ",", "'Virtual Server - standard'", ",", "'-'", ",", "firewall", "[", "'guestNetworkComponent'", "]", "[", "'guest'", "]", "[", "'id'", "]", "]", ")", "server_firewalls", "=", "[", "server", "for", "server", "in", "vlan", "[", "'firewallNetworkComponents'", "]", "if", "has_firewall_component", "(", "server", ")", "]", "for", "firewall", "in", "server_firewalls", ":", "table", ".", "add_row", "(", "[", "'server:%s'", "%", "firewall", "[", "'id'", "]", ",", "'Server - standard'", ",", "'-'", ",", "utils", ".", "lookup", "(", "firewall", ",", "'networkComponent'", ",", "'downlinkComponent'", ",", "'hardwareId'", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List firewalls.
[ "List", "firewalls", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/list.py#L14-L73
softlayer/softlayer-python
SoftLayer/CLI/subnet/cancel.py
cli
def cli(env, identifier): """Cancel a subnet.""" mgr = SoftLayer.NetworkManager(env.client) subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier, name='subnet') if not (env.skip_confirmations or formatting.no_going_back(subnet_id)): raise exceptions.CLIAbort('Aborted') mgr.cancel_subnet(subnet_id)
python
def cli(env, identifier): mgr = SoftLayer.NetworkManager(env.client) subnet_id = helpers.resolve_id(mgr.resolve_subnet_ids, identifier, name='subnet') if not (env.skip_confirmations or formatting.no_going_back(subnet_id)): raise exceptions.CLIAbort('Aborted') mgr.cancel_subnet(subnet_id)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "subnet_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_subnet_ids", ",", "identifier", ",", "name", "=", "'subnet'", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "no_going_back", "(", "subnet_id", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted'", ")", "mgr", ".", "cancel_subnet", "(", "subnet_id", ")" ]
Cancel a subnet.
[ "Cancel", "a", "subnet", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/subnet/cancel.py#L16-L26
softlayer/softlayer-python
SoftLayer/CLI/config/__init__.py
get_settings_from_client
def get_settings_from_client(client): """Pull out settings from a SoftLayer.BaseClient instance. :param client: SoftLayer.BaseClient instance """ settings = { 'username': '', 'api_key': '', 'timeout': '', 'endpoint_url': '', } try: settings['username'] = client.auth.username settings['api_key'] = client.auth.api_key except AttributeError: pass transport = _resolve_transport(client.transport) try: settings['timeout'] = transport.timeout settings['endpoint_url'] = transport.endpoint_url except AttributeError: pass return settings
python
def get_settings_from_client(client): settings = { 'username': '', 'api_key': '', 'timeout': '', 'endpoint_url': '', } try: settings['username'] = client.auth.username settings['api_key'] = client.auth.api_key except AttributeError: pass transport = _resolve_transport(client.transport) try: settings['timeout'] = transport.timeout settings['endpoint_url'] = transport.endpoint_url except AttributeError: pass return settings
[ "def", "get_settings_from_client", "(", "client", ")", ":", "settings", "=", "{", "'username'", ":", "''", ",", "'api_key'", ":", "''", ",", "'timeout'", ":", "''", ",", "'endpoint_url'", ":", "''", ",", "}", "try", ":", "settings", "[", "'username'", "]", "=", "client", ".", "auth", ".", "username", "settings", "[", "'api_key'", "]", "=", "client", ".", "auth", ".", "api_key", "except", "AttributeError", ":", "pass", "transport", "=", "_resolve_transport", "(", "client", ".", "transport", ")", "try", ":", "settings", "[", "'timeout'", "]", "=", "transport", ".", "timeout", "settings", "[", "'endpoint_url'", "]", "=", "transport", ".", "endpoint_url", "except", "AttributeError", ":", "pass", "return", "settings" ]
Pull out settings from a SoftLayer.BaseClient instance. :param client: SoftLayer.BaseClient instance
[ "Pull", "out", "settings", "from", "a", "SoftLayer", ".", "BaseClient", "instance", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/__init__.py#L16-L40
softlayer/softlayer-python
SoftLayer/CLI/config/__init__.py
config_table
def config_table(settings): """Returns a config table.""" table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['Username', settings['username'] or 'not set']) table.add_row(['API Key', settings['api_key'] or 'not set']) table.add_row(['Endpoint URL', settings['endpoint_url'] or 'not set']) table.add_row(['Timeout', settings['timeout'] or 'not set']) return table
python
def config_table(settings): table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['Username', settings['username'] or 'not set']) table.add_row(['API Key', settings['api_key'] or 'not set']) table.add_row(['Endpoint URL', settings['endpoint_url'] or 'not set']) table.add_row(['Timeout', settings['timeout'] or 'not set']) return table
[ "def", "config_table", "(", "settings", ")", ":", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "table", ".", "align", "[", "'name'", "]", "=", "'r'", "table", ".", "align", "[", "'value'", "]", "=", "'l'", "table", ".", "add_row", "(", "[", "'Username'", ",", "settings", "[", "'username'", "]", "or", "'not set'", "]", ")", "table", ".", "add_row", "(", "[", "'API Key'", ",", "settings", "[", "'api_key'", "]", "or", "'not set'", "]", ")", "table", ".", "add_row", "(", "[", "'Endpoint URL'", ",", "settings", "[", "'endpoint_url'", "]", "or", "'not set'", "]", ")", "table", ".", "add_row", "(", "[", "'Timeout'", ",", "settings", "[", "'timeout'", "]", "or", "'not set'", "]", ")", "return", "table" ]
Returns a config table.
[ "Returns", "a", "config", "table", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/__init__.py#L43-L52
softlayer/softlayer-python
SoftLayer/CLI/virt/capacity/create.py
cli
def cli(env, name, backend_router_id, flavor, instances, test=False): """Create a Reserved Capacity instance. *WARNING*: Reserved Capacity is on a yearly contract and not cancelable until the contract is expired. """ manager = CapacityManager(env.client) result = manager.create( name=name, backend_router_id=backend_router_id, flavor=flavor, instances=instances, test=test) if test: table = formatting.Table(['Name', 'Value'], "Test Order") container = result['orderContainers'][0] table.add_row(['Name', container['name']]) table.add_row(['Location', container['locationObject']['longName']]) for price in container['prices']: table.add_row(['Contract', price['item']['description']]) table.add_row(['Hourly Total', result['postTaxRecurring']]) else: table = formatting.Table(['Name', 'Value'], "Reciept") table.add_row(['Order Date', result['orderDate']]) table.add_row(['Order ID', result['orderId']]) table.add_row(['status', result['placedOrder']['status']]) table.add_row(['Hourly Total', result['orderDetails']['postTaxRecurring']]) env.fout(table)
python
def cli(env, name, backend_router_id, flavor, instances, test=False): manager = CapacityManager(env.client) result = manager.create( name=name, backend_router_id=backend_router_id, flavor=flavor, instances=instances, test=test) if test: table = formatting.Table(['Name', 'Value'], "Test Order") container = result['orderContainers'][0] table.add_row(['Name', container['name']]) table.add_row(['Location', container['locationObject']['longName']]) for price in container['prices']: table.add_row(['Contract', price['item']['description']]) table.add_row(['Hourly Total', result['postTaxRecurring']]) else: table = formatting.Table(['Name', 'Value'], "Reciept") table.add_row(['Order Date', result['orderDate']]) table.add_row(['Order ID', result['orderId']]) table.add_row(['status', result['placedOrder']['status']]) table.add_row(['Hourly Total', result['orderDetails']['postTaxRecurring']]) env.fout(table)
[ "def", "cli", "(", "env", ",", "name", ",", "backend_router_id", ",", "flavor", ",", "instances", ",", "test", "=", "False", ")", ":", "manager", "=", "CapacityManager", "(", "env", ".", "client", ")", "result", "=", "manager", ".", "create", "(", "name", "=", "name", ",", "backend_router_id", "=", "backend_router_id", ",", "flavor", "=", "flavor", ",", "instances", "=", "instances", ",", "test", "=", "test", ")", "if", "test", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Name'", ",", "'Value'", "]", ",", "\"Test Order\"", ")", "container", "=", "result", "[", "'orderContainers'", "]", "[", "0", "]", "table", ".", "add_row", "(", "[", "'Name'", ",", "container", "[", "'name'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'Location'", ",", "container", "[", "'locationObject'", "]", "[", "'longName'", "]", "]", ")", "for", "price", "in", "container", "[", "'prices'", "]", ":", "table", ".", "add_row", "(", "[", "'Contract'", ",", "price", "[", "'item'", "]", "[", "'description'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'Hourly Total'", ",", "result", "[", "'postTaxRecurring'", "]", "]", ")", "else", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Name'", ",", "'Value'", "]", ",", "\"Reciept\"", ")", "table", ".", "add_row", "(", "[", "'Order Date'", ",", "result", "[", "'orderDate'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'Order ID'", ",", "result", "[", "'orderId'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'status'", ",", "result", "[", "'placedOrder'", "]", "[", "'status'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'Hourly Total'", ",", "result", "[", "'orderDetails'", "]", "[", "'postTaxRecurring'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Create a Reserved Capacity instance. *WARNING*: Reserved Capacity is on a yearly contract and not cancelable until the contract is expired.
[ "Create", "a", "Reserved", "Capacity", "instance", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/capacity/create.py#L24-L51
softlayer/softlayer-python
SoftLayer/CLI/cdn/origin_list.py
cli
def cli(env, account_id): """List origin pull mappings.""" manager = SoftLayer.CDNManager(env.client) origins = manager.get_origins(account_id) table = formatting.Table(['id', 'media_type', 'cname', 'origin_url']) for origin in origins: table.add_row([origin['id'], origin['mediaType'], origin.get('cname', formatting.blank()), origin['originUrl']]) env.fout(table)
python
def cli(env, account_id): manager = SoftLayer.CDNManager(env.client) origins = manager.get_origins(account_id) table = formatting.Table(['id', 'media_type', 'cname', 'origin_url']) for origin in origins: table.add_row([origin['id'], origin['mediaType'], origin.get('cname', formatting.blank()), origin['originUrl']]) env.fout(table)
[ "def", "cli", "(", "env", ",", "account_id", ")", ":", "manager", "=", "SoftLayer", ".", "CDNManager", "(", "env", ".", "client", ")", "origins", "=", "manager", ".", "get_origins", "(", "account_id", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'media_type'", ",", "'cname'", ",", "'origin_url'", "]", ")", "for", "origin", "in", "origins", ":", "table", ".", "add_row", "(", "[", "origin", "[", "'id'", "]", ",", "origin", "[", "'mediaType'", "]", ",", "origin", ".", "get", "(", "'cname'", ",", "formatting", ".", "blank", "(", ")", ")", ",", "origin", "[", "'originUrl'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List origin pull mappings.
[ "List", "origin", "pull", "mappings", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/cdn/origin_list.py#L14-L28
softlayer/softlayer-python
SoftLayer/CLI/virt/placementgroup/create_options.py
cli
def cli(env): """List options for creating a placement group.""" manager = PlacementManager(env.client) routers = manager.get_routers() env.fout(get_router_table(routers)) rules = manager.get_all_rules() env.fout(get_rule_table(rules))
python
def cli(env): manager = PlacementManager(env.client) routers = manager.get_routers() env.fout(get_router_table(routers)) rules = manager.get_all_rules() env.fout(get_rule_table(rules))
[ "def", "cli", "(", "env", ")", ":", "manager", "=", "PlacementManager", "(", "env", ".", "client", ")", "routers", "=", "manager", ".", "get_routers", "(", ")", "env", ".", "fout", "(", "get_router_table", "(", "routers", ")", ")", "rules", "=", "manager", ".", "get_all_rules", "(", ")", "env", ".", "fout", "(", "get_rule_table", "(", "rules", ")", ")" ]
List options for creating a placement group.
[ "List", "options", "for", "creating", "a", "placement", "group", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/placementgroup/create_options.py#L13-L21
softlayer/softlayer-python
SoftLayer/CLI/virt/placementgroup/create_options.py
get_router_table
def get_router_table(routers): """Formats output from _get_routers and returns a table. """ table = formatting.Table(['Datacenter', 'Hostname', 'Backend Router Id'], "Available Routers") for router in routers: datacenter = router['topLevelLocation']['longName'] table.add_row([datacenter, router['hostname'], router['id']]) return table
python
def get_router_table(routers): table = formatting.Table(['Datacenter', 'Hostname', 'Backend Router Id'], "Available Routers") for router in routers: datacenter = router['topLevelLocation']['longName'] table.add_row([datacenter, router['hostname'], router['id']]) return table
[ "def", "get_router_table", "(", "routers", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Datacenter'", ",", "'Hostname'", ",", "'Backend Router Id'", "]", ",", "\"Available Routers\"", ")", "for", "router", "in", "routers", ":", "datacenter", "=", "router", "[", "'topLevelLocation'", "]", "[", "'longName'", "]", "table", ".", "add_row", "(", "[", "datacenter", ",", "router", "[", "'hostname'", "]", ",", "router", "[", "'id'", "]", "]", ")", "return", "table" ]
Formats output from _get_routers and returns a table.
[ "Formats", "output", "from", "_get_routers", "and", "returns", "a", "table", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/placementgroup/create_options.py#L24-L30
softlayer/softlayer-python
SoftLayer/CLI/virt/placementgroup/create_options.py
get_rule_table
def get_rule_table(rules): """Formats output from get_all_rules and returns a table. """ table = formatting.Table(['Id', 'KeyName'], "Rules") for rule in rules: table.add_row([rule['id'], rule['keyName']]) return table
python
def get_rule_table(rules): table = formatting.Table(['Id', 'KeyName'], "Rules") for rule in rules: table.add_row([rule['id'], rule['keyName']]) return table
[ "def", "get_rule_table", "(", "rules", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Id'", ",", "'KeyName'", "]", ",", "\"Rules\"", ")", "for", "rule", "in", "rules", ":", "table", ".", "add_row", "(", "[", "rule", "[", "'id'", "]", ",", "rule", "[", "'keyName'", "]", "]", ")", "return", "table" ]
Formats output from get_all_rules and returns a table.
[ "Formats", "output", "from", "get_all_rules", "and", "returns", "a", "table", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/placementgroup/create_options.py#L33-L38
softlayer/softlayer-python
SoftLayer/CLI/virt/detail.py
cli
def cli(env, identifier, passwords=False, price=False): """Get details for a virtual server.""" vsi = SoftLayer.VSManager(env.client) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') result = vsi.get_instance(vs_id) result = utils.NestedDict(result) table.add_row(['id', result['id']]) table.add_row(['guid', result['globalIdentifier']]) table.add_row(['hostname', result['hostname']]) table.add_row(['domain', result['domain']]) table.add_row(['fqdn', result['fullyQualifiedDomainName']]) table.add_row(['status', formatting.FormattedItem( result['status']['keyName'] or formatting.blank(), result['status']['name'] or formatting.blank() )]) table.add_row(['state', formatting.FormattedItem( utils.lookup(result, 'powerState', 'keyName'), utils.lookup(result, 'powerState', 'name'), )]) table.add_row(['active_transaction', formatting.active_txn(result)]) table.add_row(['datacenter', result['datacenter']['name'] or formatting.blank()]) _cli_helper_dedicated_host(env, result, table) operating_system = utils.lookup(result, 'operatingSystem', 'softwareLicense', 'softwareDescription') or {} table.add_row(['os', operating_system.get('name') or formatting.blank()]) table.add_row(['os_version', operating_system.get('version') or formatting.blank()]) table.add_row(['cores', result['maxCpu']]) table.add_row(['memory', formatting.mb_to_gb(result['maxMemory'])]) table.add_row(['public_ip', result['primaryIpAddress'] or formatting.blank()]) table.add_row(['private_ip', result['primaryBackendIpAddress'] or formatting.blank()]) table.add_row(['private_only', result['privateNetworkOnlyFlag']]) table.add_row(['private_cpu', result['dedicatedAccountHostOnlyFlag']]) table.add_row(['created', result['createDate']]) table.add_row(['modified', result['modifyDate']]) if utils.lookup(result, 'billingItem') != []: table.add_row(['owner', formatting.FormattedItem( utils.lookup(result, 'billingItem', 'orderItem', 'order', 'userRecord', 'username') or formatting.blank(), )]) else: table.add_row(['owner', formatting.blank()]) vlan_table = formatting.Table(['type', 'number', 'id']) for vlan in result['networkVlans']: vlan_table.add_row([ vlan['networkSpace'], vlan['vlanNumber'], vlan['id']]) table.add_row(['vlans', vlan_table]) if result.get('networkComponents'): secgroup_table = formatting.Table(['interface', 'id', 'name']) has_secgroups = False for comp in result.get('networkComponents'): interface = 'PRIVATE' if comp['port'] == 0 else 'PUBLIC' for binding in comp['securityGroupBindings']: has_secgroups = True secgroup = binding['securityGroup'] secgroup_table.add_row([ interface, secgroup['id'], secgroup.get('name') or formatting.blank()]) if has_secgroups: table.add_row(['security_groups', secgroup_table]) if result.get('notes'): table.add_row(['notes', result['notes']]) if price: total_price = utils.lookup(result, 'billingItem', 'nextInvoiceTotalRecurringAmount') or 0 total_price += sum(p['nextInvoiceTotalRecurringAmount'] for p in utils.lookup(result, 'billingItem', 'children') or []) table.add_row(['price_rate', total_price]) if passwords: pass_table = formatting.Table(['software', 'username', 'password']) for component in result['softwareComponents']: for item in component['passwords']: pass_table.add_row([ utils.lookup(component, 'softwareLicense', 'softwareDescription', 'name'), item['username'], item['password'], ]) table.add_row(['users', pass_table]) table.add_row(['tags', formatting.tags(result['tagReferences'])]) # Test to see if this actually has a primary (public) ip address try: if not result['privateNetworkOnlyFlag']: ptr_domains = env.client.call( 'Virtual_Guest', 'getReverseDomainRecords', id=vs_id, ) for ptr_domain in ptr_domains: for ptr in ptr_domain['resourceRecords']: table.add_row(['ptr', ptr['data']]) except SoftLayer.SoftLayerAPIError: pass env.fout(table)
python
def cli(env, identifier, passwords=False, price=False): vsi = SoftLayer.VSManager(env.client) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') result = vsi.get_instance(vs_id) result = utils.NestedDict(result) table.add_row(['id', result['id']]) table.add_row(['guid', result['globalIdentifier']]) table.add_row(['hostname', result['hostname']]) table.add_row(['domain', result['domain']]) table.add_row(['fqdn', result['fullyQualifiedDomainName']]) table.add_row(['status', formatting.FormattedItem( result['status']['keyName'] or formatting.blank(), result['status']['name'] or formatting.blank() )]) table.add_row(['state', formatting.FormattedItem( utils.lookup(result, 'powerState', 'keyName'), utils.lookup(result, 'powerState', 'name'), )]) table.add_row(['active_transaction', formatting.active_txn(result)]) table.add_row(['datacenter', result['datacenter']['name'] or formatting.blank()]) _cli_helper_dedicated_host(env, result, table) operating_system = utils.lookup(result, 'operatingSystem', 'softwareLicense', 'softwareDescription') or {} table.add_row(['os', operating_system.get('name') or formatting.blank()]) table.add_row(['os_version', operating_system.get('version') or formatting.blank()]) table.add_row(['cores', result['maxCpu']]) table.add_row(['memory', formatting.mb_to_gb(result['maxMemory'])]) table.add_row(['public_ip', result['primaryIpAddress'] or formatting.blank()]) table.add_row(['private_ip', result['primaryBackendIpAddress'] or formatting.blank()]) table.add_row(['private_only', result['privateNetworkOnlyFlag']]) table.add_row(['private_cpu', result['dedicatedAccountHostOnlyFlag']]) table.add_row(['created', result['createDate']]) table.add_row(['modified', result['modifyDate']]) if utils.lookup(result, 'billingItem') != []: table.add_row(['owner', formatting.FormattedItem( utils.lookup(result, 'billingItem', 'orderItem', 'order', 'userRecord', 'username') or formatting.blank(), )]) else: table.add_row(['owner', formatting.blank()]) vlan_table = formatting.Table(['type', 'number', 'id']) for vlan in result['networkVlans']: vlan_table.add_row([ vlan['networkSpace'], vlan['vlanNumber'], vlan['id']]) table.add_row(['vlans', vlan_table]) if result.get('networkComponents'): secgroup_table = formatting.Table(['interface', 'id', 'name']) has_secgroups = False for comp in result.get('networkComponents'): interface = 'PRIVATE' if comp['port'] == 0 else 'PUBLIC' for binding in comp['securityGroupBindings']: has_secgroups = True secgroup = binding['securityGroup'] secgroup_table.add_row([ interface, secgroup['id'], secgroup.get('name') or formatting.blank()]) if has_secgroups: table.add_row(['security_groups', secgroup_table]) if result.get('notes'): table.add_row(['notes', result['notes']]) if price: total_price = utils.lookup(result, 'billingItem', 'nextInvoiceTotalRecurringAmount') or 0 total_price += sum(p['nextInvoiceTotalRecurringAmount'] for p in utils.lookup(result, 'billingItem', 'children') or []) table.add_row(['price_rate', total_price]) if passwords: pass_table = formatting.Table(['software', 'username', 'password']) for component in result['softwareComponents']: for item in component['passwords']: pass_table.add_row([ utils.lookup(component, 'softwareLicense', 'softwareDescription', 'name'), item['username'], item['password'], ]) table.add_row(['users', pass_table]) table.add_row(['tags', formatting.tags(result['tagReferences'])]) try: if not result['privateNetworkOnlyFlag']: ptr_domains = env.client.call( 'Virtual_Guest', 'getReverseDomainRecords', id=vs_id, ) for ptr_domain in ptr_domains: for ptr in ptr_domain['resourceRecords']: table.add_row(['ptr', ptr['data']]) except SoftLayer.SoftLayerAPIError: pass env.fout(table)
[ "def", "cli", "(", "env", ",", "identifier", ",", "passwords", "=", "False", ",", "price", "=", "False", ")", ":", "vsi", "=", "SoftLayer", ".", "VSManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "table", ".", "align", "[", "'name'", "]", "=", "'r'", "table", ".", "align", "[", "'value'", "]", "=", "'l'", "vs_id", "=", "helpers", ".", "resolve_id", "(", "vsi", ".", "resolve_ids", ",", "identifier", ",", "'VS'", ")", "result", "=", "vsi", ".", "get_instance", "(", "vs_id", ")", "result", "=", "utils", ".", "NestedDict", "(", "result", ")", "table", ".", "add_row", "(", "[", "'id'", ",", "result", "[", "'id'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'guid'", ",", "result", "[", "'globalIdentifier'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'hostname'", ",", "result", "[", "'hostname'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'domain'", ",", "result", "[", "'domain'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'fqdn'", ",", "result", "[", "'fullyQualifiedDomainName'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'status'", ",", "formatting", ".", "FormattedItem", "(", "result", "[", "'status'", "]", "[", "'keyName'", "]", "or", "formatting", ".", "blank", "(", ")", ",", "result", "[", "'status'", "]", "[", "'name'", "]", "or", "formatting", ".", "blank", "(", ")", ")", "]", ")", "table", ".", "add_row", "(", "[", "'state'", ",", "formatting", ".", "FormattedItem", "(", "utils", ".", "lookup", "(", "result", ",", "'powerState'", ",", "'keyName'", ")", ",", "utils", ".", "lookup", "(", "result", ",", "'powerState'", ",", "'name'", ")", ",", ")", "]", ")", "table", ".", "add_row", "(", "[", "'active_transaction'", ",", "formatting", ".", "active_txn", "(", "result", ")", "]", ")", "table", ".", "add_row", "(", "[", "'datacenter'", ",", "result", "[", "'datacenter'", "]", "[", "'name'", "]", "or", "formatting", ".", "blank", "(", ")", "]", ")", "_cli_helper_dedicated_host", "(", "env", ",", "result", ",", "table", ")", "operating_system", "=", "utils", ".", "lookup", "(", "result", ",", "'operatingSystem'", ",", "'softwareLicense'", ",", "'softwareDescription'", ")", "or", "{", "}", "table", ".", "add_row", "(", "[", "'os'", ",", "operating_system", ".", "get", "(", "'name'", ")", "or", "formatting", ".", "blank", "(", ")", "]", ")", "table", ".", "add_row", "(", "[", "'os_version'", ",", "operating_system", ".", "get", "(", "'version'", ")", "or", "formatting", ".", "blank", "(", ")", "]", ")", "table", ".", "add_row", "(", "[", "'cores'", ",", "result", "[", "'maxCpu'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'memory'", ",", "formatting", ".", "mb_to_gb", "(", "result", "[", "'maxMemory'", "]", ")", "]", ")", "table", ".", "add_row", "(", "[", "'public_ip'", ",", "result", "[", "'primaryIpAddress'", "]", "or", "formatting", ".", "blank", "(", ")", "]", ")", "table", ".", "add_row", "(", "[", "'private_ip'", ",", "result", "[", "'primaryBackendIpAddress'", "]", "or", "formatting", ".", "blank", "(", ")", "]", ")", "table", ".", "add_row", "(", "[", "'private_only'", ",", "result", "[", "'privateNetworkOnlyFlag'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'private_cpu'", ",", "result", "[", "'dedicatedAccountHostOnlyFlag'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'created'", ",", "result", "[", "'createDate'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'modified'", ",", "result", "[", "'modifyDate'", "]", "]", ")", "if", "utils", ".", "lookup", "(", "result", ",", "'billingItem'", ")", "!=", "[", "]", ":", "table", ".", "add_row", "(", "[", "'owner'", ",", "formatting", ".", "FormattedItem", "(", "utils", ".", "lookup", "(", "result", ",", "'billingItem'", ",", "'orderItem'", ",", "'order'", ",", "'userRecord'", ",", "'username'", ")", "or", "formatting", ".", "blank", "(", ")", ",", ")", "]", ")", "else", ":", "table", ".", "add_row", "(", "[", "'owner'", ",", "formatting", ".", "blank", "(", ")", "]", ")", "vlan_table", "=", "formatting", ".", "Table", "(", "[", "'type'", ",", "'number'", ",", "'id'", "]", ")", "for", "vlan", "in", "result", "[", "'networkVlans'", "]", ":", "vlan_table", ".", "add_row", "(", "[", "vlan", "[", "'networkSpace'", "]", ",", "vlan", "[", "'vlanNumber'", "]", ",", "vlan", "[", "'id'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'vlans'", ",", "vlan_table", "]", ")", "if", "result", ".", "get", "(", "'networkComponents'", ")", ":", "secgroup_table", "=", "formatting", ".", "Table", "(", "[", "'interface'", ",", "'id'", ",", "'name'", "]", ")", "has_secgroups", "=", "False", "for", "comp", "in", "result", ".", "get", "(", "'networkComponents'", ")", ":", "interface", "=", "'PRIVATE'", "if", "comp", "[", "'port'", "]", "==", "0", "else", "'PUBLIC'", "for", "binding", "in", "comp", "[", "'securityGroupBindings'", "]", ":", "has_secgroups", "=", "True", "secgroup", "=", "binding", "[", "'securityGroup'", "]", "secgroup_table", ".", "add_row", "(", "[", "interface", ",", "secgroup", "[", "'id'", "]", ",", "secgroup", ".", "get", "(", "'name'", ")", "or", "formatting", ".", "blank", "(", ")", "]", ")", "if", "has_secgroups", ":", "table", ".", "add_row", "(", "[", "'security_groups'", ",", "secgroup_table", "]", ")", "if", "result", ".", "get", "(", "'notes'", ")", ":", "table", ".", "add_row", "(", "[", "'notes'", ",", "result", "[", "'notes'", "]", "]", ")", "if", "price", ":", "total_price", "=", "utils", ".", "lookup", "(", "result", ",", "'billingItem'", ",", "'nextInvoiceTotalRecurringAmount'", ")", "or", "0", "total_price", "+=", "sum", "(", "p", "[", "'nextInvoiceTotalRecurringAmount'", "]", "for", "p", "in", "utils", ".", "lookup", "(", "result", ",", "'billingItem'", ",", "'children'", ")", "or", "[", "]", ")", "table", ".", "add_row", "(", "[", "'price_rate'", ",", "total_price", "]", ")", "if", "passwords", ":", "pass_table", "=", "formatting", ".", "Table", "(", "[", "'software'", ",", "'username'", ",", "'password'", "]", ")", "for", "component", "in", "result", "[", "'softwareComponents'", "]", ":", "for", "item", "in", "component", "[", "'passwords'", "]", ":", "pass_table", ".", "add_row", "(", "[", "utils", ".", "lookup", "(", "component", ",", "'softwareLicense'", ",", "'softwareDescription'", ",", "'name'", ")", ",", "item", "[", "'username'", "]", ",", "item", "[", "'password'", "]", ",", "]", ")", "table", ".", "add_row", "(", "[", "'users'", ",", "pass_table", "]", ")", "table", ".", "add_row", "(", "[", "'tags'", ",", "formatting", ".", "tags", "(", "result", "[", "'tagReferences'", "]", ")", "]", ")", "# Test to see if this actually has a primary (public) ip address", "try", ":", "if", "not", "result", "[", "'privateNetworkOnlyFlag'", "]", ":", "ptr_domains", "=", "env", ".", "client", ".", "call", "(", "'Virtual_Guest'", ",", "'getReverseDomainRecords'", ",", "id", "=", "vs_id", ",", ")", "for", "ptr_domain", "in", "ptr_domains", ":", "for", "ptr", "in", "ptr_domain", "[", "'resourceRecords'", "]", ":", "table", ".", "add_row", "(", "[", "'ptr'", ",", "ptr", "[", "'data'", "]", "]", ")", "except", "SoftLayer", ".", "SoftLayerAPIError", ":", "pass", "env", ".", "fout", "(", "table", ")" ]
Get details for a virtual server.
[ "Get", "details", "for", "a", "virtual", "server", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/detail.py#L24-L145
softlayer/softlayer-python
SoftLayer/CLI/virt/detail.py
_cli_helper_dedicated_host
def _cli_helper_dedicated_host(env, result, table): """Get details on dedicated host for a virtual server.""" dedicated_host_id = utils.lookup(result, 'dedicatedHost', 'id') if dedicated_host_id: table.add_row(['dedicated_host_id', dedicated_host_id]) # Try to find name of dedicated host try: dedicated_host = env.client.call('Virtual_DedicatedHost', 'getObject', id=dedicated_host_id) except SoftLayer.SoftLayerAPIError: LOGGER.error('Unable to get dedicated host id %s', dedicated_host_id) dedicated_host = {} table.add_row(['dedicated_host', dedicated_host.get('name') or formatting.blank()])
python
def _cli_helper_dedicated_host(env, result, table): dedicated_host_id = utils.lookup(result, 'dedicatedHost', 'id') if dedicated_host_id: table.add_row(['dedicated_host_id', dedicated_host_id]) try: dedicated_host = env.client.call('Virtual_DedicatedHost', 'getObject', id=dedicated_host_id) except SoftLayer.SoftLayerAPIError: LOGGER.error('Unable to get dedicated host id %s', dedicated_host_id) dedicated_host = {} table.add_row(['dedicated_host', dedicated_host.get('name') or formatting.blank()])
[ "def", "_cli_helper_dedicated_host", "(", "env", ",", "result", ",", "table", ")", ":", "dedicated_host_id", "=", "utils", ".", "lookup", "(", "result", ",", "'dedicatedHost'", ",", "'id'", ")", "if", "dedicated_host_id", ":", "table", ".", "add_row", "(", "[", "'dedicated_host_id'", ",", "dedicated_host_id", "]", ")", "# Try to find name of dedicated host", "try", ":", "dedicated_host", "=", "env", ".", "client", ".", "call", "(", "'Virtual_DedicatedHost'", ",", "'getObject'", ",", "id", "=", "dedicated_host_id", ")", "except", "SoftLayer", ".", "SoftLayerAPIError", ":", "LOGGER", ".", "error", "(", "'Unable to get dedicated host id %s'", ",", "dedicated_host_id", ")", "dedicated_host", "=", "{", "}", "table", ".", "add_row", "(", "[", "'dedicated_host'", ",", "dedicated_host", ".", "get", "(", "'name'", ")", "or", "formatting", ".", "blank", "(", ")", "]", ")" ]
Get details on dedicated host for a virtual server.
[ "Get", "details", "on", "dedicated", "host", "for", "a", "virtual", "server", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/detail.py#L148-L162
softlayer/softlayer-python
SoftLayer/CLI/virt/ready.py
cli
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)
python
def cli(env, identifier, wait): 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", "cli", "(", "env", ",", "identifier", ",", "wait", ")", ":", "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", ")" ]
Check if a virtual server is ready.
[ "Check", "if", "a", "virtual", "server", "is", "ready", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/ready.py#L16-L25
softlayer/softlayer-python
SoftLayer/CLI/block/replication/failover.py
cli
def cli(env, volume_id, replicant_id, immediate): """Failover a block volume to the given replicant volume.""" block_storage_manager = SoftLayer.BlockStorageManager(env.client) success = block_storage_manager.failover_to_replicant( volume_id, replicant_id, immediate ) if success: click.echo("Failover to replicant is now in progress.") else: click.echo("Failover operation could not be initiated.")
python
def cli(env, volume_id, replicant_id, immediate): block_storage_manager = SoftLayer.BlockStorageManager(env.client) success = block_storage_manager.failover_to_replicant( volume_id, replicant_id, immediate ) if success: click.echo("Failover to replicant is now in progress.") else: click.echo("Failover operation could not be initiated.")
[ "def", "cli", "(", "env", ",", "volume_id", ",", "replicant_id", ",", "immediate", ")", ":", "block_storage_manager", "=", "SoftLayer", ".", "BlockStorageManager", "(", "env", ".", "client", ")", "success", "=", "block_storage_manager", ".", "failover_to_replicant", "(", "volume_id", ",", "replicant_id", ",", "immediate", ")", "if", "success", ":", "click", ".", "echo", "(", "\"Failover to replicant is now in progress.\"", ")", "else", ":", "click", ".", "echo", "(", "\"Failover operation could not be initiated.\"", ")" ]
Failover a block volume to the given replicant volume.
[ "Failover", "a", "block", "volume", "to", "the", "given", "replicant", "volume", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/block/replication/failover.py#L17-L30
softlayer/softlayer-python
SoftLayer/CLI/dedicatedhost/cancel.py
cli
def cli(env, identifier): """Cancel a dedicated host server immediately""" mgr = SoftLayer.DedicatedHostManager(env.client) host_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'dedicated host') if not (env.skip_confirmations or formatting.no_going_back(host_id)): raise exceptions.CLIAbort('Aborted') mgr.cancel_host(host_id) click.secho('Dedicated Host %s was cancelled' % host_id, fg='green')
python
def cli(env, identifier): mgr = SoftLayer.DedicatedHostManager(env.client) host_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'dedicated host') if not (env.skip_confirmations or formatting.no_going_back(host_id)): raise exceptions.CLIAbort('Aborted') mgr.cancel_host(host_id) click.secho('Dedicated Host %s was cancelled' % host_id, fg='green')
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "DedicatedHostManager", "(", "env", ".", "client", ")", "host_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_ids", ",", "identifier", ",", "'dedicated host'", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "no_going_back", "(", "host_id", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted'", ")", "mgr", ".", "cancel_host", "(", "host_id", ")", "click", ".", "secho", "(", "'Dedicated Host %s was cancelled'", "%", "host_id", ",", "fg", "=", "'green'", ")" ]
Cancel a dedicated host server immediately
[ "Cancel", "a", "dedicated", "host", "server", "immediately" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/cancel.py#L16-L28
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager.get_image
def get_image(self, image_id, **kwargs): """Get details about an image. :param int image: The ID of the image. :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK return self.vgbdtg.getObject(id=image_id, **kwargs)
python
def get_image(self, image_id, **kwargs): if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK return self.vgbdtg.getObject(id=image_id, **kwargs)
[ "def", "get_image", "(", "self", ",", "image_id", ",", "*", "*", "kwargs", ")", ":", "if", "'mask'", "not", "in", "kwargs", ":", "kwargs", "[", "'mask'", "]", "=", "IMAGE_MASK", "return", "self", ".", "vgbdtg", ".", "getObject", "(", "id", "=", "image_id", ",", "*", "*", "kwargs", ")" ]
Get details about an image. :param int image: The ID of the image. :param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
[ "Get", "details", "about", "an", "image", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L30-L39
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager.list_private_images
def list_private_images(self, guid=None, name=None, **kwargs): """List all private images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if name: _filter['privateBlockDeviceTemplateGroups']['name'] = ( utils.query_filter(name)) if guid: _filter['privateBlockDeviceTemplateGroups']['globalIdentifier'] = ( utils.query_filter(guid)) kwargs['filter'] = _filter.to_dict() account = self.client['Account'] return account.getPrivateBlockDeviceTemplateGroups(**kwargs)
python
def list_private_images(self, guid=None, name=None, **kwargs): if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if name: _filter['privateBlockDeviceTemplateGroups']['name'] = ( utils.query_filter(name)) if guid: _filter['privateBlockDeviceTemplateGroups']['globalIdentifier'] = ( utils.query_filter(guid)) kwargs['filter'] = _filter.to_dict() account = self.client['Account'] return account.getPrivateBlockDeviceTemplateGroups(**kwargs)
[ "def", "list_private_images", "(", "self", ",", "guid", "=", "None", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'mask'", "not", "in", "kwargs", ":", "kwargs", "[", "'mask'", "]", "=", "IMAGE_MASK", "_filter", "=", "utils", ".", "NestedDict", "(", "kwargs", ".", "get", "(", "'filter'", ")", "or", "{", "}", ")", "if", "name", ":", "_filter", "[", "'privateBlockDeviceTemplateGroups'", "]", "[", "'name'", "]", "=", "(", "utils", ".", "query_filter", "(", "name", ")", ")", "if", "guid", ":", "_filter", "[", "'privateBlockDeviceTemplateGroups'", "]", "[", "'globalIdentifier'", "]", "=", "(", "utils", ".", "query_filter", "(", "guid", ")", ")", "kwargs", "[", "'filter'", "]", "=", "_filter", ".", "to_dict", "(", ")", "account", "=", "self", ".", "client", "[", "'Account'", "]", "return", "account", ".", "getPrivateBlockDeviceTemplateGroups", "(", "*", "*", "kwargs", ")" ]
List all private images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
[ "List", "all", "private", "images", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L48-L70
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager.list_public_images
def list_public_images(self, guid=None, name=None, **kwargs): """List all public images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if name: _filter['name'] = utils.query_filter(name) if guid: _filter['globalIdentifier'] = utils.query_filter(guid) kwargs['filter'] = _filter.to_dict() return self.vgbdtg.getPublicImages(**kwargs)
python
def list_public_images(self, guid=None, name=None, **kwargs): if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if name: _filter['name'] = utils.query_filter(name) if guid: _filter['globalIdentifier'] = utils.query_filter(guid) kwargs['filter'] = _filter.to_dict() return self.vgbdtg.getPublicImages(**kwargs)
[ "def", "list_public_images", "(", "self", ",", "guid", "=", "None", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'mask'", "not", "in", "kwargs", ":", "kwargs", "[", "'mask'", "]", "=", "IMAGE_MASK", "_filter", "=", "utils", ".", "NestedDict", "(", "kwargs", ".", "get", "(", "'filter'", ")", "or", "{", "}", ")", "if", "name", ":", "_filter", "[", "'name'", "]", "=", "utils", ".", "query_filter", "(", "name", ")", "if", "guid", ":", "_filter", "[", "'globalIdentifier'", "]", "=", "utils", ".", "query_filter", "(", "guid", ")", "kwargs", "[", "'filter'", "]", "=", "_filter", ".", "to_dict", "(", ")", "return", "self", ".", "vgbdtg", ".", "getPublicImages", "(", "*", "*", "kwargs", ")" ]
List all public images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
[ "List", "all", "public", "images", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L72-L91
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager._get_ids_from_name_public
def _get_ids_from_name_public(self, name): """Get public images which match the given name.""" results = self.list_public_images(name=name) return [result['id'] for result in results]
python
def _get_ids_from_name_public(self, name): results = self.list_public_images(name=name) return [result['id'] for result in results]
[ "def", "_get_ids_from_name_public", "(", "self", ",", "name", ")", ":", "results", "=", "self", ".", "list_public_images", "(", "name", "=", "name", ")", "return", "[", "result", "[", "'id'", "]", "for", "result", "in", "results", "]" ]
Get public images which match the given name.
[ "Get", "public", "images", "which", "match", "the", "given", "name", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L93-L96
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager._get_ids_from_name_private
def _get_ids_from_name_private(self, name): """Get private images which match the given name.""" results = self.list_private_images(name=name) return [result['id'] for result in results]
python
def _get_ids_from_name_private(self, name): results = self.list_private_images(name=name) return [result['id'] for result in results]
[ "def", "_get_ids_from_name_private", "(", "self", ",", "name", ")", ":", "results", "=", "self", ".", "list_private_images", "(", "name", "=", "name", ")", "return", "[", "result", "[", "'id'", "]", "for", "result", "in", "results", "]" ]
Get private images which match the given name.
[ "Get", "private", "images", "which", "match", "the", "given", "name", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L98-L101
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager.edit
def edit(self, image_id, name=None, note=None, tag=None): """Edit image related details. :param int image_id: The ID of the image :param string name: Name of the Image. :param string note: Note of the image. :param string tag: Tags of the image to be updated to. """ obj = {} if name: obj['name'] = name if note: obj['note'] = note if obj: self.vgbdtg.editObject(obj, id=image_id) if tag: self.vgbdtg.setTags(str(tag), id=image_id) return bool(name or note or tag)
python
def edit(self, image_id, name=None, note=None, tag=None): obj = {} if name: obj['name'] = name if note: obj['note'] = note if obj: self.vgbdtg.editObject(obj, id=image_id) if tag: self.vgbdtg.setTags(str(tag), id=image_id) return bool(name or note or tag)
[ "def", "edit", "(", "self", ",", "image_id", ",", "name", "=", "None", ",", "note", "=", "None", ",", "tag", "=", "None", ")", ":", "obj", "=", "{", "}", "if", "name", ":", "obj", "[", "'name'", "]", "=", "name", "if", "note", ":", "obj", "[", "'note'", "]", "=", "note", "if", "obj", ":", "self", ".", "vgbdtg", ".", "editObject", "(", "obj", ",", "id", "=", "image_id", ")", "if", "tag", ":", "self", ".", "vgbdtg", ".", "setTags", "(", "str", "(", "tag", ")", ",", "id", "=", "image_id", ")", "return", "bool", "(", "name", "or", "note", "or", "tag", ")" ]
Edit image related details. :param int image_id: The ID of the image :param string name: Name of the Image. :param string note: Note of the image. :param string tag: Tags of the image to be updated to.
[ "Edit", "image", "related", "details", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L103-L121
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager.import_image_from_uri
def import_image_from_uri(self, name, uri, os_code=None, note=None, ibm_api_key=None, root_key_crn=None, wrapped_dek=None, cloud_init=False, byol=False, is_encrypted=False): """Import a new image from object storage. :param string name: Name of the new image :param string uri: The URI for an object storage object (.vhd/.iso file) of the format: swift://<objectStorageAccount>@<cluster>/<container>/<objectPath> or (.vhd/.iso/.raw file) of the format: cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud Object Storage :param string os_code: The reference code of the operating system :param string note: Note to add to the image :param string ibm_api_key: Ibm Api Key needed to communicate with ICOS and your KMS :param string root_key_crn: CRN of the root key in your KMS. Go to your KMS (Key Protect or Hyper Protect) provider to get the CRN for your root key. An example CRN: crn:v1:bluemix:public:hs-crypto:us-south:acctID:serviceID:key:keyID' Used only when is_encrypted is True. :param string wrapped_dek: Wrapped Data Encryption Key provided by your KMS. Used only when is_encrypted is True. :param boolean cloud_init: Specifies if image is cloud-init :param boolean byol: Specifies if image is bring your own license :param boolean is_encrypted: Specifies if image is encrypted """ if 'cos://' in uri: return self.vgbdtg.createFromIcos({ 'name': name, 'note': note, 'operatingSystemReferenceCode': os_code, 'uri': uri, 'ibmApiKey': ibm_api_key, 'crkCrn': root_key_crn, 'wrappedDek': wrapped_dek, 'cloudInit': cloud_init, 'byol': byol, 'isEncrypted': is_encrypted }) else: return self.vgbdtg.createFromExternalSource({ 'name': name, 'note': note, 'operatingSystemReferenceCode': os_code, 'uri': uri, })
python
def import_image_from_uri(self, name, uri, os_code=None, note=None, ibm_api_key=None, root_key_crn=None, wrapped_dek=None, cloud_init=False, byol=False, is_encrypted=False): if 'cos://' in uri: return self.vgbdtg.createFromIcos({ 'name': name, 'note': note, 'operatingSystemReferenceCode': os_code, 'uri': uri, 'ibmApiKey': ibm_api_key, 'crkCrn': root_key_crn, 'wrappedDek': wrapped_dek, 'cloudInit': cloud_init, 'byol': byol, 'isEncrypted': is_encrypted }) else: return self.vgbdtg.createFromExternalSource({ 'name': name, 'note': note, 'operatingSystemReferenceCode': os_code, 'uri': uri, })
[ "def", "import_image_from_uri", "(", "self", ",", "name", ",", "uri", ",", "os_code", "=", "None", ",", "note", "=", "None", ",", "ibm_api_key", "=", "None", ",", "root_key_crn", "=", "None", ",", "wrapped_dek", "=", "None", ",", "cloud_init", "=", "False", ",", "byol", "=", "False", ",", "is_encrypted", "=", "False", ")", ":", "if", "'cos://'", "in", "uri", ":", "return", "self", ".", "vgbdtg", ".", "createFromIcos", "(", "{", "'name'", ":", "name", ",", "'note'", ":", "note", ",", "'operatingSystemReferenceCode'", ":", "os_code", ",", "'uri'", ":", "uri", ",", "'ibmApiKey'", ":", "ibm_api_key", ",", "'crkCrn'", ":", "root_key_crn", ",", "'wrappedDek'", ":", "wrapped_dek", ",", "'cloudInit'", ":", "cloud_init", ",", "'byol'", ":", "byol", ",", "'isEncrypted'", ":", "is_encrypted", "}", ")", "else", ":", "return", "self", ".", "vgbdtg", ".", "createFromExternalSource", "(", "{", "'name'", ":", "name", ",", "'note'", ":", "note", ",", "'operatingSystemReferenceCode'", ":", "os_code", ",", "'uri'", ":", "uri", ",", "}", ")" ]
Import a new image from object storage. :param string name: Name of the new image :param string uri: The URI for an object storage object (.vhd/.iso file) of the format: swift://<objectStorageAccount>@<cluster>/<container>/<objectPath> or (.vhd/.iso/.raw file) of the format: cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud Object Storage :param string os_code: The reference code of the operating system :param string note: Note to add to the image :param string ibm_api_key: Ibm Api Key needed to communicate with ICOS and your KMS :param string root_key_crn: CRN of the root key in your KMS. Go to your KMS (Key Protect or Hyper Protect) provider to get the CRN for your root key. An example CRN: crn:v1:bluemix:public:hs-crypto:us-south:acctID:serviceID:key:keyID' Used only when is_encrypted is True. :param string wrapped_dek: Wrapped Data Encryption Key provided by your KMS. Used only when is_encrypted is True. :param boolean cloud_init: Specifies if image is cloud-init :param boolean byol: Specifies if image is bring your own license :param boolean is_encrypted: Specifies if image is encrypted
[ "Import", "a", "new", "image", "from", "object", "storage", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L123-L170
softlayer/softlayer-python
SoftLayer/managers/image.py
ImageManager.export_image_to_uri
def export_image_to_uri(self, image_id, uri, ibm_api_key=None): """Export image into the given object storage :param int image_id: The ID of the image :param string uri: The URI for object storage of the format swift://<objectStorageAccount>@<cluster>/<container>/<objectPath> or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud Object Storage :param string ibm_api_key: Ibm Api Key needed to communicate with IBM Cloud Object Storage """ if 'cos://' in uri: return self.vgbdtg.copyToIcos({ 'uri': uri, 'ibmApiKey': ibm_api_key }, id=image_id) else: return self.vgbdtg.copyToExternalSource({'uri': uri}, id=image_id)
python
def export_image_to_uri(self, image_id, uri, ibm_api_key=None): if 'cos://' in uri: return self.vgbdtg.copyToIcos({ 'uri': uri, 'ibmApiKey': ibm_api_key }, id=image_id) else: return self.vgbdtg.copyToExternalSource({'uri': uri}, id=image_id)
[ "def", "export_image_to_uri", "(", "self", ",", "image_id", ",", "uri", ",", "ibm_api_key", "=", "None", ")", ":", "if", "'cos://'", "in", "uri", ":", "return", "self", ".", "vgbdtg", ".", "copyToIcos", "(", "{", "'uri'", ":", "uri", ",", "'ibmApiKey'", ":", "ibm_api_key", "}", ",", "id", "=", "image_id", ")", "else", ":", "return", "self", ".", "vgbdtg", ".", "copyToExternalSource", "(", "{", "'uri'", ":", "uri", "}", ",", "id", "=", "image_id", ")" ]
Export image into the given object storage :param int image_id: The ID of the image :param string uri: The URI for object storage of the format swift://<objectStorageAccount>@<cluster>/<container>/<objectPath> or cos://<regionName>/<bucketName>/<objectPath> if using IBM Cloud Object Storage :param string ibm_api_key: Ibm Api Key needed to communicate with IBM Cloud Object Storage
[ "Export", "image", "into", "the", "given", "object", "storage" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/image.py#L172-L189
softlayer/softlayer-python
SoftLayer/CLI/object_storage/credential/delete.py
cli
def cli(env, identifier, credential_id): """Delete the credential of an Object Storage Account.""" mgr = SoftLayer.ObjectStorageManager(env.client) credential = mgr.delete_credential(identifier, credential_id=credential_id) env.fout(credential)
python
def cli(env, identifier, credential_id): mgr = SoftLayer.ObjectStorageManager(env.client) credential = mgr.delete_credential(identifier, credential_id=credential_id) env.fout(credential)
[ "def", "cli", "(", "env", ",", "identifier", ",", "credential_id", ")", ":", "mgr", "=", "SoftLayer", ".", "ObjectStorageManager", "(", "env", ".", "client", ")", "credential", "=", "mgr", ".", "delete_credential", "(", "identifier", ",", "credential_id", "=", "credential_id", ")", "env", ".", "fout", "(", "credential", ")" ]
Delete the credential of an Object Storage Account.
[ "Delete", "the", "credential", "of", "an", "Object", "Storage", "Account", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/object_storage/credential/delete.py#L15-L21
softlayer/softlayer-python
SoftLayer/managers/vs_capacity.py
CapacityManager.list
def list(self): """List Reserved Capacities""" mask = """mask[availableInstanceCount, occupiedInstanceCount, instances[id, billingItem[description, hourlyRecurringFee]], instanceCount, backendRouter[datacenter]]""" results = self.client.call('Account', 'getReservedCapacityGroups', mask=mask) return results
python
def list(self): mask = results = self.client.call('Account', 'getReservedCapacityGroups', mask=mask) return results
[ "def", "list", "(", "self", ")", ":", "mask", "=", "\"\"\"mask[availableInstanceCount, occupiedInstanceCount,\ninstances[id, billingItem[description, hourlyRecurringFee]], instanceCount, backendRouter[datacenter]]\"\"\"", "results", "=", "self", ".", "client", ".", "call", "(", "'Account'", ",", "'getReservedCapacityGroups'", ",", "mask", "=", "mask", ")", "return", "results" ]
List Reserved Capacities
[ "List", "Reserved", "Capacities" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_capacity.py#L46-L51
softlayer/softlayer-python
SoftLayer/managers/vs_capacity.py
CapacityManager.get_object
def get_object(self, identifier, mask=None): """Get a Reserved Capacity Group :param int identifier: Id of the SoftLayer_Virtual_ReservedCapacityGroup :param string mask: override default object Mask """ if mask is None: mask = "mask[instances[billingItem[item[keyName],category], guest], backendRouter[datacenter]]" result = self.client.call(self.rcg_service, 'getObject', id=identifier, mask=mask) return result
python
def get_object(self, identifier, mask=None): if mask is None: mask = "mask[instances[billingItem[item[keyName],category], guest], backendRouter[datacenter]]" result = self.client.call(self.rcg_service, 'getObject', id=identifier, mask=mask) return result
[ "def", "get_object", "(", "self", ",", "identifier", ",", "mask", "=", "None", ")", ":", "if", "mask", "is", "None", ":", "mask", "=", "\"mask[instances[billingItem[item[keyName],category], guest], backendRouter[datacenter]]\"", "result", "=", "self", ".", "client", ".", "call", "(", "self", ".", "rcg_service", ",", "'getObject'", ",", "id", "=", "identifier", ",", "mask", "=", "mask", ")", "return", "result" ]
Get a Reserved Capacity Group :param int identifier: Id of the SoftLayer_Virtual_ReservedCapacityGroup :param string mask: override default object Mask
[ "Get", "a", "Reserved", "Capacity", "Group" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_capacity.py#L53-L62
softlayer/softlayer-python
SoftLayer/managers/vs_capacity.py
CapacityManager.get_create_options
def get_create_options(self): """List available reserved capacity plans""" mask = "mask[attributes,prices[pricingLocationGroup]]" results = self.ordering_manager.list_items(self.capacity_package, mask=mask) return results
python
def get_create_options(self): mask = "mask[attributes,prices[pricingLocationGroup]]" results = self.ordering_manager.list_items(self.capacity_package, mask=mask) return results
[ "def", "get_create_options", "(", "self", ")", ":", "mask", "=", "\"mask[attributes,prices[pricingLocationGroup]]\"", "results", "=", "self", ".", "ordering_manager", ".", "list_items", "(", "self", ".", "capacity_package", ",", "mask", "=", "mask", ")", "return", "results" ]
List available reserved capacity plans
[ "List", "available", "reserved", "capacity", "plans" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_capacity.py#L64-L68
softlayer/softlayer-python
SoftLayer/managers/vs_capacity.py
CapacityManager.get_available_routers
def get_available_routers(self, dc=None): """Pulls down all backendRouterIds that are available :param string dc: A specific location to get routers for, like 'dal13'. :returns list: A list of locations where RESERVED_CAPACITY can be ordered. """ mask = "mask[locations]" # Step 1, get the package id package = self.ordering_manager.get_package_by_key(self.capacity_package, mask="id") # Step 2, get the regions this package is orderable in regions = self.client.call('Product_Package', 'getRegions', id=package['id'], mask=mask, iter=True) _filter = None routers = {} if dc is not None: _filter = {'datacenterName': {'operation': dc}} # Step 3, for each location in each region, get the pod details, which contains the router id pods = self.client.call('Network_Pod', 'getAllObjects', filter=_filter, iter=True) for region in regions: routers[region['keyname']] = [] for location in region['locations']: location['location']['pods'] = list() for pod in pods: if pod['datacenterName'] == location['location']['name']: location['location']['pods'].append(pod) # Step 4, return the data. return regions
python
def get_available_routers(self, dc=None): mask = "mask[locations]" package = self.ordering_manager.get_package_by_key(self.capacity_package, mask="id") regions = self.client.call('Product_Package', 'getRegions', id=package['id'], mask=mask, iter=True) _filter = None routers = {} if dc is not None: _filter = {'datacenterName': {'operation': dc}} pods = self.client.call('Network_Pod', 'getAllObjects', filter=_filter, iter=True) for region in regions: routers[region['keyname']] = [] for location in region['locations']: location['location']['pods'] = list() for pod in pods: if pod['datacenterName'] == location['location']['name']: location['location']['pods'].append(pod) return regions
[ "def", "get_available_routers", "(", "self", ",", "dc", "=", "None", ")", ":", "mask", "=", "\"mask[locations]\"", "# Step 1, get the package id", "package", "=", "self", ".", "ordering_manager", ".", "get_package_by_key", "(", "self", ".", "capacity_package", ",", "mask", "=", "\"id\"", ")", "# Step 2, get the regions this package is orderable in", "regions", "=", "self", ".", "client", ".", "call", "(", "'Product_Package'", ",", "'getRegions'", ",", "id", "=", "package", "[", "'id'", "]", ",", "mask", "=", "mask", ",", "iter", "=", "True", ")", "_filter", "=", "None", "routers", "=", "{", "}", "if", "dc", "is", "not", "None", ":", "_filter", "=", "{", "'datacenterName'", ":", "{", "'operation'", ":", "dc", "}", "}", "# Step 3, for each location in each region, get the pod details, which contains the router id", "pods", "=", "self", ".", "client", ".", "call", "(", "'Network_Pod'", ",", "'getAllObjects'", ",", "filter", "=", "_filter", ",", "iter", "=", "True", ")", "for", "region", "in", "regions", ":", "routers", "[", "region", "[", "'keyname'", "]", "]", "=", "[", "]", "for", "location", "in", "region", "[", "'locations'", "]", ":", "location", "[", "'location'", "]", "[", "'pods'", "]", "=", "list", "(", ")", "for", "pod", "in", "pods", ":", "if", "pod", "[", "'datacenterName'", "]", "==", "location", "[", "'location'", "]", "[", "'name'", "]", ":", "location", "[", "'location'", "]", "[", "'pods'", "]", ".", "append", "(", "pod", ")", "# Step 4, return the data.", "return", "regions" ]
Pulls down all backendRouterIds that are available :param string dc: A specific location to get routers for, like 'dal13'. :returns list: A list of locations where RESERVED_CAPACITY can be ordered.
[ "Pulls", "down", "all", "backendRouterIds", "that", "are", "available" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_capacity.py#L70-L98
softlayer/softlayer-python
SoftLayer/managers/vs_capacity.py
CapacityManager.create
def create(self, name, backend_router_id, flavor, instances, test=False): """Orders a Virtual_ReservedCapacityGroup :param string name: Name for the new reserved capacity :param int backend_router_id: This selects the pod. See create_options for a list :param string flavor: Capacity KeyName, see create_options for a list :param int instances: Number of guest this capacity can support :param bool test: If True, don't actually order, just test. """ # Since orderManger needs a DC id, just send in 0, the API will ignore it args = (self.capacity_package, 0, [flavor]) extras = {"backendRouterId": backend_router_id, "name": name} kwargs = { 'extras': extras, 'quantity': instances, 'complex_type': 'SoftLayer_Container_Product_Order_Virtual_ReservedCapacity', 'hourly': True } if test: receipt = self.ordering_manager.verify_order(*args, **kwargs) else: receipt = self.ordering_manager.place_order(*args, **kwargs) return receipt
python
def create(self, name, backend_router_id, flavor, instances, test=False): args = (self.capacity_package, 0, [flavor]) extras = {"backendRouterId": backend_router_id, "name": name} kwargs = { 'extras': extras, 'quantity': instances, 'complex_type': 'SoftLayer_Container_Product_Order_Virtual_ReservedCapacity', 'hourly': True } if test: receipt = self.ordering_manager.verify_order(*args, **kwargs) else: receipt = self.ordering_manager.place_order(*args, **kwargs) return receipt
[ "def", "create", "(", "self", ",", "name", ",", "backend_router_id", ",", "flavor", ",", "instances", ",", "test", "=", "False", ")", ":", "# Since orderManger needs a DC id, just send in 0, the API will ignore it", "args", "=", "(", "self", ".", "capacity_package", ",", "0", ",", "[", "flavor", "]", ")", "extras", "=", "{", "\"backendRouterId\"", ":", "backend_router_id", ",", "\"name\"", ":", "name", "}", "kwargs", "=", "{", "'extras'", ":", "extras", ",", "'quantity'", ":", "instances", ",", "'complex_type'", ":", "'SoftLayer_Container_Product_Order_Virtual_ReservedCapacity'", ",", "'hourly'", ":", "True", "}", "if", "test", ":", "receipt", "=", "self", ".", "ordering_manager", ".", "verify_order", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "receipt", "=", "self", ".", "ordering_manager", ".", "place_order", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "receipt" ]
Orders a Virtual_ReservedCapacityGroup :param string name: Name for the new reserved capacity :param int backend_router_id: This selects the pod. See create_options for a list :param string flavor: Capacity KeyName, see create_options for a list :param int instances: Number of guest this capacity can support :param bool test: If True, don't actually order, just test.
[ "Orders", "a", "Virtual_ReservedCapacityGroup" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_capacity.py#L100-L123
softlayer/softlayer-python
SoftLayer/managers/vs_capacity.py
CapacityManager.create_guest
def create_guest(self, capacity_id, test, guest_object): """Turns an empty Reserve Capacity into a real Virtual Guest :param int capacity_id: ID of the RESERVED_CAPACITY_GROUP to create this guest into :param bool test: True will use verifyOrder, False will use placeOrder :param dictionary guest_object: Below is the minimum info you need to send in guest_object = { 'domain': 'test.com', 'hostname': 'A1538172419', 'os_code': 'UBUNTU_LATEST_64', 'primary_disk': '25', } """ vs_manager = VSManager(self.client) mask = "mask[instances[id, billingItem[id, item[id,keyName]]], backendRouter[id, datacenter[name]]]" capacity = self.get_object(capacity_id, mask=mask) try: capacity_flavor = capacity['instances'][0]['billingItem']['item']['keyName'] flavor = _flavor_string(capacity_flavor, guest_object['primary_disk']) except KeyError: raise SoftLayer.SoftLayerError("Unable to find capacity Flavor.") guest_object['flavor'] = flavor guest_object['datacenter'] = capacity['backendRouter']['datacenter']['name'] # Reserved capacity only supports SAN as of 20181008 guest_object['local_disk'] = False template = vs_manager.verify_create_instance(**guest_object) template['reservedCapacityId'] = capacity_id if guest_object.get('ipv6'): ipv6_price = self.ordering_manager.get_price_id_list('PUBLIC_CLOUD_SERVER', ['1_IPV6_ADDRESS']) template['prices'].append({'id': ipv6_price[0]}) if test: result = self.client.call('Product_Order', 'verifyOrder', template) else: result = self.client.call('Product_Order', 'placeOrder', template) return result
python
def create_guest(self, capacity_id, test, guest_object): vs_manager = VSManager(self.client) mask = "mask[instances[id, billingItem[id, item[id,keyName]]], backendRouter[id, datacenter[name]]]" capacity = self.get_object(capacity_id, mask=mask) try: capacity_flavor = capacity['instances'][0]['billingItem']['item']['keyName'] flavor = _flavor_string(capacity_flavor, guest_object['primary_disk']) except KeyError: raise SoftLayer.SoftLayerError("Unable to find capacity Flavor.") guest_object['flavor'] = flavor guest_object['datacenter'] = capacity['backendRouter']['datacenter']['name'] guest_object['local_disk'] = False template = vs_manager.verify_create_instance(**guest_object) template['reservedCapacityId'] = capacity_id if guest_object.get('ipv6'): ipv6_price = self.ordering_manager.get_price_id_list('PUBLIC_CLOUD_SERVER', ['1_IPV6_ADDRESS']) template['prices'].append({'id': ipv6_price[0]}) if test: result = self.client.call('Product_Order', 'verifyOrder', template) else: result = self.client.call('Product_Order', 'placeOrder', template) return result
[ "def", "create_guest", "(", "self", ",", "capacity_id", ",", "test", ",", "guest_object", ")", ":", "vs_manager", "=", "VSManager", "(", "self", ".", "client", ")", "mask", "=", "\"mask[instances[id, billingItem[id, item[id,keyName]]], backendRouter[id, datacenter[name]]]\"", "capacity", "=", "self", ".", "get_object", "(", "capacity_id", ",", "mask", "=", "mask", ")", "try", ":", "capacity_flavor", "=", "capacity", "[", "'instances'", "]", "[", "0", "]", "[", "'billingItem'", "]", "[", "'item'", "]", "[", "'keyName'", "]", "flavor", "=", "_flavor_string", "(", "capacity_flavor", ",", "guest_object", "[", "'primary_disk'", "]", ")", "except", "KeyError", ":", "raise", "SoftLayer", ".", "SoftLayerError", "(", "\"Unable to find capacity Flavor.\"", ")", "guest_object", "[", "'flavor'", "]", "=", "flavor", "guest_object", "[", "'datacenter'", "]", "=", "capacity", "[", "'backendRouter'", "]", "[", "'datacenter'", "]", "[", "'name'", "]", "# Reserved capacity only supports SAN as of 20181008", "guest_object", "[", "'local_disk'", "]", "=", "False", "template", "=", "vs_manager", ".", "verify_create_instance", "(", "*", "*", "guest_object", ")", "template", "[", "'reservedCapacityId'", "]", "=", "capacity_id", "if", "guest_object", ".", "get", "(", "'ipv6'", ")", ":", "ipv6_price", "=", "self", ".", "ordering_manager", ".", "get_price_id_list", "(", "'PUBLIC_CLOUD_SERVER'", ",", "[", "'1_IPV6_ADDRESS'", "]", ")", "template", "[", "'prices'", "]", ".", "append", "(", "{", "'id'", ":", "ipv6_price", "[", "0", "]", "}", ")", "if", "test", ":", "result", "=", "self", ".", "client", ".", "call", "(", "'Product_Order'", ",", "'verifyOrder'", ",", "template", ")", "else", ":", "result", "=", "self", ".", "client", ".", "call", "(", "'Product_Order'", ",", "'placeOrder'", ",", "template", ")", "return", "result" ]
Turns an empty Reserve Capacity into a real Virtual Guest :param int capacity_id: ID of the RESERVED_CAPACITY_GROUP to create this guest into :param bool test: True will use verifyOrder, False will use placeOrder :param dictionary guest_object: Below is the minimum info you need to send in guest_object = { 'domain': 'test.com', 'hostname': 'A1538172419', 'os_code': 'UBUNTU_LATEST_64', 'primary_disk': '25', }
[ "Turns", "an", "empty", "Reserve", "Capacity", "into", "a", "real", "Virtual", "Guest" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs_capacity.py#L125-L165
softlayer/softlayer-python
SoftLayer/CLI/virt/capacity/list.py
cli
def cli(env): """List Reserved Capacity groups.""" manager = CapacityManager(env.client) result = manager.list() table = formatting.Table( ["ID", "Name", "Capacity", "Flavor", "Location", "Created"], title="Reserved Capacity" ) for r_c in result: occupied_string = "#" * int(r_c.get('occupiedInstanceCount', 0)) available_string = "-" * int(r_c.get('availableInstanceCount', 0)) try: flavor = r_c['instances'][0]['billingItem']['description'] # cost = float(r_c['instances'][0]['billingItem']['hourlyRecurringFee']) except KeyError: flavor = "Unknown Billing Item" location = r_c['backendRouter']['hostname'] capacity = "%s%s" % (occupied_string, available_string) table.add_row([r_c['id'], r_c['name'], capacity, flavor, location, r_c['createDate']]) env.fout(table)
python
def cli(env): manager = CapacityManager(env.client) result = manager.list() table = formatting.Table( ["ID", "Name", "Capacity", "Flavor", "Location", "Created"], title="Reserved Capacity" ) for r_c in result: occupied_string = " available_string = "-" * int(r_c.get('availableInstanceCount', 0)) try: flavor = r_c['instances'][0]['billingItem']['description'] except KeyError: flavor = "Unknown Billing Item" location = r_c['backendRouter']['hostname'] capacity = "%s%s" % (occupied_string, available_string) table.add_row([r_c['id'], r_c['name'], capacity, flavor, location, r_c['createDate']]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "manager", "=", "CapacityManager", "(", "env", ".", "client", ")", "result", "=", "manager", ".", "list", "(", ")", "table", "=", "formatting", ".", "Table", "(", "[", "\"ID\"", ",", "\"Name\"", ",", "\"Capacity\"", ",", "\"Flavor\"", ",", "\"Location\"", ",", "\"Created\"", "]", ",", "title", "=", "\"Reserved Capacity\"", ")", "for", "r_c", "in", "result", ":", "occupied_string", "=", "\"#\"", "*", "int", "(", "r_c", ".", "get", "(", "'occupiedInstanceCount'", ",", "0", ")", ")", "available_string", "=", "\"-\"", "*", "int", "(", "r_c", ".", "get", "(", "'availableInstanceCount'", ",", "0", ")", ")", "try", ":", "flavor", "=", "r_c", "[", "'instances'", "]", "[", "0", "]", "[", "'billingItem'", "]", "[", "'description'", "]", "# cost = float(r_c['instances'][0]['billingItem']['hourlyRecurringFee'])", "except", "KeyError", ":", "flavor", "=", "\"Unknown Billing Item\"", "location", "=", "r_c", "[", "'backendRouter'", "]", "[", "'hostname'", "]", "capacity", "=", "\"%s%s\"", "%", "(", "occupied_string", ",", "available_string", ")", "table", ".", "add_row", "(", "[", "r_c", "[", "'id'", "]", ",", "r_c", "[", "'name'", "]", ",", "capacity", ",", "flavor", ",", "location", ",", "r_c", "[", "'createDate'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List Reserved Capacity groups.
[ "List", "Reserved", "Capacity", "groups", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/capacity/list.py#L12-L32
softlayer/softlayer-python
SoftLayer/CLI/order/place_quote.py
cli
def cli(env, package_keyname, location, preset, name, send_email, complex_type, extras, order_items): """Place a quote. This CLI command is used for creating a quote of the specified package in the given location (denoted by a datacenter's long name). Orders made via the CLI can then be converted to be made programmatically by calling SoftLayer.OrderingManager.place_quote() with the same keynames. Packages for ordering can be retrieved from `slcli order package-list` Presets for ordering can be retrieved from `slcli order preset-list` (not all packages have presets) Items can be retrieved from `slcli order item-list`. In order to find required items for the order, use `slcli order category-list`, and then provide the --category option for each category code in `slcli order item-list`. Example:: # Place quote a VSI with 4 CPU, 16 GB RAM, 100 GB SAN disk, # Ubuntu 16.04, and 1 Gbps public & private uplink in dal13 slcli order place-quote --name "foobar" --send-email CLOUD_SERVER DALLAS13 \\ GUEST_CORES_4 \\ RAM_16_GB \\ REBOOT_REMOTE_CONSOLE \\ 1_GBPS_PUBLIC_PRIVATE_NETWORK_UPLINKS \\ BANDWIDTH_0_GB_2 \\ 1_IP_ADDRESS \\ GUEST_DISK_100_GB_SAN \\ OS_UBUNTU_16_04_LTS_XENIAL_XERUS_MINIMAL_64_BIT_FOR_VSI \\ MONITORING_HOST_PING \\ NOTIFICATION_EMAIL_AND_TICKET \\ AUTOMATED_NOTIFICATION \\ UNLIMITED_SSL_VPN_USERS_1_PPTP_VPN_USER_PER_ACCOUNT \\ NESSUS_VULNERABILITY_ASSESSMENT_REPORTING \\ --extras '{"virtualGuests": [{"hostname": "test", "domain": "softlayer.com"}]}' \\ --complex-type SoftLayer_Container_Product_Order_Virtual_Guest """ manager = ordering.OrderingManager(env.client) if extras: try: extras = json.loads(extras) except ValueError as err: raise exceptions.CLIAbort("There was an error when parsing the --extras value: {}".format(err)) args = (package_keyname, location, order_items) kwargs = {'preset_keyname': preset, 'extras': extras, 'quantity': 1, 'quote_name': name, 'send_email': send_email, 'complex_type': complex_type} order = manager.place_quote(*args, **kwargs) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', order['quote']['id']]) table.add_row(['name', order['quote']['name']]) table.add_row(['created', order['orderDate']]) table.add_row(['expires', order['quote']['expirationDate']]) table.add_row(['status', order['quote']['status']]) env.fout(table)
python
def cli(env, package_keyname, location, preset, name, send_email, complex_type, extras, order_items): manager = ordering.OrderingManager(env.client) if extras: try: extras = json.loads(extras) except ValueError as err: raise exceptions.CLIAbort("There was an error when parsing the --extras value: {}".format(err)) args = (package_keyname, location, order_items) kwargs = {'preset_keyname': preset, 'extras': extras, 'quantity': 1, 'quote_name': name, 'send_email': send_email, 'complex_type': complex_type} order = manager.place_quote(*args, **kwargs) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', order['quote']['id']]) table.add_row(['name', order['quote']['name']]) table.add_row(['created', order['orderDate']]) table.add_row(['expires', order['quote']['expirationDate']]) table.add_row(['status', order['quote']['status']]) env.fout(table)
[ "def", "cli", "(", "env", ",", "package_keyname", ",", "location", ",", "preset", ",", "name", ",", "send_email", ",", "complex_type", ",", "extras", ",", "order_items", ")", ":", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "if", "extras", ":", "try", ":", "extras", "=", "json", ".", "loads", "(", "extras", ")", "except", "ValueError", "as", "err", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"There was an error when parsing the --extras value: {}\"", ".", "format", "(", "err", ")", ")", "args", "=", "(", "package_keyname", ",", "location", ",", "order_items", ")", "kwargs", "=", "{", "'preset_keyname'", ":", "preset", ",", "'extras'", ":", "extras", ",", "'quantity'", ":", "1", ",", "'quote_name'", ":", "name", ",", "'send_email'", ":", "send_email", ",", "'complex_type'", ":", "complex_type", "}", "order", "=", "manager", ".", "place_quote", "(", "*", "args", ",", "*", "*", "kwargs", ")", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "table", ".", "align", "[", "'name'", "]", "=", "'r'", "table", ".", "align", "[", "'value'", "]", "=", "'l'", "table", ".", "add_row", "(", "[", "'id'", ",", "order", "[", "'quote'", "]", "[", "'id'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'name'", ",", "order", "[", "'quote'", "]", "[", "'name'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'created'", ",", "order", "[", "'orderDate'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'expires'", ",", "order", "[", "'quote'", "]", "[", "'expirationDate'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'status'", ",", "order", "[", "'quote'", "]", "[", "'status'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Place a quote. This CLI command is used for creating a quote of the specified package in the given location (denoted by a datacenter's long name). Orders made via the CLI can then be converted to be made programmatically by calling SoftLayer.OrderingManager.place_quote() with the same keynames. Packages for ordering can be retrieved from `slcli order package-list` Presets for ordering can be retrieved from `slcli order preset-list` (not all packages have presets) Items can be retrieved from `slcli order item-list`. In order to find required items for the order, use `slcli order category-list`, and then provide the --category option for each category code in `slcli order item-list`. Example:: # Place quote a VSI with 4 CPU, 16 GB RAM, 100 GB SAN disk, # Ubuntu 16.04, and 1 Gbps public & private uplink in dal13 slcli order place-quote --name "foobar" --send-email CLOUD_SERVER DALLAS13 \\ GUEST_CORES_4 \\ RAM_16_GB \\ REBOOT_REMOTE_CONSOLE \\ 1_GBPS_PUBLIC_PRIVATE_NETWORK_UPLINKS \\ BANDWIDTH_0_GB_2 \\ 1_IP_ADDRESS \\ GUEST_DISK_100_GB_SAN \\ OS_UBUNTU_16_04_LTS_XENIAL_XERUS_MINIMAL_64_BIT_FOR_VSI \\ MONITORING_HOST_PING \\ NOTIFICATION_EMAIL_AND_TICKET \\ AUTOMATED_NOTIFICATION \\ UNLIMITED_SSL_VPN_USERS_1_PPTP_VPN_USER_PER_ACCOUNT \\ NESSUS_VULNERABILITY_ASSESSMENT_REPORTING \\ --extras '{"virtualGuests": [{"hostname": "test", "domain": "softlayer.com"}]}' \\ --complex-type SoftLayer_Container_Product_Order_Virtual_Guest
[ "Place", "a", "quote", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/place_quote.py#L30-L96
softlayer/softlayer-python
SoftLayer/CLI/file/snapshot/create.py
cli
def cli(env, volume_id, notes): """Creates a snapshot on a given volume""" file_storage_manager = SoftLayer.FileStorageManager(env.client) snapshot = file_storage_manager.create_snapshot(volume_id, notes=notes) if 'id' in snapshot: click.echo('New snapshot created with id: %s' % snapshot['id']) else: click.echo('Error occurred while creating snapshot.\n' 'Ensure volume is not failed over or in another ' 'state which prevents taking snapshots.')
python
def cli(env, volume_id, notes): file_storage_manager = SoftLayer.FileStorageManager(env.client) snapshot = file_storage_manager.create_snapshot(volume_id, notes=notes) if 'id' in snapshot: click.echo('New snapshot created with id: %s' % snapshot['id']) else: click.echo('Error occurred while creating snapshot.\n' 'Ensure volume is not failed over or in another ' 'state which prevents taking snapshots.')
[ "def", "cli", "(", "env", ",", "volume_id", ",", "notes", ")", ":", "file_storage_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "snapshot", "=", "file_storage_manager", ".", "create_snapshot", "(", "volume_id", ",", "notes", "=", "notes", ")", "if", "'id'", "in", "snapshot", ":", "click", ".", "echo", "(", "'New snapshot created with id: %s'", "%", "snapshot", "[", "'id'", "]", ")", "else", ":", "click", ".", "echo", "(", "'Error occurred while creating snapshot.\\n'", "'Ensure volume is not failed over or in another '", "'state which prevents taking snapshots.'", ")" ]
Creates a snapshot on a given volume
[ "Creates", "a", "snapshot", "on", "a", "given", "volume" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/create.py#L14-L24
softlayer/softlayer-python
SoftLayer/CLI/order/quote_list.py
cli
def cli(env): """List all active quotes on an account""" table = formatting.Table([ 'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id' ]) table.align['Name'] = 'l' table.align['Package Name'] = 'r' table.align['Package Id'] = 'l' manager = ordering.OrderingManager(env.client) items = manager.get_quotes() for item in items: package = item['order']['items'][0]['package'] table.add_row([ item.get('id'), item.get('name'), clean_time(item.get('createDate')), clean_time(item.get('modifyDate')), item.get('status'), package.get('keyName'), package.get('id') ]) env.fout(table)
python
def cli(env): table = formatting.Table([ 'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id' ]) table.align['Name'] = 'l' table.align['Package Name'] = 'r' table.align['Package Id'] = 'l' manager = ordering.OrderingManager(env.client) items = manager.get_quotes() for item in items: package = item['order']['items'][0]['package'] table.add_row([ item.get('id'), item.get('name'), clean_time(item.get('createDate')), clean_time(item.get('modifyDate')), item.get('status'), package.get('keyName'), package.get('id') ]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Id'", ",", "'Name'", ",", "'Created'", ",", "'Expiration'", ",", "'Status'", ",", "'Package Name'", ",", "'Package Id'", "]", ")", "table", ".", "align", "[", "'Name'", "]", "=", "'l'", "table", ".", "align", "[", "'Package Name'", "]", "=", "'r'", "table", ".", "align", "[", "'Package Id'", "]", "=", "'l'", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "items", "=", "manager", ".", "get_quotes", "(", ")", "for", "item", "in", "items", ":", "package", "=", "item", "[", "'order'", "]", "[", "'items'", "]", "[", "0", "]", "[", "'package'", "]", "table", ".", "add_row", "(", "[", "item", ".", "get", "(", "'id'", ")", ",", "item", ".", "get", "(", "'name'", ")", ",", "clean_time", "(", "item", ".", "get", "(", "'createDate'", ")", ")", ",", "clean_time", "(", "item", ".", "get", "(", "'modifyDate'", ")", ")", ",", "item", ".", "get", "(", "'status'", ")", ",", "package", ".", "get", "(", "'keyName'", ")", ",", "package", ".", "get", "(", "'id'", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List all active quotes on an account
[ "List", "all", "active", "quotes", "on", "an", "account" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/quote_list.py#L13-L36
softlayer/softlayer-python
SoftLayer/CLI/image/delete.py
cli
def cli(env, identifier): """Delete an image.""" image_mgr = SoftLayer.ImageManager(env.client) image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image') image_mgr.delete_image(image_id)
python
def cli(env, identifier): image_mgr = SoftLayer.ImageManager(env.client) image_id = helpers.resolve_id(image_mgr.resolve_ids, identifier, 'image') image_mgr.delete_image(image_id)
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "image_mgr", "=", "SoftLayer", ".", "ImageManager", "(", "env", ".", "client", ")", "image_id", "=", "helpers", ".", "resolve_id", "(", "image_mgr", ".", "resolve_ids", ",", "identifier", ",", "'image'", ")", "image_mgr", ".", "delete_image", "(", "image_id", ")" ]
Delete an image.
[ "Delete", "an", "image", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/image/delete.py#L14-L20
softlayer/softlayer-python
SoftLayer/CLI/file/snapshot/delete.py
cli
def cli(env, snapshot_id): """Deletes a snapshot on a given volume""" file_storage_manager = SoftLayer.FileStorageManager(env.client) deleted = file_storage_manager.delete_snapshot(snapshot_id) if deleted: click.echo('Snapshot %s deleted' % snapshot_id)
python
def cli(env, snapshot_id): file_storage_manager = SoftLayer.FileStorageManager(env.client) deleted = file_storage_manager.delete_snapshot(snapshot_id) if deleted: click.echo('Snapshot %s deleted' % snapshot_id)
[ "def", "cli", "(", "env", ",", "snapshot_id", ")", ":", "file_storage_manager", "=", "SoftLayer", ".", "FileStorageManager", "(", "env", ".", "client", ")", "deleted", "=", "file_storage_manager", ".", "delete_snapshot", "(", "snapshot_id", ")", "if", "deleted", ":", "click", ".", "echo", "(", "'Snapshot %s deleted'", "%", "snapshot_id", ")" ]
Deletes a snapshot on a given volume
[ "Deletes", "a", "snapshot", "on", "a", "given", "volume" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/file/snapshot/delete.py#L12-L18
softlayer/softlayer-python
SoftLayer/CLI/loadbal/service_add.py
cli
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address): """Adds a new load balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, group_id = loadbal.parse_id(identifier) # check if the IP is valid ip_address_id = None if ip_address: ip_service = env.client['Network_Subnet_IpAddress'] ip_record = ip_service.getByIpAddress(ip_address) if len(ip_record) > 0: ip_address_id = ip_record['id'] mgr.add_service(loadbal_id, group_id, ip_address_id=ip_address_id, enabled=enabled, port=port, weight=weight, hc_type=healthcheck_type) env.fout('Load balancer service is being added!')
python
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address): mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, group_id = loadbal.parse_id(identifier) ip_address_id = None if ip_address: ip_service = env.client['Network_Subnet_IpAddress'] ip_record = ip_service.getByIpAddress(ip_address) if len(ip_record) > 0: ip_address_id = ip_record['id'] mgr.add_service(loadbal_id, group_id, ip_address_id=ip_address_id, enabled=enabled, port=port, weight=weight, hc_type=healthcheck_type) env.fout('Load balancer service is being added!')
[ "def", "cli", "(", "env", ",", "identifier", ",", "enabled", ",", "port", ",", "weight", ",", "healthcheck_type", ",", "ip_address", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "loadbal_id", ",", "group_id", "=", "loadbal", ".", "parse_id", "(", "identifier", ")", "# check if the IP is valid", "ip_address_id", "=", "None", "if", "ip_address", ":", "ip_service", "=", "env", ".", "client", "[", "'Network_Subnet_IpAddress'", "]", "ip_record", "=", "ip_service", ".", "getByIpAddress", "(", "ip_address", ")", "if", "len", "(", "ip_record", ")", ">", "0", ":", "ip_address_id", "=", "ip_record", "[", "'id'", "]", "mgr", ".", "add_service", "(", "loadbal_id", ",", "group_id", ",", "ip_address_id", "=", "ip_address_id", ",", "enabled", "=", "enabled", ",", "port", "=", "port", ",", "weight", "=", "weight", ",", "hc_type", "=", "healthcheck_type", ")", "env", ".", "fout", "(", "'Load balancer service is being added!'", ")" ]
Adds a new load balancer service.
[ "Adds", "a", "new", "load", "balancer", "service", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/service_add.py#L31-L53
softlayer/softlayer-python
SoftLayer/shell/core.py
cli
def cli(ctx, env): """Enters a shell for slcli.""" # Set up the environment env = copy.deepcopy(env) env.load_modules_from_python(routes.ALL_ROUTES) env.aliases.update(routes.ALL_ALIASES) env.vars['global_args'] = ctx.parent.params env.vars['is_shell'] = True env.vars['last_exit_code'] = 0 # Set up prompt_toolkit settings app_path = click.get_app_dir('softlayer_shell') if not os.path.exists(app_path): os.makedirs(app_path) complete = completer.ShellCompleter(core.cli) while True: try: line = p_shortcuts.prompt( completer=complete, complete_while_typing=True, auto_suggest=p_auto_suggest.AutoSuggestFromHistory(), ) # Parse arguments try: args = shlex.split(line) except ValueError as ex: print("Invalid Command: %s" % ex) continue if not args: continue # Run Command try: # Reset client so that the client gets refreshed env.client = None core.main(args=list(get_env_args(env)) + args, obj=env, prog_name="", reraise_exceptions=True) except SystemExit as ex: env.vars['last_exit_code'] = ex.code except EOFError: return except ShellExit: return except Exception as ex: env.vars['last_exit_code'] = 1 traceback.print_exc(file=sys.stderr) except KeyboardInterrupt: env.vars['last_exit_code'] = 130
python
def cli(ctx, env): env = copy.deepcopy(env) env.load_modules_from_python(routes.ALL_ROUTES) env.aliases.update(routes.ALL_ALIASES) env.vars['global_args'] = ctx.parent.params env.vars['is_shell'] = True env.vars['last_exit_code'] = 0 app_path = click.get_app_dir('softlayer_shell') if not os.path.exists(app_path): os.makedirs(app_path) complete = completer.ShellCompleter(core.cli) while True: try: line = p_shortcuts.prompt( completer=complete, complete_while_typing=True, auto_suggest=p_auto_suggest.AutoSuggestFromHistory(), ) try: args = shlex.split(line) except ValueError as ex: print("Invalid Command: %s" % ex) continue if not args: continue try: env.client = None core.main(args=list(get_env_args(env)) + args, obj=env, prog_name="", reraise_exceptions=True) except SystemExit as ex: env.vars['last_exit_code'] = ex.code except EOFError: return except ShellExit: return except Exception as ex: env.vars['last_exit_code'] = 1 traceback.print_exc(file=sys.stderr) except KeyboardInterrupt: env.vars['last_exit_code'] = 130
[ "def", "cli", "(", "ctx", ",", "env", ")", ":", "# Set up the environment", "env", "=", "copy", ".", "deepcopy", "(", "env", ")", "env", ".", "load_modules_from_python", "(", "routes", ".", "ALL_ROUTES", ")", "env", ".", "aliases", ".", "update", "(", "routes", ".", "ALL_ALIASES", ")", "env", ".", "vars", "[", "'global_args'", "]", "=", "ctx", ".", "parent", ".", "params", "env", ".", "vars", "[", "'is_shell'", "]", "=", "True", "env", ".", "vars", "[", "'last_exit_code'", "]", "=", "0", "# Set up prompt_toolkit settings", "app_path", "=", "click", ".", "get_app_dir", "(", "'softlayer_shell'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "app_path", ")", ":", "os", ".", "makedirs", "(", "app_path", ")", "complete", "=", "completer", ".", "ShellCompleter", "(", "core", ".", "cli", ")", "while", "True", ":", "try", ":", "line", "=", "p_shortcuts", ".", "prompt", "(", "completer", "=", "complete", ",", "complete_while_typing", "=", "True", ",", "auto_suggest", "=", "p_auto_suggest", ".", "AutoSuggestFromHistory", "(", ")", ",", ")", "# Parse arguments", "try", ":", "args", "=", "shlex", ".", "split", "(", "line", ")", "except", "ValueError", "as", "ex", ":", "print", "(", "\"Invalid Command: %s\"", "%", "ex", ")", "continue", "if", "not", "args", ":", "continue", "# Run Command", "try", ":", "# Reset client so that the client gets refreshed", "env", ".", "client", "=", "None", "core", ".", "main", "(", "args", "=", "list", "(", "get_env_args", "(", "env", ")", ")", "+", "args", ",", "obj", "=", "env", ",", "prog_name", "=", "\"\"", ",", "reraise_exceptions", "=", "True", ")", "except", "SystemExit", "as", "ex", ":", "env", ".", "vars", "[", "'last_exit_code'", "]", "=", "ex", ".", "code", "except", "EOFError", ":", "return", "except", "ShellExit", ":", "return", "except", "Exception", "as", "ex", ":", "env", ".", "vars", "[", "'last_exit_code'", "]", "=", "1", "traceback", ".", "print_exc", "(", "file", "=", "sys", ".", "stderr", ")", "except", "KeyboardInterrupt", ":", "env", ".", "vars", "[", "'last_exit_code'", "]", "=", "130" ]
Enters a shell for slcli.
[ "Enters", "a", "shell", "for", "slcli", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/shell/core.py#L34-L88
softlayer/softlayer-python
SoftLayer/shell/core.py
get_env_args
def get_env_args(env): """Yield options to inject into the slcli command from the environment.""" for arg, val in env.vars.get('global_args', {}).items(): if val is True: yield '--%s' % arg elif isinstance(val, int): for _ in range(val): yield '--%s' % arg elif val is None: continue else: yield '--%s=%s' % (arg, val)
python
def get_env_args(env): for arg, val in env.vars.get('global_args', {}).items(): if val is True: yield '--%s' % arg elif isinstance(val, int): for _ in range(val): yield '--%s' % arg elif val is None: continue else: yield '--%s=%s' % (arg, val)
[ "def", "get_env_args", "(", "env", ")", ":", "for", "arg", ",", "val", "in", "env", ".", "vars", ".", "get", "(", "'global_args'", ",", "{", "}", ")", ".", "items", "(", ")", ":", "if", "val", "is", "True", ":", "yield", "'--%s'", "%", "arg", "elif", "isinstance", "(", "val", ",", "int", ")", ":", "for", "_", "in", "range", "(", "val", ")", ":", "yield", "'--%s'", "%", "arg", "elif", "val", "is", "None", ":", "continue", "else", ":", "yield", "'--%s=%s'", "%", "(", "arg", ",", "val", ")" ]
Yield options to inject into the slcli command from the environment.
[ "Yield", "options", "to", "inject", "into", "the", "slcli", "command", "from", "the", "environment", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/shell/core.py#L91-L102
softlayer/softlayer-python
SoftLayer/CLI/virt/placementgroup/delete.py
cli
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')
python
def cli(env, identifier, purge): 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", ",", "purge", ")", ":", "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'", ")" ]
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
[ "Delete", "a", "placement", "group", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/virt/placementgroup/delete.py#L19-L49
softlayer/softlayer-python
SoftLayer/CLI/loadbal/routing_types.py
cli
def cli(env): """List routing types.""" mgr = SoftLayer.LoadBalancerManager(env.client) routing_types = mgr.get_routing_types() table = formatting.KeyValueTable(['ID', 'Name']) table.align['ID'] = 'l' table.align['Name'] = 'l' table.sortby = 'ID' for routing_type in routing_types: table.add_row([routing_type['id'], routing_type['name']]) env.fout(table)
python
def cli(env): mgr = SoftLayer.LoadBalancerManager(env.client) routing_types = mgr.get_routing_types() table = formatting.KeyValueTable(['ID', 'Name']) table.align['ID'] = 'l' table.align['Name'] = 'l' table.sortby = 'ID' for routing_type in routing_types: table.add_row([routing_type['id'], routing_type['name']]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "routing_types", "=", "mgr", ".", "get_routing_types", "(", ")", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'ID'", ",", "'Name'", "]", ")", "table", ".", "align", "[", "'ID'", "]", "=", "'l'", "table", ".", "align", "[", "'Name'", "]", "=", "'l'", "table", ".", "sortby", "=", "'ID'", "for", "routing_type", "in", "routing_types", ":", "table", ".", "add_row", "(", "[", "routing_type", "[", "'id'", "]", ",", "routing_type", "[", "'name'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List routing types.
[ "List", "routing", "types", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/routing_types.py#L13-L24
softlayer/softlayer-python
SoftLayer/CLI/vpn/ipsec/translation/update.py
cli
def cli(env, context_id, translation_id, static_ip, remote_ip, note): """Update an address translation for an IPSEC tunnel context. A separate configuration request should be made to realize changes on network devices. """ manager = SoftLayer.IPSECManager(env.client) succeeded = manager.update_translation(context_id, translation_id, static_ip=static_ip, remote_ip=remote_ip, notes=note) if succeeded: env.out('Updated translation #{}'.format(translation_id)) else: raise CLIHalt('Failed to update translation #{}'.format(translation_id))
python
def cli(env, context_id, translation_id, static_ip, remote_ip, note): manager = SoftLayer.IPSECManager(env.client) succeeded = manager.update_translation(context_id, translation_id, static_ip=static_ip, remote_ip=remote_ip, notes=note) if succeeded: env.out('Updated translation else: raise CLIHalt('Failed to update translation
[ "def", "cli", "(", "env", ",", "context_id", ",", "translation_id", ",", "static_ip", ",", "remote_ip", ",", "note", ")", ":", "manager", "=", "SoftLayer", ".", "IPSECManager", "(", "env", ".", "client", ")", "succeeded", "=", "manager", ".", "update_translation", "(", "context_id", ",", "translation_id", ",", "static_ip", "=", "static_ip", ",", "remote_ip", "=", "remote_ip", ",", "notes", "=", "note", ")", "if", "succeeded", ":", "env", ".", "out", "(", "'Updated translation #{}'", ".", "format", "(", "translation_id", ")", ")", "else", ":", "raise", "CLIHalt", "(", "'Failed to update translation #{}'", ".", "format", "(", "translation_id", ")", ")" ]
Update an address translation for an IPSEC tunnel context. A separate configuration request should be made to realize changes on network devices.
[ "Update", "an", "address", "translation", "for", "an", "IPSEC", "tunnel", "context", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vpn/ipsec/translation/update.py#L31-L46
softlayer/softlayer-python
SoftLayer/CLI/account/invoice_detail.py
cli
def cli(env, identifier, details): """Invoices and all that mess""" manager = AccountManager(env.client) top_items = manager.get_billing_items(identifier) title = "Invoice %s" % identifier table = formatting.Table(["Item Id", "Category", "Description", "Single", "Monthly", "Create Date", "Location"], title=title) table.align['category'] = 'l' table.align['description'] = 'l' for item in top_items: fqdn = "%s.%s" % (item.get('hostName', ''), item.get('domainName', '')) # category id=2046, ram_usage doesn't have a name... category = utils.lookup(item, 'category', 'name') or item.get('categoryCode') description = nice_string(item.get('description')) if fqdn != '.': description = "%s (%s)" % (item.get('description'), fqdn) table.add_row([ item.get('id'), category, nice_string(description), "$%.2f" % float(item.get('oneTimeAfterTaxAmount')), "$%.2f" % float(item.get('recurringAfterTaxAmount')), utils.clean_time(item.get('createDate'), out_format="%Y-%m-%d"), utils.lookup(item, 'location', 'name') ]) if details: for child in item.get('children', []): table.add_row([ '>>>', utils.lookup(child, 'category', 'name'), nice_string(child.get('description')), "$%.2f" % float(child.get('oneTimeAfterTaxAmount')), "$%.2f" % float(child.get('recurringAfterTaxAmount')), '---', '---' ]) env.fout(table)
python
def cli(env, identifier, details): manager = AccountManager(env.client) top_items = manager.get_billing_items(identifier) title = "Invoice %s" % identifier table = formatting.Table(["Item Id", "Category", "Description", "Single", "Monthly", "Create Date", "Location"], title=title) table.align['category'] = 'l' table.align['description'] = 'l' for item in top_items: fqdn = "%s.%s" % (item.get('hostName', ''), item.get('domainName', '')) category = utils.lookup(item, 'category', 'name') or item.get('categoryCode') description = nice_string(item.get('description')) if fqdn != '.': description = "%s (%s)" % (item.get('description'), fqdn) table.add_row([ item.get('id'), category, nice_string(description), "$%.2f" % float(item.get('oneTimeAfterTaxAmount')), "$%.2f" % float(item.get('recurringAfterTaxAmount')), utils.clean_time(item.get('createDate'), out_format="%Y-%m-%d"), utils.lookup(item, 'location', 'name') ]) if details: for child in item.get('children', []): table.add_row([ '>>>', utils.lookup(child, 'category', 'name'), nice_string(child.get('description')), "$%.2f" % float(child.get('oneTimeAfterTaxAmount')), "$%.2f" % float(child.get('recurringAfterTaxAmount')), '---', '---' ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "identifier", ",", "details", ")", ":", "manager", "=", "AccountManager", "(", "env", ".", "client", ")", "top_items", "=", "manager", ".", "get_billing_items", "(", "identifier", ")", "title", "=", "\"Invoice %s\"", "%", "identifier", "table", "=", "formatting", ".", "Table", "(", "[", "\"Item Id\"", ",", "\"Category\"", ",", "\"Description\"", ",", "\"Single\"", ",", "\"Monthly\"", ",", "\"Create Date\"", ",", "\"Location\"", "]", ",", "title", "=", "title", ")", "table", ".", "align", "[", "'category'", "]", "=", "'l'", "table", ".", "align", "[", "'description'", "]", "=", "'l'", "for", "item", "in", "top_items", ":", "fqdn", "=", "\"%s.%s\"", "%", "(", "item", ".", "get", "(", "'hostName'", ",", "''", ")", ",", "item", ".", "get", "(", "'domainName'", ",", "''", ")", ")", "# category id=2046, ram_usage doesn't have a name...", "category", "=", "utils", ".", "lookup", "(", "item", ",", "'category'", ",", "'name'", ")", "or", "item", ".", "get", "(", "'categoryCode'", ")", "description", "=", "nice_string", "(", "item", ".", "get", "(", "'description'", ")", ")", "if", "fqdn", "!=", "'.'", ":", "description", "=", "\"%s (%s)\"", "%", "(", "item", ".", "get", "(", "'description'", ")", ",", "fqdn", ")", "table", ".", "add_row", "(", "[", "item", ".", "get", "(", "'id'", ")", ",", "category", ",", "nice_string", "(", "description", ")", ",", "\"$%.2f\"", "%", "float", "(", "item", ".", "get", "(", "'oneTimeAfterTaxAmount'", ")", ")", ",", "\"$%.2f\"", "%", "float", "(", "item", ".", "get", "(", "'recurringAfterTaxAmount'", ")", ")", ",", "utils", ".", "clean_time", "(", "item", ".", "get", "(", "'createDate'", ")", ",", "out_format", "=", "\"%Y-%m-%d\"", ")", ",", "utils", ".", "lookup", "(", "item", ",", "'location'", ",", "'name'", ")", "]", ")", "if", "details", ":", "for", "child", "in", "item", ".", "get", "(", "'children'", ",", "[", "]", ")", ":", "table", ".", "add_row", "(", "[", "'>>>'", ",", "utils", ".", "lookup", "(", "child", ",", "'category'", ",", "'name'", ")", ",", "nice_string", "(", "child", ".", "get", "(", "'description'", ")", ")", ",", "\"$%.2f\"", "%", "float", "(", "child", ".", "get", "(", "'oneTimeAfterTaxAmount'", ")", ")", ",", "\"$%.2f\"", "%", "float", "(", "child", ".", "get", "(", "'recurringAfterTaxAmount'", ")", ")", ",", "'---'", ",", "'---'", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Invoices and all that mess
[ "Invoices", "and", "all", "that", "mess" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/invoice_detail.py#L17-L56
softlayer/softlayer-python
SoftLayer/shell/cmd_help.py
cli
def cli(ctx, env): """Print shell help text.""" env.out("Welcome to the SoftLayer shell.") env.out("") formatter = formatting.HelpFormatter() commands = [] shell_commands = [] for name in cli_core.cli.list_commands(ctx): command = cli_core.cli.get_command(ctx, name) if command.short_help is None: command.short_help = command.help details = (name, command.short_help) if name in dict(routes.ALL_ROUTES): shell_commands.append(details) else: commands.append(details) with formatter.section('Shell Commands'): formatter.write_dl(shell_commands) with formatter.section('Commands'): formatter.write_dl(commands) for line in formatter.buffer: env.out(line, newline=False)
python
def cli(ctx, env): env.out("Welcome to the SoftLayer shell.") env.out("") formatter = formatting.HelpFormatter() commands = [] shell_commands = [] for name in cli_core.cli.list_commands(ctx): command = cli_core.cli.get_command(ctx, name) if command.short_help is None: command.short_help = command.help details = (name, command.short_help) if name in dict(routes.ALL_ROUTES): shell_commands.append(details) else: commands.append(details) with formatter.section('Shell Commands'): formatter.write_dl(shell_commands) with formatter.section('Commands'): formatter.write_dl(commands) for line in formatter.buffer: env.out(line, newline=False)
[ "def", "cli", "(", "ctx", ",", "env", ")", ":", "env", ".", "out", "(", "\"Welcome to the SoftLayer shell.\"", ")", "env", ".", "out", "(", "\"\"", ")", "formatter", "=", "formatting", ".", "HelpFormatter", "(", ")", "commands", "=", "[", "]", "shell_commands", "=", "[", "]", "for", "name", "in", "cli_core", ".", "cli", ".", "list_commands", "(", "ctx", ")", ":", "command", "=", "cli_core", ".", "cli", ".", "get_command", "(", "ctx", ",", "name", ")", "if", "command", ".", "short_help", "is", "None", ":", "command", ".", "short_help", "=", "command", ".", "help", "details", "=", "(", "name", ",", "command", ".", "short_help", ")", "if", "name", "in", "dict", "(", "routes", ".", "ALL_ROUTES", ")", ":", "shell_commands", ".", "append", "(", "details", ")", "else", ":", "commands", ".", "append", "(", "details", ")", "with", "formatter", ".", "section", "(", "'Shell Commands'", ")", ":", "formatter", ".", "write_dl", "(", "shell_commands", ")", "with", "formatter", ".", "section", "(", "'Commands'", ")", ":", "formatter", ".", "write_dl", "(", "commands", ")", "for", "line", "in", "formatter", ".", "buffer", ":", "env", ".", "out", "(", "line", ",", "newline", "=", "False", ")" ]
Print shell help text.
[ "Print", "shell", "help", "text", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/shell/cmd_help.py#L15-L40
softlayer/softlayer-python
SoftLayer/CLI/hardware/reload.py
cli
def cli(env, identifier, postinstall, key): """Reload operating system on a server.""" hardware = SoftLayer.HardwareManager(env.client) hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, 'hardware') key_list = [] if key: for single_key in key: resolver = SoftLayer.SshKeyManager(env.client).resolve_ids key_id = helpers.resolve_id(resolver, single_key, 'SshKey') key_list.append(key_id) if not (env.skip_confirmations or formatting.no_going_back(hardware_id)): raise exceptions.CLIAbort('Aborted') hardware.reload(hardware_id, postinstall, key_list)
python
def cli(env, identifier, postinstall, key): hardware = SoftLayer.HardwareManager(env.client) hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, 'hardware') key_list = [] if key: for single_key in key: resolver = SoftLayer.SshKeyManager(env.client).resolve_ids key_id = helpers.resolve_id(resolver, single_key, 'SshKey') key_list.append(key_id) if not (env.skip_confirmations or formatting.no_going_back(hardware_id)): raise exceptions.CLIAbort('Aborted') hardware.reload(hardware_id, postinstall, key_list)
[ "def", "cli", "(", "env", ",", "identifier", ",", "postinstall", ",", "key", ")", ":", "hardware", "=", "SoftLayer", ".", "HardwareManager", "(", "env", ".", "client", ")", "hardware_id", "=", "helpers", ".", "resolve_id", "(", "hardware", ".", "resolve_ids", ",", "identifier", ",", "'hardware'", ")", "key_list", "=", "[", "]", "if", "key", ":", "for", "single_key", "in", "key", ":", "resolver", "=", "SoftLayer", ".", "SshKeyManager", "(", "env", ".", "client", ")", ".", "resolve_ids", "key_id", "=", "helpers", ".", "resolve_id", "(", "resolver", ",", "single_key", ",", "'SshKey'", ")", "key_list", ".", "append", "(", "key_id", ")", "if", "not", "(", "env", ".", "skip_confirmations", "or", "formatting", ".", "no_going_back", "(", "hardware_id", ")", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'Aborted'", ")", "hardware", ".", "reload", "(", "hardware_id", ",", "postinstall", ",", "key_list", ")" ]
Reload operating system on a server.
[ "Reload", "operating", "system", "on", "a", "server", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/hardware/reload.py#L20-L36
softlayer/softlayer-python
SoftLayer/CLI/loadbal/service_edit.py
cli
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address): """Edit the properties of a service group.""" mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, service_id = loadbal.parse_id(identifier) # check if any input is provided if ((not any([ip_address, weight, port, healthcheck_type])) and enabled is None): raise exceptions.CLIAbort( 'At least one property is required to be changed!') # check if the IP is valid ip_address_id = None if ip_address: ip_service = env.client['Network_Subnet_IpAddress'] ip_record = ip_service.getByIpAddress(ip_address) ip_address_id = ip_record['id'] mgr.edit_service(loadbal_id, service_id, ip_address_id=ip_address_id, enabled=enabled, port=port, weight=weight, hc_type=healthcheck_type) env.fout('Load balancer service %s is being modified!' % identifier)
python
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address): mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, service_id = loadbal.parse_id(identifier) if ((not any([ip_address, weight, port, healthcheck_type])) and enabled is None): raise exceptions.CLIAbort( 'At least one property is required to be changed!') ip_address_id = None if ip_address: ip_service = env.client['Network_Subnet_IpAddress'] ip_record = ip_service.getByIpAddress(ip_address) ip_address_id = ip_record['id'] mgr.edit_service(loadbal_id, service_id, ip_address_id=ip_address_id, enabled=enabled, port=port, weight=weight, hc_type=healthcheck_type) env.fout('Load balancer service %s is being modified!' % identifier)
[ "def", "cli", "(", "env", ",", "identifier", ",", "enabled", ",", "port", ",", "weight", ",", "healthcheck_type", ",", "ip_address", ")", ":", "mgr", "=", "SoftLayer", ".", "LoadBalancerManager", "(", "env", ".", "client", ")", "loadbal_id", ",", "service_id", "=", "loadbal", ".", "parse_id", "(", "identifier", ")", "# check if any input is provided", "if", "(", "(", "not", "any", "(", "[", "ip_address", ",", "weight", ",", "port", ",", "healthcheck_type", "]", ")", ")", "and", "enabled", "is", "None", ")", ":", "raise", "exceptions", ".", "CLIAbort", "(", "'At least one property is required to be changed!'", ")", "# check if the IP is valid", "ip_address_id", "=", "None", "if", "ip_address", ":", "ip_service", "=", "env", ".", "client", "[", "'Network_Subnet_IpAddress'", "]", "ip_record", "=", "ip_service", ".", "getByIpAddress", "(", "ip_address", ")", "ip_address_id", "=", "ip_record", "[", "'id'", "]", "mgr", ".", "edit_service", "(", "loadbal_id", ",", "service_id", ",", "ip_address_id", "=", "ip_address_id", ",", "enabled", "=", "enabled", ",", "port", "=", "port", ",", "weight", "=", "weight", ",", "hc_type", "=", "healthcheck_type", ")", "env", ".", "fout", "(", "'Load balancer service %s is being modified!'", "%", "identifier", ")" ]
Edit the properties of a service group.
[ "Edit", "the", "properties", "of", "a", "service", "group", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/loadbal/service_edit.py#L25-L52
softlayer/softlayer-python
SoftLayer/CLI/subnet/list.py
cli
def cli(env, sortby, datacenter, identifier, subnet_type, network_space, ipv4, ipv6): """List subnets.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table([ 'id', 'identifier', 'type', 'network_space', 'datacenter', 'vlan_id', 'IPs', 'hardware', 'vs', ]) table.sortby = sortby version = 0 if ipv4: version = 4 elif ipv6: version = 6 subnets = mgr.list_subnets( datacenter=datacenter, version=version, identifier=identifier, subnet_type=subnet_type, network_space=network_space, ) for subnet in subnets: table.add_row([ subnet['id'], '%s/%s' % (subnet['networkIdentifier'], str(subnet['cidr'])), subnet.get('subnetType', formatting.blank()), utils.lookup(subnet, 'networkVlan', 'networkSpace') or formatting.blank(), utils.lookup(subnet, 'datacenter', 'name',) or formatting.blank(), subnet['networkVlanId'], subnet['ipAddressCount'], len(subnet['hardware']), len(subnet['virtualGuests']), ]) env.fout(table)
python
def cli(env, sortby, datacenter, identifier, subnet_type, network_space, ipv4, ipv6): mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table([ 'id', 'identifier', 'type', 'network_space', 'datacenter', 'vlan_id', 'IPs', 'hardware', 'vs', ]) table.sortby = sortby version = 0 if ipv4: version = 4 elif ipv6: version = 6 subnets = mgr.list_subnets( datacenter=datacenter, version=version, identifier=identifier, subnet_type=subnet_type, network_space=network_space, ) for subnet in subnets: table.add_row([ subnet['id'], '%s/%s' % (subnet['networkIdentifier'], str(subnet['cidr'])), subnet.get('subnetType', formatting.blank()), utils.lookup(subnet, 'networkVlan', 'networkSpace') or formatting.blank(), utils.lookup(subnet, 'datacenter', 'name',) or formatting.blank(), subnet['networkVlanId'], subnet['ipAddressCount'], len(subnet['hardware']), len(subnet['virtualGuests']), ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "sortby", ",", "datacenter", ",", "identifier", ",", "subnet_type", ",", "network_space", ",", "ipv4", ",", "ipv6", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'identifier'", ",", "'type'", ",", "'network_space'", ",", "'datacenter'", ",", "'vlan_id'", ",", "'IPs'", ",", "'hardware'", ",", "'vs'", ",", "]", ")", "table", ".", "sortby", "=", "sortby", "version", "=", "0", "if", "ipv4", ":", "version", "=", "4", "elif", "ipv6", ":", "version", "=", "6", "subnets", "=", "mgr", ".", "list_subnets", "(", "datacenter", "=", "datacenter", ",", "version", "=", "version", ",", "identifier", "=", "identifier", ",", "subnet_type", "=", "subnet_type", ",", "network_space", "=", "network_space", ",", ")", "for", "subnet", "in", "subnets", ":", "table", ".", "add_row", "(", "[", "subnet", "[", "'id'", "]", ",", "'%s/%s'", "%", "(", "subnet", "[", "'networkIdentifier'", "]", ",", "str", "(", "subnet", "[", "'cidr'", "]", ")", ")", ",", "subnet", ".", "get", "(", "'subnetType'", ",", "formatting", ".", "blank", "(", ")", ")", ",", "utils", ".", "lookup", "(", "subnet", ",", "'networkVlan'", ",", "'networkSpace'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "utils", ".", "lookup", "(", "subnet", ",", "'datacenter'", ",", "'name'", ",", ")", "or", "formatting", ".", "blank", "(", ")", ",", "subnet", "[", "'networkVlanId'", "]", ",", "subnet", "[", "'ipAddressCount'", "]", ",", "len", "(", "subnet", "[", "'hardware'", "]", ")", ",", "len", "(", "subnet", "[", "'virtualGuests'", "]", ")", ",", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List subnets.
[ "List", "subnets", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/subnet/list.py#L32-L72
softlayer/softlayer-python
SoftLayer/CLI/firewall/add.py
cli
def cli(env, target, firewall_type, high_availability): """Create new firewall. TARGET: Id of the server the firewall will protect """ 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: exceptions.CLIAbort( "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) env.fout("Firewall is being created!")
python
def cli(env, target, firewall_type, high_availability): 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: exceptions.CLIAbort( "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) env.fout("Firewall is being created!")
[ "def", "cli", "(", "env", ",", "target", ",", "firewall_type", ",", "high_availability", ")", ":", "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", ":", "exceptions", ".", "CLIAbort", "(", "\"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", ")", "env", ".", "fout", "(", "\"Firewall is being created!\"", ")" ]
Create new firewall. TARGET: Id of the server the firewall will protect
[ "Create", "new", "firewall", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/firewall/add.py#L22-L58
softlayer/softlayer-python
SoftLayer/CLI/cdn/purge.py
cli
def cli(env, account_id, content_url): """Purge cached files from all edge nodes. Examples: slcli cdn purge 97794 http://example.com/cdn/file.txt slcli cdn purge 97794 http://example.com/cdn/file.txt https://dal01.example.softlayer.net/image.png """ manager = SoftLayer.CDNManager(env.client) content_list = manager.purge_content(account_id, content_url) table = formatting.Table(['url', 'status']) for content in content_list: table.add_row([ content['url'], content['statusCode'] ]) env.fout(table)
python
def cli(env, account_id, content_url): manager = SoftLayer.CDNManager(env.client) content_list = manager.purge_content(account_id, content_url) table = formatting.Table(['url', 'status']) for content in content_list: table.add_row([ content['url'], content['statusCode'] ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "account_id", ",", "content_url", ")", ":", "manager", "=", "SoftLayer", ".", "CDNManager", "(", "env", ".", "client", ")", "content_list", "=", "manager", ".", "purge_content", "(", "account_id", ",", "content_url", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'url'", ",", "'status'", "]", ")", "for", "content", "in", "content_list", ":", "table", ".", "add_row", "(", "[", "content", "[", "'url'", "]", ",", "content", "[", "'statusCode'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
Purge cached files from all edge nodes. Examples: slcli cdn purge 97794 http://example.com/cdn/file.txt slcli cdn purge 97794 http://example.com/cdn/file.txt https://dal01.example.softlayer.net/image.png
[ "Purge", "cached", "files", "from", "all", "edge", "nodes", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/cdn/purge.py#L15-L34
softlayer/softlayer-python
SoftLayer/decoration.py
retry
def retry(ex=RETRIABLE, tries=4, delay=5, backoff=2, logger=None): """Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ex: the exception to check. may be a tuple of exceptions to check :param tries: number of times to try (not retry) before giving up :param delay: initial delay between retries in seconds. A random 0-5s will be added to this number to stagger calls. :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :param logger: logger to use. If None, print """ def deco_retry(func): """@retry(arg[, ...]) -> true decorator""" @wraps(func) def f_retry(*args, **kwargs): """true decorator -> decorated function""" mtries, mdelay = tries, delay while mtries > 1: try: return func(*args, **kwargs) except ex as error: sleeping = mdelay + randint(0, 5) msg = "%s, Retrying in %d seconds..." % (str(error), sleeping) if logger: logger.warning(msg) sleep(sleeping) mtries -= 1 mdelay *= backoff return func(*args, **kwargs) return f_retry # true decorator return deco_retry
python
def retry(ex=RETRIABLE, tries=4, delay=5, backoff=2, logger=None): def deco_retry(func): @wraps(func) def f_retry(*args, **kwargs): mtries, mdelay = tries, delay while mtries > 1: try: return func(*args, **kwargs) except ex as error: sleeping = mdelay + randint(0, 5) msg = "%s, Retrying in %d seconds..." % (str(error), sleeping) if logger: logger.warning(msg) sleep(sleeping) mtries -= 1 mdelay *= backoff return func(*args, **kwargs) return f_retry return deco_retry
[ "def", "retry", "(", "ex", "=", "RETRIABLE", ",", "tries", "=", "4", ",", "delay", "=", "5", ",", "backoff", "=", "2", ",", "logger", "=", "None", ")", ":", "def", "deco_retry", "(", "func", ")", ":", "\"\"\"@retry(arg[, ...]) -> true decorator\"\"\"", "@", "wraps", "(", "func", ")", "def", "f_retry", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"true decorator -> decorated function\"\"\"", "mtries", ",", "mdelay", "=", "tries", ",", "delay", "while", "mtries", ">", "1", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "ex", "as", "error", ":", "sleeping", "=", "mdelay", "+", "randint", "(", "0", ",", "5", ")", "msg", "=", "\"%s, Retrying in %d seconds...\"", "%", "(", "str", "(", "error", ")", ",", "sleeping", ")", "if", "logger", ":", "logger", ".", "warning", "(", "msg", ")", "sleep", "(", "sleeping", ")", "mtries", "-=", "1", "mdelay", "*=", "backoff", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "f_retry", "# true decorator", "return", "deco_retry" ]
Retry calling the decorated function using an exponential backoff. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry :param ex: the exception to check. may be a tuple of exceptions to check :param tries: number of times to try (not retry) before giving up :param delay: initial delay between retries in seconds. A random 0-5s will be added to this number to stagger calls. :param backoff: backoff multiplier e.g. value of 2 will double the delay each retry :param logger: logger to use. If None, print
[ "Retry", "calling", "the", "decorated", "function", "using", "an", "exponential", "backoff", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/decoration.py#L22-L57
softlayer/softlayer-python
SoftLayer/CLI/order/package_locations.py
cli
def cli(env, package_keyname): """List Datacenters a package can be ordered in. Use the location Key Name to place orders """ manager = ordering.OrderingManager(env.client) table = formatting.Table(COLUMNS) locations = manager.package_locations(package_keyname) for region in locations: for datacenter in region['locations']: table.add_row([ datacenter['location']['id'], datacenter['location']['name'], region['description'], region['keyname'] ]) env.fout(table)
python
def cli(env, package_keyname): manager = ordering.OrderingManager(env.client) table = formatting.Table(COLUMNS) locations = manager.package_locations(package_keyname) for region in locations: for datacenter in region['locations']: table.add_row([ datacenter['location']['id'], datacenter['location']['name'], region['description'], region['keyname'] ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "package_keyname", ")", ":", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "locations", "=", "manager", ".", "package_locations", "(", "package_keyname", ")", "for", "region", "in", "locations", ":", "for", "datacenter", "in", "region", "[", "'locations'", "]", ":", "table", ".", "add_row", "(", "[", "datacenter", "[", "'location'", "]", "[", "'id'", "]", ",", "datacenter", "[", "'location'", "]", "[", "'name'", "]", ",", "region", "[", "'description'", "]", ",", "region", "[", "'keyname'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List Datacenters a package can be ordered in. Use the location Key Name to place orders
[ "List", "Datacenters", "a", "package", "can", "be", "ordered", "in", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/package_locations.py#L15-L32
softlayer/softlayer-python
SoftLayer/CLI/rwhois/edit.py
cli
def cli(env, abuse, address1, address2, city, company, country, firstname, lastname, postal, public, state): """Edit the RWhois data on the account.""" mgr = SoftLayer.NetworkManager(env.client) update = { 'abuse_email': abuse, 'address1': address1, 'address2': address2, 'company_name': company, 'city': city, 'country': country, 'first_name': firstname, 'last_name': lastname, 'postal_code': postal, 'state': state, 'private_residence': public, } if public is True: update['private_residence'] = False elif public is False: update['private_residence'] = True check = [x for x in update.values() if x is not None] if not check: raise exceptions.CLIAbort( "You must specify at least one field to update.") mgr.edit_rwhois(**update)
python
def cli(env, abuse, address1, address2, city, company, country, firstname, lastname, postal, public, state): mgr = SoftLayer.NetworkManager(env.client) update = { 'abuse_email': abuse, 'address1': address1, 'address2': address2, 'company_name': company, 'city': city, 'country': country, 'first_name': firstname, 'last_name': lastname, 'postal_code': postal, 'state': state, 'private_residence': public, } if public is True: update['private_residence'] = False elif public is False: update['private_residence'] = True check = [x for x in update.values() if x is not None] if not check: raise exceptions.CLIAbort( "You must specify at least one field to update.") mgr.edit_rwhois(**update)
[ "def", "cli", "(", "env", ",", "abuse", ",", "address1", ",", "address2", ",", "city", ",", "company", ",", "country", ",", "firstname", ",", "lastname", ",", "postal", ",", "public", ",", "state", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "update", "=", "{", "'abuse_email'", ":", "abuse", ",", "'address1'", ":", "address1", ",", "'address2'", ":", "address2", ",", "'company_name'", ":", "company", ",", "'city'", ":", "city", ",", "'country'", ":", "country", ",", "'first_name'", ":", "firstname", ",", "'last_name'", ":", "lastname", ",", "'postal_code'", ":", "postal", ",", "'state'", ":", "state", ",", "'private_residence'", ":", "public", ",", "}", "if", "public", "is", "True", ":", "update", "[", "'private_residence'", "]", "=", "False", "elif", "public", "is", "False", ":", "update", "[", "'private_residence'", "]", "=", "True", "check", "=", "[", "x", "for", "x", "in", "update", ".", "values", "(", ")", "if", "x", "is", "not", "None", "]", "if", "not", "check", ":", "raise", "exceptions", ".", "CLIAbort", "(", "\"You must specify at least one field to update.\"", ")", "mgr", ".", "edit_rwhois", "(", "*", "*", "update", ")" ]
Edit the RWhois data on the account.
[ "Edit", "the", "RWhois", "data", "on", "the", "account", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/rwhois/edit.py#L26-L55
softlayer/softlayer-python
SoftLayer/CLI/order/quote.py
_parse_create_args
def _parse_create_args(client, args): """Converts CLI arguments to args for VSManager.create_instance. :param dict args: CLI arguments """ data = {} if args.get('quantity'): data['quantity'] = int(args.get('quantity')) if args.get('postinstall'): data['provisionScripts'] = [args.get('postinstall')] if args.get('complex_type'): data['complexType'] = args.get('complex_type') if args.get('fqdn'): servers = [] for name in args.get('fqdn'): fqdn = name.split(".", 1) servers.append({'hostname': fqdn[0], 'domain': fqdn[1]}) data['hardware'] = servers if args.get('image'): if args.get('image').isdigit(): image_mgr = ImageManager(client) image_details = image_mgr.get_image(args.get('image'), mask="id,globalIdentifier") data['imageTemplateGlobalIdentifier'] = image_details['globalIdentifier'] else: data['imageTemplateGlobalIdentifier'] = args['image'] userdata = None if args.get('userdata'): userdata = args['userdata'] elif args.get('userfile'): with open(args['userfile'], 'r') as userfile: userdata = userfile.read() if userdata: for hardware in data['hardware']: hardware['userData'] = [{'value': userdata}] # Get the SSH keys if args.get('key'): keys = [] for key in args.get('key'): resolver = SshKeyManager(client).resolve_ids key_id = helpers.resolve_id(resolver, key, 'SshKey') keys.append(key_id) data['sshKeys'] = keys return data
python
def _parse_create_args(client, args): data = {} if args.get('quantity'): data['quantity'] = int(args.get('quantity')) if args.get('postinstall'): data['provisionScripts'] = [args.get('postinstall')] if args.get('complex_type'): data['complexType'] = args.get('complex_type') if args.get('fqdn'): servers = [] for name in args.get('fqdn'): fqdn = name.split(".", 1) servers.append({'hostname': fqdn[0], 'domain': fqdn[1]}) data['hardware'] = servers if args.get('image'): if args.get('image').isdigit(): image_mgr = ImageManager(client) image_details = image_mgr.get_image(args.get('image'), mask="id,globalIdentifier") data['imageTemplateGlobalIdentifier'] = image_details['globalIdentifier'] else: data['imageTemplateGlobalIdentifier'] = args['image'] userdata = None if args.get('userdata'): userdata = args['userdata'] elif args.get('userfile'): with open(args['userfile'], 'r') as userfile: userdata = userfile.read() if userdata: for hardware in data['hardware']: hardware['userData'] = [{'value': userdata}] if args.get('key'): keys = [] for key in args.get('key'): resolver = SshKeyManager(client).resolve_ids key_id = helpers.resolve_id(resolver, key, 'SshKey') keys.append(key_id) data['sshKeys'] = keys return data
[ "def", "_parse_create_args", "(", "client", ",", "args", ")", ":", "data", "=", "{", "}", "if", "args", ".", "get", "(", "'quantity'", ")", ":", "data", "[", "'quantity'", "]", "=", "int", "(", "args", ".", "get", "(", "'quantity'", ")", ")", "if", "args", ".", "get", "(", "'postinstall'", ")", ":", "data", "[", "'provisionScripts'", "]", "=", "[", "args", ".", "get", "(", "'postinstall'", ")", "]", "if", "args", ".", "get", "(", "'complex_type'", ")", ":", "data", "[", "'complexType'", "]", "=", "args", ".", "get", "(", "'complex_type'", ")", "if", "args", ".", "get", "(", "'fqdn'", ")", ":", "servers", "=", "[", "]", "for", "name", "in", "args", ".", "get", "(", "'fqdn'", ")", ":", "fqdn", "=", "name", ".", "split", "(", "\".\"", ",", "1", ")", "servers", ".", "append", "(", "{", "'hostname'", ":", "fqdn", "[", "0", "]", ",", "'domain'", ":", "fqdn", "[", "1", "]", "}", ")", "data", "[", "'hardware'", "]", "=", "servers", "if", "args", ".", "get", "(", "'image'", ")", ":", "if", "args", ".", "get", "(", "'image'", ")", ".", "isdigit", "(", ")", ":", "image_mgr", "=", "ImageManager", "(", "client", ")", "image_details", "=", "image_mgr", ".", "get_image", "(", "args", ".", "get", "(", "'image'", ")", ",", "mask", "=", "\"id,globalIdentifier\"", ")", "data", "[", "'imageTemplateGlobalIdentifier'", "]", "=", "image_details", "[", "'globalIdentifier'", "]", "else", ":", "data", "[", "'imageTemplateGlobalIdentifier'", "]", "=", "args", "[", "'image'", "]", "userdata", "=", "None", "if", "args", ".", "get", "(", "'userdata'", ")", ":", "userdata", "=", "args", "[", "'userdata'", "]", "elif", "args", ".", "get", "(", "'userfile'", ")", ":", "with", "open", "(", "args", "[", "'userfile'", "]", ",", "'r'", ")", "as", "userfile", ":", "userdata", "=", "userfile", ".", "read", "(", ")", "if", "userdata", ":", "for", "hardware", "in", "data", "[", "'hardware'", "]", ":", "hardware", "[", "'userData'", "]", "=", "[", "{", "'value'", ":", "userdata", "}", "]", "# Get the SSH keys", "if", "args", ".", "get", "(", "'key'", ")", ":", "keys", "=", "[", "]", "for", "key", "in", "args", ".", "get", "(", "'key'", ")", ":", "resolver", "=", "SshKeyManager", "(", "client", ")", ".", "resolve_ids", "key_id", "=", "helpers", ".", "resolve_id", "(", "resolver", ",", "key", ",", "'SshKey'", ")", "keys", ".", "append", "(", "key_id", ")", "data", "[", "'sshKeys'", "]", "=", "keys", "return", "data" ]
Converts CLI arguments to args for VSManager.create_instance. :param dict args: CLI arguments
[ "Converts", "CLI", "arguments", "to", "args", "for", "VSManager", ".", "create_instance", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/quote.py#L13-L61
softlayer/softlayer-python
SoftLayer/CLI/order/quote.py
cli
def cli(env, quote, **args): """View and Order a quote \f :note: The hostname and domain are split out from the fully qualified domain name. If you want to order multiple servers, you need to specify each FQDN. Postinstall, userdata, and sshkeys are applied to all servers in an order. :: slcli order quote 12345 --fqdn testing.tester.com \\ --complex-type SoftLayer_Container_Product_Order_Virtual_Guest -k sshKeyNameLabel\\ -i https://domain.com/runthis.sh --userdata DataGoesHere """ table = formatting.Table([ 'Id', 'Name', 'Created', 'Expiration', 'Status' ]) create_args = _parse_create_args(env.client, args) manager = ordering.OrderingManager(env.client) quote_details = manager.get_quote_details(quote) package = quote_details['order']['items'][0]['package'] create_args['packageId'] = package['id'] if args.get('verify'): result = manager.verify_quote(quote, create_args) verify_table = formatting.Table(['keyName', 'description', 'cost']) verify_table.align['keyName'] = 'l' verify_table.align['description'] = 'l' for price in result['prices']: cost_key = 'hourlyRecurringFee' if result['useHourlyPricing'] is True else 'recurringFee' verify_table.add_row([ price['item']['keyName'], price['item']['description'], price[cost_key] if cost_key in price else formatting.blank() ]) env.fout(verify_table) else: result = manager.order_quote(quote, create_args) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', result['orderId']]) table.add_row(['created', result['orderDate']]) table.add_row(['status', result['placedOrder']['status']]) env.fout(table)
python
def cli(env, quote, **args): table = formatting.Table([ 'Id', 'Name', 'Created', 'Expiration', 'Status' ]) create_args = _parse_create_args(env.client, args) manager = ordering.OrderingManager(env.client) quote_details = manager.get_quote_details(quote) package = quote_details['order']['items'][0]['package'] create_args['packageId'] = package['id'] if args.get('verify'): result = manager.verify_quote(quote, create_args) verify_table = formatting.Table(['keyName', 'description', 'cost']) verify_table.align['keyName'] = 'l' verify_table.align['description'] = 'l' for price in result['prices']: cost_key = 'hourlyRecurringFee' if result['useHourlyPricing'] is True else 'recurringFee' verify_table.add_row([ price['item']['keyName'], price['item']['description'], price[cost_key] if cost_key in price else formatting.blank() ]) env.fout(verify_table) else: result = manager.order_quote(quote, create_args) table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['id', result['orderId']]) table.add_row(['created', result['orderDate']]) table.add_row(['status', result['placedOrder']['status']]) env.fout(table)
[ "def", "cli", "(", "env", ",", "quote", ",", "*", "*", "args", ")", ":", "table", "=", "formatting", ".", "Table", "(", "[", "'Id'", ",", "'Name'", ",", "'Created'", ",", "'Expiration'", ",", "'Status'", "]", ")", "create_args", "=", "_parse_create_args", "(", "env", ".", "client", ",", "args", ")", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "quote_details", "=", "manager", ".", "get_quote_details", "(", "quote", ")", "package", "=", "quote_details", "[", "'order'", "]", "[", "'items'", "]", "[", "0", "]", "[", "'package'", "]", "create_args", "[", "'packageId'", "]", "=", "package", "[", "'id'", "]", "if", "args", ".", "get", "(", "'verify'", ")", ":", "result", "=", "manager", ".", "verify_quote", "(", "quote", ",", "create_args", ")", "verify_table", "=", "formatting", ".", "Table", "(", "[", "'keyName'", ",", "'description'", ",", "'cost'", "]", ")", "verify_table", ".", "align", "[", "'keyName'", "]", "=", "'l'", "verify_table", ".", "align", "[", "'description'", "]", "=", "'l'", "for", "price", "in", "result", "[", "'prices'", "]", ":", "cost_key", "=", "'hourlyRecurringFee'", "if", "result", "[", "'useHourlyPricing'", "]", "is", "True", "else", "'recurringFee'", "verify_table", ".", "add_row", "(", "[", "price", "[", "'item'", "]", "[", "'keyName'", "]", ",", "price", "[", "'item'", "]", "[", "'description'", "]", ",", "price", "[", "cost_key", "]", "if", "cost_key", "in", "price", "else", "formatting", ".", "blank", "(", ")", "]", ")", "env", ".", "fout", "(", "verify_table", ")", "else", ":", "result", "=", "manager", ".", "order_quote", "(", "quote", ",", "create_args", ")", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "table", ".", "align", "[", "'name'", "]", "=", "'r'", "table", ".", "align", "[", "'value'", "]", "=", "'l'", "table", ".", "add_row", "(", "[", "'id'", ",", "result", "[", "'orderId'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'created'", ",", "result", "[", "'orderDate'", "]", "]", ")", "table", ".", "add_row", "(", "[", "'status'", ",", "result", "[", "'placedOrder'", "]", "[", "'status'", "]", "]", ")", "env", ".", "fout", "(", "table", ")" ]
View and Order a quote \f :note: The hostname and domain are split out from the fully qualified domain name. If you want to order multiple servers, you need to specify each FQDN. Postinstall, userdata, and sshkeys are applied to all servers in an order. :: slcli order quote 12345 --fqdn testing.tester.com \\ --complex-type SoftLayer_Container_Product_Order_Virtual_Guest -k sshKeyNameLabel\\ -i https://domain.com/runthis.sh --userdata DataGoesHere
[ "View", "and", "Order", "a", "quote" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/quote.py#L81-L130
softlayer/softlayer-python
SoftLayer/managers/block.py
BlockStorageManager.authorize_host_to_volume
def authorize_host_to_volume(self, volume_id, hardware_ids=None, virtual_guest_ids=None, ip_address_ids=None, **kwargs): """Authorizes hosts to Block Storage Volumes :param volume_id: The Block volume to authorize hosts to :param hardware_ids: A List of SoftLayer_Hardware ids :param virtual_guest_ids: A List of SoftLayer_Virtual_Guest ids :param ip_address_ids: A List of SoftLayer_Network_Subnet_IpAddress ids :return: Returns an array of SoftLayer_Network_Storage_Allowed_Host objects which now have access to the given Block volume """ host_templates = [] storage_utils.populate_host_templates(host_templates, hardware_ids, virtual_guest_ids, ip_address_ids, None) return self.client.call('Network_Storage', 'allowAccessFromHostList', host_templates, id=volume_id, **kwargs)
python
def authorize_host_to_volume(self, volume_id, hardware_ids=None, virtual_guest_ids=None, ip_address_ids=None, **kwargs): host_templates = [] storage_utils.populate_host_templates(host_templates, hardware_ids, virtual_guest_ids, ip_address_ids, None) return self.client.call('Network_Storage', 'allowAccessFromHostList', host_templates, id=volume_id, **kwargs)
[ "def", "authorize_host_to_volume", "(", "self", ",", "volume_id", ",", "hardware_ids", "=", "None", ",", "virtual_guest_ids", "=", "None", ",", "ip_address_ids", "=", "None", ",", "*", "*", "kwargs", ")", ":", "host_templates", "=", "[", "]", "storage_utils", ".", "populate_host_templates", "(", "host_templates", ",", "hardware_ids", ",", "virtual_guest_ids", ",", "ip_address_ids", ",", "None", ")", "return", "self", ".", "client", ".", "call", "(", "'Network_Storage'", ",", "'allowAccessFromHostList'", ",", "host_templates", ",", "id", "=", "volume_id", ",", "*", "*", "kwargs", ")" ]
Authorizes hosts to Block Storage Volumes :param volume_id: The Block volume to authorize hosts to :param hardware_ids: A List of SoftLayer_Hardware ids :param virtual_guest_ids: A List of SoftLayer_Virtual_Guest ids :param ip_address_ids: A List of SoftLayer_Network_Subnet_IpAddress ids :return: Returns an array of SoftLayer_Network_Storage_Allowed_Host objects which now have access to the given Block volume
[ "Authorizes", "hosts", "to", "Block", "Storage", "Volumes" ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/block.py#L154-L177
softlayer/softlayer-python
SoftLayer/managers/block.py
BlockStorageManager.order_replicant_volume
def order_replicant_volume(self, volume_id, snapshot_schedule, location, tier=None, os_type=None): """Places an order for a replicant block volume. :param volume_id: The ID of the primary volume to be replicated :param snapshot_schedule: The primary volume's snapshot schedule to use for replication :param location: The location for the ordered replicant volume :param tier: The tier (IOPS per GB) of the primary volume :param os_type: The OS type of the primary volume :return: Returns a SoftLayer_Container_Product_Order_Receipt """ block_mask = 'billingItem[activeChildren,hourlyFlag],'\ 'storageTierLevel,osType,staasVersion,'\ 'hasEncryptionAtRest,snapshotCapacityGb,schedules,'\ 'intervalSchedule,hourlySchedule,dailySchedule,'\ 'weeklySchedule,storageType[keyName],provisionedIops' block_volume = self.get_block_volume_details(volume_id, mask=block_mask) if os_type is None: if isinstance(utils.lookup(block_volume, 'osType', 'keyName'), str): os_type = block_volume['osType']['keyName'] else: raise exceptions.SoftLayerError( "Cannot find primary volume's os-type " "automatically; must specify manually") order = storage_utils.prepare_replicant_order_object( self, snapshot_schedule, location, tier, block_volume, 'block' ) order['osFormatType'] = {'keyName': os_type} return self.client.call('Product_Order', 'placeOrder', order)
python
def order_replicant_volume(self, volume_id, snapshot_schedule, location, tier=None, os_type=None): block_mask = 'billingItem[activeChildren,hourlyFlag],'\ 'storageTierLevel,osType,staasVersion,'\ 'hasEncryptionAtRest,snapshotCapacityGb,schedules,'\ 'intervalSchedule,hourlySchedule,dailySchedule,'\ 'weeklySchedule,storageType[keyName],provisionedIops' block_volume = self.get_block_volume_details(volume_id, mask=block_mask) if os_type is None: if isinstance(utils.lookup(block_volume, 'osType', 'keyName'), str): os_type = block_volume['osType']['keyName'] else: raise exceptions.SoftLayerError( "Cannot find primary volume's os-type " "automatically; must specify manually") order = storage_utils.prepare_replicant_order_object( self, snapshot_schedule, location, tier, block_volume, 'block' ) order['osFormatType'] = {'keyName': os_type} return self.client.call('Product_Order', 'placeOrder', order)
[ "def", "order_replicant_volume", "(", "self", ",", "volume_id", ",", "snapshot_schedule", ",", "location", ",", "tier", "=", "None", ",", "os_type", "=", "None", ")", ":", "block_mask", "=", "'billingItem[activeChildren,hourlyFlag],'", "'storageTierLevel,osType,staasVersion,'", "'hasEncryptionAtRest,snapshotCapacityGb,schedules,'", "'intervalSchedule,hourlySchedule,dailySchedule,'", "'weeklySchedule,storageType[keyName],provisionedIops'", "block_volume", "=", "self", ".", "get_block_volume_details", "(", "volume_id", ",", "mask", "=", "block_mask", ")", "if", "os_type", "is", "None", ":", "if", "isinstance", "(", "utils", ".", "lookup", "(", "block_volume", ",", "'osType'", ",", "'keyName'", ")", ",", "str", ")", ":", "os_type", "=", "block_volume", "[", "'osType'", "]", "[", "'keyName'", "]", "else", ":", "raise", "exceptions", ".", "SoftLayerError", "(", "\"Cannot find primary volume's os-type \"", "\"automatically; must specify manually\"", ")", "order", "=", "storage_utils", ".", "prepare_replicant_order_object", "(", "self", ",", "snapshot_schedule", ",", "location", ",", "tier", ",", "block_volume", ",", "'block'", ")", "order", "[", "'osFormatType'", "]", "=", "{", "'keyName'", ":", "os_type", "}", "return", "self", ".", "client", ".", "call", "(", "'Product_Order'", ",", "'placeOrder'", ",", "order", ")" ]
Places an order for a replicant block volume. :param volume_id: The ID of the primary volume to be replicated :param snapshot_schedule: The primary volume's snapshot schedule to use for replication :param location: The location for the ordered replicant volume :param tier: The tier (IOPS per GB) of the primary volume :param os_type: The OS type of the primary volume :return: Returns a SoftLayer_Container_Product_Order_Receipt
[ "Places", "an", "order", "for", "a", "replicant", "block", "volume", "." ]
train
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/block.py#L224-L260