code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' a helper function shared between functions that will return a container_id. First preference goes to a container_id provided by the user at runtime. Second preference goes to the container_id instantiated with the client. Parameters ========== container_id: image uri to parse (required) ''' # The user must provide a container_id, or have one with the client if container_id == None and self.container_id == None: bot.exit('You must provide a container_id.') # Choose whichever is not None, with preference for function provided container_id = container_id or self.container_id return container_id
def get_container_id(self, container_id=None)
a helper function shared between functions that will return a container_id. First preference goes to a container_id provided by the user at runtime. Second preference goes to the container_id instantiated with the client. Parameters ========== container_id: image uri to parse (required)
8.936507
3.133983
2.851485
''' Run a command, show the message to the user if quiet isn't set, and return the return code. This is a wrapper for the OCI client to run a command and easily return the return code value (what the user is ultimately interested in). Parameters ========== cmd: the command (list) to run. sudo: whether to add sudo or not. ''' sudo = self._get_sudo(sudo) result = self._run_command(cmd, sudo=sudo, quiet=True, return_result=True) # Successful return with no output if len(result) == 0: return # Show the response to the user, only if not quiet. elif not self.quiet: bot.println(result['message']) # Return the state object to the user return result['return_code']
def _run_and_return(self, cmd, sudo=None)
Run a command, show the message to the user if quiet isn't set, and return the return code. This is a wrapper for the OCI client to run a command and easily return the return code value (what the user is ultimately interested in). Parameters ========== cmd: the command (list) to run. sudo: whether to add sudo or not.
7.839124
3.180142
2.465023
''' a wrapper to the base init_command, ensuring that "oci" is added to each command Parameters ========== action: the main action to perform (e.g., build) flags: one or more additional flags (e.g, volumes) not implemented yet. ''' from spython.main.base.command import init_command if not isinstance(action, list): action = [action] cmd = ['oci'] + action return init_command(self, cmd, flags)
def _init_command(self, action, flags=None)
a wrapper to the base init_command, ensuring that "oci" is added to each command Parameters ========== action: the main action to perform (e.g., build) flags: one or more additional flags (e.g, volumes) not implemented yet.
9.369371
2.692235
3.480146
'''export will export an image, sudo must be used. Parameters ========== image_path: full path to image tmptar: if defined, use custom temporary path for tar export ''' from spython.utils import check_install check_install() if tmptar is None: tmptar = "/%s/tmptar.tar" %(tempfile.mkdtemp()) cmd = ['singularity', 'image.export', '-f', tmptar, image_path] output = self.run_command(cmd, sudo=False) return tmptar
def export(self, image_path, tmptar=None)
export will export an image, sudo must be used. Parameters ========== image_path: full path to image tmptar: if defined, use custom temporary path for tar export
7.667802
3.734135
2.053434
'''write_json will (optionally,pretty print) a json object to file :param json_obj: the dict to print to json :param filename: the output file to write to :param pretty_print: if True, will use nicer formatting ''' with open(filename, mode) as filey: if print_pretty: filey.writelines( json.dumps( json_obj, indent=4, separators=( ',', ': '))) else: filey.writelines(json.dumps(json_obj)) return filename
def write_json(json_obj, filename, mode="w", print_pretty=True)
write_json will (optionally,pretty print) a json object to file :param json_obj: the dict to print to json :param filename: the output file to write to :param pretty_print: if True, will use nicer formatting
3.215125
1.975744
1.627298
''' execute: send a command to a container Parameters ========== image: full path to singularity image command: command to send to container app: if not None, execute a command in context of an app writable: This option makes the file system accessible as read/write contain: This option disables the automatic sharing of writable filesystems on your host bind: list or single string of bind paths. This option allows you to map directories on your host system to directories within your container using bind mounts nv: if True, load Nvidia Drivers in runtime (default False) return_result: if True, return entire json object with return code and message result (default is False) ''' from spython.utils import check_install check_install() cmd = self._init_command('exec') # nv option leverages any GPU cards if nv is True: cmd += ['--nv'] # If the image is given as a list, it's probably the command if isinstance(image, list): command = image image = None if command is not None: # No image provided, default to use the client's loaded image if image is None: image = self._get_uri() self.quiet = True # If an instance is provided, grab it's name if isinstance(image, self.instance): image = image.get_uri() # Does the user want to use bind paths option? if bind is not None: cmd += self._generate_bind_list(bind) # Does the user want to run an app? if app is not None: cmd = cmd + ['--app', app] sudo = False if writable is True: sudo = True if not isinstance(command, list): command = command.split(' ') cmd = cmd + [image] + command if stream is False: return self._run_command(cmd, sudo=sudo, return_result=return_result) return stream_command(cmd, sudo=sudo) bot.error('Please include a command (list) to execute.')
def execute(self, image = None, command = None, app = None, writable = False, contain = False, bind = None, stream = False, nv = False, return_result=False)
execute: send a command to a container Parameters ========== image: full path to singularity image command: command to send to container app: if not None, execute a command in context of an app writable: This option makes the file system accessible as read/write contain: This option disables the automatic sharing of writable filesystems on your host bind: list or single string of bind paths. This option allows you to map directories on your host system to directories within your container using bind mounts nv: if True, load Nvidia Drivers in runtime (default False) return_result: if True, return entire json object with return code and message result (default is False)
6.195061
3.133312
1.977161
'''parse a table to json from a string, where a header is expected by default. Return a jsonified table. Parameters ========== table_string: the string table, ideally with a header header: header of expected table, must match dimension (number columns) remove_rows: an integer to indicate a number of rows to remove from top the default is 1 assuming we don't want the header ''' rows = [x for x in table_string.split('\n') if x] rows = rows[0+remove_rows:] # Parse into json dictionary parsed = [] for row in rows: item = {} # This assumes no white spaces in each entry, which should be the case row = [x for x in row.split(' ') if x] for e in range(len(row)): item[header[e]] = row[e] parsed.append(item) return parsed
def parse_table(table_string, header, remove_rows=1)
parse a table to json from a string, where a header is expected by default. Return a jsonified table. Parameters ========== table_string: the string table, ideally with a header header: header of expected table, must match dimension (number columns) remove_rows: an integer to indicate a number of rows to remove from top the default is 1 assuming we don't want the header
6.102181
2.354091
2.592161
'''get is a list for a single instance. It is assumed to be running, and we need to look up the PID, etc. ''' from spython.utils import check_install check_install() # Ensure compatible for singularity prior to 3.0, and after 3.0 subgroup = "instance.list" if 'version 3' in self.version(): subgroup = ["instance", "list"] cmd = self._init_command(subgroup) cmd.append(name) output = run_command(cmd, quiet=True) # Success, we have instances if output['return_code'] == 0: # Only print the table if we are returning json if quiet is False: print(''.join(output['message'])) # Prepare json result from table header = ['daemon_name','pid','container_image'] instances = parse_table(output['message'][0], header) # Does the user want instance objects instead? listing = [] if return_json is False: for i in instances: new_instance = Instance(pid=i['pid'], name=i['daemon_name'], image=i['container_image'], start=False) listing.append(new_instance) instances = listing # Couldn't get UID elif output['return_code'] == 255: bot.error("Couldn't get UID") # Return code of 0 else: bot.info('No instances found.') # If we are given a name, return just one if name is not None and len(instances) == 1: instances = instances[0] return instances
def get(self, name, return_json=False, quiet=False)
get is a list for a single instance. It is assumed to be running, and we need to look up the PID, etc.
6.866303
5.484925
1.25185
'''determine the message level in the environment to set based on args. ''' level = "INFO" if args.debug is True: level = "DEBUG" elif args.quiet is True: level = "QUIET" os.environ['MESSAGELEVEL'] = level os.putenv('MESSAGELEVEL', level) os.environ['SINGULARITY_MESSAGELEVEL'] = level os.putenv('SINGULARITY_MESSAGELEVEL', level) # Import logger to set from spython.logger import bot bot.debug('Logging level %s' %level) import spython bot.debug("Singularity Python Version: %s" % spython.__version__)
def set_verbosity(args)
determine the message level in the environment to set based on args.
5.633942
4.432431
1.271073
''' The Image client holds the Singularity image command group, mainly deprecated commands (image.import) and additional command helpers that are commonly use but not provided by Singularity The levels of verbosity (debug and quiet) are passed from the main client via the environment variable MESSAGELEVEL. These commands are added to Client.image under main/__init__.py to expose subcommands: Client.image.export Client.image.imprt Client.image.decompress Client.image.create ''' class ImageClient(object): group = "image" from spython.main.base.logger import println from spython.main.base.command import ( init_command, run_command ) from .utils import ( compress, decompress ) from .create import create from .importcmd import importcmd from .export import export ImageClient.create = create ImageClient.imprt = importcmd ImageClient.export = export ImageClient.decompress = decompress ImageClient.compress = compress ImageClient.println = println ImageClient.init_command = init_command ImageClient.run_command = run_command cli = ImageClient() return cli
def generate_image_commands()
The Image client holds the Singularity image command group, mainly deprecated commands (image.import) and additional command helpers that are commonly use but not provided by Singularity The levels of verbosity (debug and quiet) are passed from the main client via the environment variable MESSAGELEVEL. These commands are added to Client.image under main/__init__.py to expose subcommands: Client.image.export Client.image.imprt Client.image.decompress Client.image.create
9.687146
2.620328
3.696921
'''return the initial Singularity command with any added flags. Parameters ========== action: the main action to perform (e.g., build) flags: one or more additional flags (e.g, volumes) not implemented yet. ''' if not isinstance(action, list): action = [action] cmd = ['singularity'] + action if self.quiet is True: cmd.insert(1, '--quiet') if self.debug is True: cmd.insert(1, '--debug') return cmd
def init_command(self, action, flags=None)
return the initial Singularity command with any added flags. Parameters ========== action: the main action to perform (e.g., build) flags: one or more additional flags (e.g, volumes) not implemented yet.
6.355158
2.364658
2.68756
'''generate bind string will take a single string or list of binds, and return a list that can be added to an exec or run command. For example, the following map as follows: ['/host:/container', '/both'] --> ["--bind", "/host:/container","--bind","/both" ] ['/both'] --> ["--bind", "/both"] '/host:container' --> ["--bind", "/host:container"] None --> [] An empty bind or otherwise value of None should return an empty list. The binds are also checked on the host. Parameters ========== bindlist: a string or list of bind mounts ''' binds = [] # Case 1: No binds provided if not bindlist: return binds # Case 2: provides a long string or non list, and must be split if not isinstance(bindlist, list): bindlist = bindlist.split(' ') for bind in bindlist: # Still cannot be None if bind: bot.debug('Adding bind %s' %bind) binds += ['--bind', bind] # Check that exists on host host = bind.split(':')[0] if not os.path.exists(host): bot.error('%s does not exist on host.' %bind) sys.exit(1) return binds
def generate_bind_list(self, bindlist=None)
generate bind string will take a single string or list of binds, and return a list that can be added to an exec or run command. For example, the following map as follows: ['/host:/container', '/both'] --> ["--bind", "/host:/container","--bind","/both" ] ['/both'] --> ["--bind", "/both"] '/host:container' --> ["--bind", "/host:container"] None --> [] An empty bind or otherwise value of None should return an empty list. The binds are also checked on the host. Parameters ========== bindlist: a string or list of bind mounts
6.330265
2.277025
2.78006
'''send command is a non interactive version of run_command, meaning that we execute the command and return the return value, but don't attempt to stream any content (text from the screen) back to the user. This is useful for commands interacting with OCI bundles. Parameters ========== cmd: the list of commands to send to the terminal sudo: use sudo (or not) ''' if sudo is True: cmd = ['sudo'] + cmd process = subprocess.Popen(cmd, stderr=stderr, stdout=stdout) result = process.communicate() return result
def send_command(self, cmd, sudo=False, stderr=None, stdout=None)
send command is a non interactive version of run_command, meaning that we execute the command and return the return value, but don't attempt to stream any content (text from the screen) back to the user. This is useful for commands interacting with OCI bundles. Parameters ========== cmd: the list of commands to send to the terminal sudo: use sudo (or not)
9.210214
1.807492
5.095576
'''run_command is a wrapper for the global run_command, checking first for sudo and exiting on error if needed. The message is returned as a list of lines for the calling function to parse, and stdout uses the parent process so it appears for the user. Parameters ========== cmd: the command to run sudo: does the command require sudo? quiet: if quiet set by function, overrides client setting. return_result: return the result, if not successful (default False). On success, returns result. ''' # First preference to function, then to client setting if quiet == None: quiet = self.quiet result = run_cmd(cmd, sudo=sudo, capture=capture, quiet=quiet) # If one line is returned, squash dimension if len(result['message']) == 1: result['message'] = result['message'][0] # If the user wants to return the result, just return it if return_result is True: return result # On success, return result if result['return_code'] == 0: return result['message'] return result
def run_command(self, cmd, sudo=False, capture=True, quiet=None, return_result=False)
run_command is a wrapper for the global run_command, checking first for sudo and exiting on error if needed. The message is returned as a list of lines for the calling function to parse, and stdout uses the parent process so it appears for the user. Parameters ========== cmd: the command to run sudo: does the command require sudo? quiet: if quiet set by function, overrides client setting. return_result: return the result, if not successful (default False). On success, returns result.
6.616894
2.327226
2.843253
'''load a recipe file into the client, first performing checks, and then parsing the file. Parameters ========== recipe: the original recipe file, parsed by the subclass either DockerRecipe or SingularityRecipe ''' self.recipe = recipe # the recipe file self._run_checks() # does the recipe file exist? self.parse()
def load(self, recipe)
load a recipe file into the client, first performing checks, and then parsing the file. Parameters ========== recipe: the original recipe file, parsed by the subclass either DockerRecipe or SingularityRecipe
17.182291
4.027985
4.265729
'''basic sanity checks for the file name (and others if needed) before attempting parsing. ''' if self.recipe is not None: # Does the recipe provided exist? if not os.path.exists(self.recipe): bot.error("Cannot find %s, is the path correct?" %self.recipe) sys.exit(1) # Ensure we carry fullpath self.recipe = os.path.abspath(self.recipe)
def _run_checks(self)
basic sanity checks for the file name (and others if needed) before attempting parsing.
9.420236
4.715009
1.997925
'''parse is the base function for parsing the recipe, whether it be a Dockerfile or Singularity recipe. The recipe is read in as lines, and saved to a list if needed for the future. If the client has it, the recipe type specific _parse function is called. Instructions for making a client subparser: It should have a main function _parse that parses a list of lines from some recipe text file into the appropriate sections, e.g., self.fromHeader self.environ self.labels self.install self.files self.test self.entrypoint ''' self.cmd = None self.comments = [] self.entrypoint = None self.environ = [] self.files = [] self.install = [] self.labels = [] self.ports = [] self.test = None self.volumes = [] if self.recipe: # Read in the raw lines of the file self.lines = read_file(self.recipe) # If properly instantiated by Docker or Singularity Recipe, parse if hasattr(self, '_parse'): self._parse()
def parse(self)
parse is the base function for parsing the recipe, whether it be a Dockerfile or Singularity recipe. The recipe is read in as lines, and saved to a list if needed for the future. If the client has it, the recipe type specific _parse function is called. Instructions for making a client subparser: It should have a main function _parse that parses a list of lines from some recipe text file into the appropriate sections, e.g., self.fromHeader self.environ self.labels self.install self.files self.test self.entrypoint
9.387969
2.126083
4.415617
'''save will convert a recipe to a specified format (defaults to the opposite of the recipe type originally loaded, (e.g., docker--> singularity and singularity-->docker) and write to an output file, if specified. If not specified, a temporary file is used. Parameters ========== output_file: the file to save to, not required (estimates default) convert_to: can be manually forced (docker or singularity) runscript: default runscript (entrypoint) to use force: if True, override discovery from Dockerfile ''' converted = self.convert(convert_to, runscript, force) if output_file is None: output_file = self._get_conversion_outfile(convert_to=None) bot.info('Saving to %s' %output_file) write_file(output_file, converted)
def save(self, output_file=None, convert_to=None, runscript="/bin/bash", force=False)
save will convert a recipe to a specified format (defaults to the opposite of the recipe type originally loaded, (e.g., docker--> singularity and singularity-->docker) and write to an output file, if specified. If not specified, a temporary file is used. Parameters ========== output_file: the file to save to, not required (estimates default) convert_to: can be manually forced (docker or singularity) runscript: default runscript (entrypoint) to use force: if True, override discovery from Dockerfile
7.825387
1.862441
4.201682
'''This is a convenience function for the user to easily call to get the most likely desired result, conversion to the opposite format. We choose the selection based on the recipe name - meaning that we perform conversion with default based on recipe name. If the recipe object is DockerRecipe, we convert to Singularity. If the recipe object is SingularityRecipe, we convert to Docker. The user can override this by setting the variable convert_to Parameters ========== convert_to: can be manually forced (docker or singularity) runscript: default runscript (entrypoint) to use force: if True, override discovery from Dockerfile ''' converter = self._get_converter(convert_to) return converter(runscript=runscript, force=force)
def convert(self, convert_to=None, runscript="/bin/bash", force=False)
This is a convenience function for the user to easily call to get the most likely desired result, conversion to the opposite format. We choose the selection based on the recipe name - meaning that we perform conversion with default based on recipe name. If the recipe object is DockerRecipe, we convert to Singularity. If the recipe object is SingularityRecipe, we convert to Docker. The user can override this by setting the variable convert_to Parameters ========== convert_to: can be manually forced (docker or singularity) runscript: default runscript (entrypoint) to use force: if True, override discovery from Dockerfile
11.006838
1.34457
8.186142
'''see convert and save. This is a helper function that returns the proper conversion function, but doesn't call it. We do this so that in the case of convert, we do the conversion and return a string. In the case of save, we save the recipe to file for the user. Parameters ========== convert_to: a string either docker or singularity, if a different Returns ======= converter: the function to do the conversion ''' conversion = self._get_conversion_type(convert_to) # Perform conversion if conversion == "singularity": return self.docker2singularity return self.singularity2docker
def _get_converter(self, convert_to=None)
see convert and save. This is a helper function that returns the proper conversion function, but doesn't call it. We do this so that in the case of convert, we do the conversion and return a string. In the case of save, we save the recipe to file for the user. Parameters ========== convert_to: a string either docker or singularity, if a different Returns ======= converter: the function to do the conversion
10.804603
1.999923
5.402511
'''a helper function to return a conversion temporary output file based on kind of conversion Parameters ========== convert_to: a string either docker or singularity, if a different ''' conversion = self._get_conversion_type(convert_to) prefix = "Singularity" if conversion == "docker": prefix = "Dockerfile" suffix = next(tempfile._get_candidate_names()) return "%s.%s" %(prefix, suffix)
def _get_conversion_outfile(self, convert_to=None)
a helper function to return a conversion temporary output file based on kind of conversion Parameters ========== convert_to: a string either docker or singularity, if a different
8.571394
3.527211
2.430077
'''a helper function to return the conversion type based on user preference and input recipe. Parameters ========== convert_to: a string either docker or singularity (default None) ''' acceptable = ['singularity', 'docker'] # Default is to convert to opposite kind conversion = "singularity" if self.name == "singularity": conversion = "docker" # Unless the user asks for a specific type if convert_to is not None and convert_to in acceptable: conversion = convert_to return conversion
def _get_conversion_type(self, convert_to=None)
a helper function to return the conversion type based on user preference and input recipe. Parameters ========== convert_to: a string either docker or singularity (default None)
8.084306
3.621956
2.232028
'''write a script with some lines content to path in the image. This is done by way of adding echo statements to the install section. Parameters ========== path: the path to the file to write lines: the lines to echo to the file chmod: If true, change permission to make u+x ''' if len(lines) > 0: lastline = lines.pop() for line in lines: self.install.append('echo "%s" >> %s' %path) self.install.append(lastline) if chmod is True: self.install.append('chmod u+x %s' %path)
def _write_script(path, lines, chmod=True)
write a script with some lines content to path in the image. This is done by way of adding echo statements to the install section. Parameters ========== path: the path to the file to write lines: the lines to echo to the file chmod: If true, change permission to make u+x
6.952014
2.36304
2.941978
''' get the state of an OciImage, if it exists. The optional states that can be returned are created, running, stopped or (not existing). Equivalent command line example: singularity oci state <container_ID> Parameters ========== container_id: the id to get the state of. sudo: Add sudo to the command. If the container was created by root, you need sudo to interact and get its state. sync_socket: the path to the unix socket for state synchronization Returns ======= state: a parsed json of the container state, if exists. If the container is not found, None is returned. ''' sudo = self._get_sudo(sudo) container_id = self.get_container_id(container_id) # singularity oci state cmd = self._init_command('state') if sync_socket != None: cmd = cmd + ['--sync-socket', sync_socket] # Finally, add the container_id cmd.append(container_id) # Get the instance state result = self._run_command(cmd, sudo=sudo, quiet=True) if result != None: # If successful, a string is returned to parse if isinstance(result, str): return json.loads(result)
def state(self, container_id=None, sudo=None, sync_socket=None)
get the state of an OciImage, if it exists. The optional states that can be returned are created, running, stopped or (not existing). Equivalent command line example: singularity oci state <container_ID> Parameters ========== container_id: the id to get the state of. sudo: Add sudo to the command. If the container was created by root, you need sudo to interact and get its state. sync_socket: the path to the unix socket for state synchronization Returns ======= state: a parsed json of the container state, if exists. If the container is not found, None is returned.
6.00534
1.989121
3.019093
''' A generic state command to wrap pause, resume, kill, etc., where the only difference is the command. This function will be unwrapped if the child functions get more complicated (with additional arguments). Equivalent command line example: singularity oci <command> <container_ID> Parameters ========== container_id: the id to start. command: one of start, resume, pause, kill, defaults to start. sudo: Add sudo to the command. If the container was created by root, you need sudo to interact and get its state. Returns ======= return_code: the return code to indicate if the container was started. ''' sudo = self._get_sudo(sudo) container_id = self.get_container_id(container_id) # singularity oci state cmd = self._init_command(command) # Finally, add the container_id cmd.append(container_id) # Run the command, return return code return self._run_and_return(cmd, sudo)
def _state_command(self, container_id=None, command='start', sudo=None)
A generic state command to wrap pause, resume, kill, etc., where the only difference is the command. This function will be unwrapped if the child functions get more complicated (with additional arguments). Equivalent command line example: singularity oci <command> <container_ID> Parameters ========== container_id: the id to start. command: one of start, resume, pause, kill, defaults to start. sudo: Add sudo to the command. If the container was created by root, you need sudo to interact and get its state. Returns ======= return_code: the return code to indicate if the container was started.
8.520568
1.835788
4.641368
''' stop (kill) a started OciImage container, if it exists Equivalent command line example: singularity oci kill <container_ID> Parameters ========== container_id: the id to stop. signal: signal sent to the container (default SIGTERM) sudo: Add sudo to the command. If the container was created by root, you need sudo to interact and get its state. Returns ======= return_code: the return code to indicate if the container was killed. ''' sudo = self._get_sudo(sudo) container_id = self.get_container_id(container_id) # singularity oci state cmd = self._init_command('kill') # Finally, add the container_id cmd.append(container_id) # Add the signal, if defined if signal != None: cmd = cmd + ['--signal', signal] # Run the command, return return code return self._run_and_return(cmd, sudo)
def kill(self, container_id=None, sudo=None, signal=None)
stop (kill) a started OciImage container, if it exists Equivalent command line example: singularity oci kill <container_ID> Parameters ========== container_id: the id to stop. signal: signal sent to the container (default SIGTERM) sudo: Add sudo to the command. If the container was created by root, you need sudo to interact and get its state. Returns ======= return_code: the return code to indicate if the container was killed.
6.846856
2.272945
3.012328
''' resume a stopped OciImage container, if it exists Equivalent command line example: singularity oci resume <container_ID> Parameters ========== container_id: the id to stop. sudo: Add sudo to the command. If the container was created by root, you need sudo to interact and get its state. Returns ======= return_code: the return code to indicate if the container was resumed. ''' return self._state_command(container_id, command='resume', sudo=sudo)
def resume(self, container_id=None, sudo=None)
resume a stopped OciImage container, if it exists Equivalent command line example: singularity oci resume <container_ID> Parameters ========== container_id: the id to stop. sudo: Add sudo to the command. If the container was created by root, you need sudo to interact and get its state. Returns ======= return_code: the return code to indicate if the container was resumed.
11.857185
1.916902
6.185598
''' pause a running OciImage container, if it exists Equivalent command line example: singularity oci pause <container_ID> Parameters ========== container_id: the id to stop. sudo: Add sudo to the command. If the container was created by root, you need sudo to interact and get its state. Returns ======= return_code: the return code to indicate if the container was paused. ''' return self._state_command(container_id, command='pause', sudo=sudo)
def pause(self, container_id=None, sudo=None)
pause a running OciImage container, if it exists Equivalent command line example: singularity oci pause <container_ID> Parameters ========== container_id: the id to stop. sudo: Add sudo to the command. If the container was created by root, you need sudo to interact and get its state. Returns ======= return_code: the return code to indicate if the container was paused.
12.156063
1.925827
6.312128
'''stop ALL instances. This command is only added to the command group as it doesn't make sense to call from a single instance Parameters ========== sudo: if the command should be done with sudo (exposes different set of instances) ''' from spython.utils import run_command, check_install check_install() subgroup = 'instance.stop' if 'version 3' in self.version(): subgroup = ["instance", "stop"] cmd = self._init_command(subgroup) cmd = cmd + ['--all'] output = run_command(cmd, sudo=sudo, quiet=quiet) if output['return_code'] != 0: message = '%s : return code %s' %(output['message'], output['return_code']) bot.error(message) return output['return_code'] return output['return_code']
def stopall(self, sudo=False, quiet=True)
stop ALL instances. This command is only added to the command group as it doesn't make sense to call from a single instance Parameters ========== sudo: if the command should be done with sudo (exposes different set of instances)
7.846097
4.344526
1.805973
'''set the logging level based on the environment Parameters ========== quiet: boolean if True, set to quiet. Gets overriden by environment setting, and only exists to define default ''' if os.environ.get('MESSAGELEVEL') == "QUIET": quiet = True self.quiet = quiet
def init_level(self, quiet=False)
set the logging level based on the environment Parameters ========== quiet: boolean if True, set to quiet. Gets overriden by environment setting, and only exists to define default
16.14444
3.790614
4.259057
'''print will print the output, given that quiet is not True. This function also serves to convert output in bytes to utf-8 Parameters ========== output: the string to print quiet: a runtime variable to over-ride the default. ''' if isinstance(output,bytes): output = output.decode('utf-8') if self.quiet is False and quiet is False: print(output)
def println(self, output, quiet=False)
print will print the output, given that quiet is not True. This function also serves to convert output in bytes to utf-8 Parameters ========== output: the string to print quiet: a runtime variable to over-ride the default.
8.264141
2.167545
3.812674
'''help prints the general function help, or help for a specific command Parameters ========== command: the command to get help for, if none, prints general help ''' from spython.utils import check_install check_install() cmd = ['singularity','--help'] if command != None: cmd.append(command) help = self._run_command(cmd) return help
def help(self, command=None)
help prints the general function help, or help for a specific command Parameters ========== command: the command to get help for, if none, prints general help
8.810743
4.811493
1.831187
''' The Instance client holds the Singularity Instance command group The levels of verbosity (debug and quiet) are passed from the main client via the environment variable MESSAGELEVEL. ''' from spython.instance import Instance from spython.main.base.logger import println from spython.main.instances import instances from spython.utils import run_command as run_cmd # run_command uses run_cmd, but wraps to catch error from spython.main.base.command import ( init_command, run_command ) from spython.main.base.generate import RobotNamer from .start import start from .stop import stop Instance.RobotNamer = RobotNamer() Instance._init_command = init_command Instance.run_command = run_cmd Instance._run_command = run_command Instance._list = instances # list command is used to get metadata Instance._println = println Instance.start = start # intended to be called on init, not by user Instance.stop = stop # Give an instance the ability to breed :) Instance.instance = Instance return Instance
def generate_instance_commands()
The Instance client holds the Singularity Instance command group The levels of verbosity (debug and quiet) are passed from the main client via the environment variable MESSAGELEVEL.
11.004177
6.816246
1.614404
'''compress will (properly) compress an image''' if os.path.exists(image_path): compressed_image = "%s.gz" %image_path os.system('gzip -c -6 %s > %s' %(image_path, compressed_image)) return compressed_image bot.exit("Cannot find image %s" %image_path)
def compress(self, image_path)
compress will (properly) compress an image
5.180691
4.382695
1.182079
'''decompress will (properly) decompress an image''' if not os.path.exists(image_path): bot.exit("Cannot find image %s" %image_path) extracted_file = image_path.replace('.gz','') cmd = ['gzip','-d','-f', image_path] result = self.run_command(cmd, quiet=quiet) # exits if return code != 0 return extracted_file
def decompress(self, image_path, quiet=True)
decompress will (properly) decompress an image
6.140942
5.350932
1.14764
'''generate a Robot Name for the instance to use, if the user doesn't supply one. ''' # If no name provided, use robot name if name == None: name = self.RobotNamer.generate() self.name = name.replace('-','_')
def generate_name(self, name=None)
generate a Robot Name for the instance to use, if the user doesn't supply one.
11.432945
4.533828
2.521698
'''Extract any additional attributes to hold with the instance from kwargs ''' # If not given metadata, use instance.list to get it for container if kwargs == None and hasattr(self, 'name'): kwargs = self._list(self.name, quiet=True, return_json=True) # Add acceptable arguments for arg in ['pid', 'name']: # Skip over non-iterables: if arg in kwargs: setattr(self, arg, kwargs[arg]) if "image" in kwargs: self._image = kwargs['image'] elif "container_image" in kwargs: self._image = kwargs['container_image']
def _update_metadata(self, kwargs=None)
Extract any additional attributes to hold with the instance from kwargs
8.497512
6.079312
1.397775
''' run will run the container, with or withour arguments (which should be provided in a list) Parameters ========== image: full path to singularity image args: args to include with the run app: if not None, execute a command in context of an app writable: This option makes the file system accessible as read/write contain: This option disables the automatic sharing of writable filesystems on your host bind: list or single string of bind paths. This option allows you to map directories on your host system to directories within your container using bind mounts stream: if True, return <generator> for the user to run nv: if True, load Nvidia Drivers in runtime (default False) return_result: if True, return entire json object with return code and message result (default is False) ''' from spython.utils import check_install check_install() cmd = self._init_command('run') # nv option leverages any GPU cards if nv is True: cmd += ['--nv'] # No image provided, default to use the client's loaded image if image is None: image = self._get_uri() # If an instance is provided, grab it's name if isinstance(image, self.instance): image = image.get_uri() # Does the user want to use bind paths option? if bind is not None: cmd += self._generate_bind_list(bind) # Does the user want to run an app? if app is not None: cmd = cmd + ['--app', app] cmd = cmd + [image] # Conditions for needing sudo if writable is True: sudo = True if args is not None: if not isinstance(args, list): args = args.split(' ') cmd = cmd + args if stream is False: result = self._run_command(cmd, sudo=sudo, return_result=return_result) else: return stream_command(cmd, sudo=sudo) # If the user wants the raw result object if return_result: return result # Otherwise, we parse the result if it was successful if result: result = result.strip('\n') try: result = json.loads(result) except: pass return result
def run(self, image = None, args = None, app = None, sudo = False, writable = False, contain = False, bind = None, stream = False, nv = False, return_result=False)
run will run the container, with or withour arguments (which should be provided in a list) Parameters ========== image: full path to singularity image args: args to include with the run app: if not None, execute a command in context of an app writable: This option makes the file system accessible as read/write contain: This option disables the automatic sharing of writable filesystems on your host bind: list or single string of bind paths. This option allows you to map directories on your host system to directories within your container using bind mounts stream: if True, return <generator> for the user to run nv: if True, load Nvidia Drivers in runtime (default False) return_result: if True, return entire json object with return code and message result (default is False)
6.427607
2.797756
2.297415
'''create an OCI bundle from SIF image Parameters ========== image: the container (sif) to mount ''' return self._state_command(image, command="mount", sudo=sudo)
def mount(self, image, sudo=None)
create an OCI bundle from SIF image Parameters ========== image: the container (sif) to mount
19.040077
5.409252
3.519909
'''This function serves as a wrapper around the DockerRecipe and SingularityRecipe converters. We can either save to file if args.outfile is defined, or print to the console if not. ''' from spython.main.parse import ( DockerRecipe, SingularityRecipe ) # We need something to work with if not args.files: parser.print_help() sys.exit(1) # Get the user specified input and output files outfile = None if len(args.files) > 1: outfile = args.files[1] # Choose the recipe parser parser = SingularityRecipe if args.input == "docker": parser = DockerRecipe elif args.input == "singularity": parser = SingularityRecipe(args.files[0]) else: if "dockerfile" in args.files[0].lower(): parser = DockerRecipe # Initialize the chosen parser parser = parser(args.files[0]) # By default, discover entrypoint / cmd from Dockerfile entrypoint = "/bin/bash" force = False if args.entrypoint is not None: entrypoint = args.entrypoint force = True # If the user specifies an output file, save to it if outfile is not None: parser.save(outfile, runscript=entrypoint, force=force) # Otherwise, convert and print to screen else: recipe = parser.convert(runscript=entrypoint, force=True) print(recipe)
def main(args, options, parser)
This function serves as a wrapper around the DockerRecipe and SingularityRecipe converters. We can either save to file if args.outfile is defined, or print to the console if not.
5.253099
3.666821
1.432603
''' replace the command name from the group, alert the user of content, and clean up empty spaces ''' bot.debug('[in] %s' % line) # Replace ACTION at beginning line = re.sub('^%s' % action, '', line) # Handle continuation lines without ACTION by padding with leading space line = " " + line # Split into components return [x for x in self._split_line(line) if x not in ['', None]]
def _setup(self, action, line)
replace the command name from the group, alert the user of content, and clean up empty spaces
15.247143
7.318421
2.083392
''' get the FROM container image name from a FROM line! Parameters ========== line: the line from the recipe file to parse for FROM ''' fromHeader = self._setup('FROM', line) # Singularity does not support AS level self.fromHeader = re.sub("AS .+", "", fromHeader[0], flags=re.I) if "scratch" in self.fromHeader: bot.warning('scratch is no longer available on Docker Hub.') bot.debug('FROM %s' %self.fromHeader)
def _from(self, line)
get the FROM container image name from a FROM line! Parameters ========== line: the line from the recipe file to parse for FROM
14.945854
8.159029
1.831818
''' everything from RUN goes into the install list Parameters ========== line: the line from the recipe file to parse for FROM ''' line = self._setup('RUN', line) self.install += line
def _run(self, line)
everything from RUN goes into the install list Parameters ========== line: the line from the recipe file to parse for FROM
33.662922
6.41318
5.249022
'''singularity doesn't have support for ARG, so instead will issue a warning to the console for the user to export the variable with SINGULARITY prefixed at build. Parameters ========== line: the line from the recipe file to parse for ARG ''' line = self._setup('ARG', line) bot.warning("ARG is not supported for Singularity! To get %s" %line[0]) bot.warning("in the container, on host export SINGULARITY_%s" %line[0])
def _arg(self, line)
singularity doesn't have support for ARG, so instead will issue a warning to the console for the user to export the variable with SINGULARITY prefixed at build. Parameters ========== line: the line from the recipe file to parse for ARG
24.033785
5.172399
4.646545
'''env will parse a line that beings with ENV, indicative of one or more environment variables. Parameters ========== line: the line from the recipe file to parse for ADD ''' line = self._setup('ENV', line) # Extract environment (list) from the line environ = parse_env(line) # Add to global environment, run during install self.install += environ # Also define for global environment self.environ += environ
def _env(self, line)
env will parse a line that beings with ENV, indicative of one or more environment variables. Parameters ========== line: the line from the recipe file to parse for ADD
22.261522
8.007045
2.780242
'''parse_add will copy multiple files from one location to another. This likely will need tweaking, as the files might need to be mounted from some location before adding to the image. The add command is done for an entire directory. It is also possible to have more than one file copied to a destination: https://docs.docker.com/engine/reference/builder/#copy e.g.: <src> <src> <dest>/ ''' lines = self._setup('COPY', lines) for line in lines: values = line.split(" ") topath = values.pop() for frompath in values: self._add_files(frompath, topath)
def _copy(self, lines)
parse_add will copy multiple files from one location to another. This likely will need tweaking, as the files might need to be mounted from some location before adding to the image. The add command is done for an entire directory. It is also possible to have more than one file copied to a destination: https://docs.docker.com/engine/reference/builder/#copy e.g.: <src> <src> <dest>/
11.129548
2.214906
5.024841
'''Add can also handle https, and compressed files. Parameters ========== line: the line from the recipe file to parse for ADD ''' lines = self._setup('ADD', lines) for line in lines: values = line.split(" ") frompath = values.pop(0) # Custom parsing for frompath # If it's a web address, add to install routine to get if frompath.startswith('http'): for topath in values: self._parse_http(frompath, topath) # Add the file, and decompress in install elif re.search("[.](gz|gzip|bz2|xz)$", frompath.strip()): for topath in values: self._parse_archive(frompath, topath) # Just add the files else: for topath in values: self._add_files(frompath, topath)
def _add(self, lines)
Add can also handle https, and compressed files. Parameters ========== line: the line from the recipe file to parse for ADD
7.355619
4.738018
1.552468
'''add files is the underlying function called to add files to the list, whether originally called from the functions to parse archives, or https. We make sure that any local references are changed to actual file locations before adding to the files list. Parameters ========== source: the source dest: the destiation ''' # Create data structure to iterate over paths = {'source': source, 'dest': dest} for pathtype, path in paths.items(): if path == ".": paths[pathtype] = os.getcwd() # Warning if doesn't exist if not os.path.exists(path): bot.warning("%s doesn't exist, ensure exists for build" %path) # The pair is added to the files as a list self.files.append([paths['source'], paths['dest']])
def _add_files(self, source, dest)
add files is the underlying function called to add files to the list, whether originally called from the functions to parse archives, or https. We make sure that any local references are changed to actual file locations before adding to the files list. Parameters ========== source: the source dest: the destiation
11.924055
3.888042
3.066853
'''will get the filename of an http address, and return a statement to download it to some location Parameters ========== url: the source url to retrieve with curl dest: the destination folder to put it in the image ''' file_name = os.path.basename(url) download_path = "%s/%s" %(dest, file_name) command = "curl %s -o %s" %(url, download_path) self.install.append(command)
def _parse_http(self, url, dest)
will get the filename of an http address, and return a statement to download it to some location Parameters ========== url: the source url to retrieve with curl dest: the destination folder to put it in the image
7.682027
2.253438
3.409026
'''parse_targz will add a line to the install script to extract a targz to a location, and also add it to the files. Parameters ========== targz: the targz to extract dest: the location to extract it to ''' # Add command to extract it self.install.append("tar -zvf %s %s" %(targz, dest)) # Ensure added to container files return self._add_files(targz, dest)
def _parse_archive(self, targz, dest)
parse_targz will add a line to the install script to extract a targz to a location, and also add it to the files. Parameters ========== targz: the targz to extract dest: the location to extract it to
8.904863
3.357142
2.652513
'''the default action assumes a line that is either a command (a continuation of a previous, for example) or a comment. Parameters ========== line: the line from the recipe file to parse to INSTALL ''' if line.strip().startswith('#'): return self._comment(line) self.install.append(line)
def _default(self, line)
the default action assumes a line that is either a command (a continuation of a previous, for example) or a comment. Parameters ========== line: the line from the recipe file to parse to INSTALL
14.321884
2.505371
5.716472
'''We don't have logic for volume for Singularity, so we add as a comment in the install, and a metadata value for the recipe object Parameters ========== line: the line from the recipe file to parse to INSTALL ''' volumes = self._setup('VOLUME', line) if len(volumes) > 0: self.volumes += volumes return self._comment("# %s" %line)
def _volume(self, line)
We don't have logic for volume for Singularity, so we add as a comment in the install, and a metadata value for the recipe object Parameters ========== line: the line from the recipe file to parse to INSTALL
19.756613
3.36271
5.875206
'''Again, just add to metadata, and comment in install. Parameters ========== line: the line from the recipe file to parse to INSTALL ''' ports = self._setup('EXPOSE', line) if len(ports) > 0: self.ports += ports return self._comment("# %s" %line)
def _expose(self, line)
Again, just add to metadata, and comment in install. Parameters ========== line: the line from the recipe file to parse to INSTALL
23.696516
5.434477
4.360404
'''A Docker WORKDIR command simply implies to cd to that location Parameters ========== line: the line from the recipe file to parse for WORKDIR ''' workdir = self._setup('WORKDIR', line) line = "cd %s" %(''.join(workdir)) self.install.append(line)
def _workdir(self, line)
A Docker WORKDIR command simply implies to cd to that location Parameters ========== line: the line from the recipe file to parse for WORKDIR
15.990726
4.469997
3.577346
'''_label will parse a Dockerfile label Parameters ========== line: the line from the recipe file to parse for CMD ''' label = self._setup('LABEL', line) self.labels += [ label ]
def _label(self, line)
_label will parse a Dockerfile label Parameters ========== line: the line from the recipe file to parse for CMD
26.747055
6.035772
4.431422
'''mapping will take the command from a Dockerfile and return a map function to add it to the appropriate place. Any lines that don't cleanly map are assumed to be comments. Parameters ========== line: the list that has been parsed into parts with _split_line parser: the previously used parser, for context Returns ======= function: to map a line to its command group ''' # Split the command into cleanly the command and rest if not isinstance(line, list): line = self._split_line(line) # No line we will give function to handle empty line if len(line) == 0: return None cmd = line[0].upper() mapping = {"ADD": self._add, "ARG": self._arg, "COPY": self._copy, "CMD": self._cmd, "ENTRYPOINT": self._entry, "ENV": self._env, "EXPOSE": self._expose, "FROM": self._from, "HEALTHCHECK": self._test, "RUN": self._run, "WORKDIR": self._workdir, "MAINTAINER": self._label, "VOLUME": self._volume, "LABEL": self._label} # If it's a command line, return correct function if cmd in mapping: return mapping[cmd] # If it's a continued line, return previous cleaned = self._clean_line(line[-1]) previous = self._clean_line(previous) # if we are continuing from last if cleaned.endswith('\\') and parser or previous.endswith('\\'): return parser return self._default
def _get_mapping(self, line, parser=None, previous=None)
mapping will take the command from a Dockerfile and return a map function to add it to the appropriate place. Any lines that don't cleanly map are assumed to be comments. Parameters ========== line: the list that has been parsed into parts with _split_line parser: the previously used parser, for context Returns ======= function: to map a line to its command group
5.640089
2.916389
1.933929
'''parse is the base function for parsing the Dockerfile, and extracting elements into the correct data structures. Everything is parsed into lists or dictionaries that can be assembled again on demand. Environment: Since Docker also exports environment as we go, we add environment to the environment section and install Labels: include anything that is a LABEL, ARG, or (deprecated) maintainer. Add/Copy: are treated the same ''' parser = None previous = None for line in self.lines: parser = self._get_mapping(line, parser, previous) # Parse it, if appropriate if parser: parser(line) previous = line
def _parse(self)
parse is the base function for parsing the Dockerfile, and extracting elements into the correct data structures. Everything is parsed into lists or dictionaries that can be assembled again on demand. Environment: Since Docker also exports environment as we go, we add environment to the environment section and install Labels: include anything that is a LABEL, ARG, or (deprecated) maintainer. Add/Copy: are treated the same
27.319975
2.401771
11.374931
'''get the uri of an image, or the string (optional) that appears before ://. Optional. If none found, returns '' ''' image = image or '' uri = '' match = re.match("^(?P<uri>.+)://", image) if match: uri = match.group('uri') return uri
def get_uri(self, image)
get the uri of an image, or the string (optional) that appears before ://. Optional. If none found, returns ''
10.08844
2.801
3.601727
'''remove_image_uri will return just the image name. this will also remove all spaces from the uri. ''' image = image or '' uri = self.get_uri(image) or '' image = image.replace('%s://' %uri,'', 1) return image.strip('-').rstrip('/')
def remove_uri(self, image)
remove_image_uri will return just the image name. this will also remove all spaces from the uri.
10.39722
4.991913
2.082813
''' simply split the uri from the image. Singularity handles parsing of registry, namespace, image. Parameters ========== image: the complete image uri to load (e.g., docker://ubuntu) ''' self._image = image self.uri = self.get_uri(image) self.image = self.remove_uri(image)
def parse_image_name(self, image)
simply split the uri from the image. Singularity handles parsing of registry, namespace, image. Parameters ========== image: the complete image uri to load (e.g., docker://ubuntu)
13.964445
2.63842
5.292731
'''return an md5 hash of the file based on a criteria level. This is intended to give the file a reasonable version. This only is useful for actual image files. Parameters ========== image: the image path to get hash for (first priority). Second priority is image path saved with image object, if exists. ''' hasher = hashlib.md5() image = image or self.image if os.path.exists(image): with open(image, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hasher.update(chunk) return hasher.hexdigest() bot.warning('%s does not exist.' %image)
def get_hash(self, image=None)
return an md5 hash of the file based on a criteria level. This is intended to give the file a reasonable version. This only is useful for actual image files. Parameters ========== image: the image path to get hash for (first priority). Second priority is image path saved with image object, if exists.
7.671464
2.047613
3.74654
''' return list of SCIF apps in image. The Singularity software serves a scientific filesystem integration that will install apps to /scif/apps and associated data to /scif/data. For more information about SCIF, see https://sci-f.github.io Parameters ========== full_path: if True, return relative to scif base folder image_path: full path to the image ''' from spython.utils import check_install check_install() # No image provided, default to use the client's loaded image if image is None: image = self._get_uri() cmd = self._init_command('apps') + [ image ] output = self._run_command(cmd) if full_path is True: root = '/scif/apps/' if len(output) > 0: output = ''.join(output).split('\n') output = ['%s%s' %(root,x) for x in output if x] return output
def apps(self, image=None, full_path=False, root='')
return list of SCIF apps in image. The Singularity software serves a scientific filesystem integration that will install apps to /scif/apps and associated data to /scif/data. For more information about SCIF, see https://sci-f.github.io Parameters ========== full_path: if True, return relative to scif base folder image_path: full path to the image
7.753265
2.721048
2.849367
'''create will create a a new image Parameters ========== image_path: full path to image size: image sizein MiB, default is 1024MiB filesystem: supported file systems ext3/ext4 (ext[2/3]: default ext3 ''' from spython.utils import check_install check_install() cmd = self.init_command('image.create') cmd = cmd + ['--size', str(size), image_path ] output = self.run_command(cmd,sudo=sudo) self.println(output) if not os.path.exists(image_path): bot.exit("Could not create image %s" %image_path) return image_path
def create(self,image_path, size=1024, sudo=False)
create will create a a new image Parameters ========== image_path: full path to image size: image sizein MiB, default is 1024MiB filesystem: supported file systems ext3/ext4 (ext[2/3]: default ext3
7.807512
3.678894
2.122244
'''check_install will attempt to run the singularity command, and return True if installed. The command line utils will not run without this check. ''' cmd = [software, '--version'] found = False try: version = run_command(cmd, quiet=True) except: # FileNotFoundError return found if version is not None: if version['return_code'] == 0: found = True if quiet is False: version = version['message'] bot.info("Found %s version %s" % (software.upper(), version)) return found
def check_install(software='singularity', quiet=True)
check_install will attempt to run the singularity command, and return True if installed. The command line utils will not run without this check.
6.380969
3.620995
1.762214
'''get the singularity client version. Useful in the case that functionality has changed, etc. Can be "hacked" if needed by exporting SPYTHON_SINGULARITY_VERSION, which is checked before checking on the command line. ''' version = os.environ.get('SPYTHON_SINGULARITY_VERSION', "") if version == "": try: version = run_command(["singularity", '--version'], quiet=True) except: # FileNotFoundError return version if version['return_code'] == 0: if len(version['message']) > 0: version = version['message'][0].strip('\n') return version
def get_singularity_version()
get the singularity client version. Useful in the case that functionality has changed, etc. Can be "hacked" if needed by exporting SPYTHON_SINGULARITY_VERSION, which is checked before checking on the command line.
7.237332
2.657291
2.723575
'''stream a command (yield) back to the user, as each line is available. # Example usage: results = [] for line in stream_command(cmd): print(line, end="") results.append(line) Parameters ========== cmd: the command to send, should be a list for subprocess no_newline_regexp: the regular expression to determine skipping a newline. Defaults to finding Progress ''' if sudo is True: cmd = ['sudo'] + cmd process = subprocess.Popen(cmd, stdout = subprocess.PIPE, universal_newlines = True) for line in iter(process.stdout.readline, ""): if not re.search(no_newline_regexp, line): yield line process.stdout.close() return_code = process.wait() if return_code: raise subprocess.CalledProcessError(return_code, cmd)
def stream_command(cmd, no_newline_regexp="Progess", sudo=False)
stream a command (yield) back to the user, as each line is available. # Example usage: results = [] for line in stream_command(cmd): print(line, end="") results.append(line) Parameters ========== cmd: the command to send, should be a list for subprocess no_newline_regexp: the regular expression to determine skipping a newline. Defaults to finding Progress
3.657169
1.637302
2.233657
'''run_command uses subprocess to send a command to the terminal. If capture is True, we use the parent stdout, so the progress bar (and other commands of interest) are piped to the user. This means we don't return the output to parse. Parameters ========== cmd: the command to send, should be a list for subprocess sudo: if needed, add to start of command no_newline_regexp: the regular expression to determine skipping a newline. Defaults to finding Progress capture: if True, don't set stdout and have it go to console. This option can print a progress bar, but won't return the lines as output. ''' if sudo is True: cmd = ['sudo'] + cmd stdout = None if capture is True: stdout = subprocess.PIPE # Use the parent stdout and stderr process = subprocess.Popen(cmd, stderr = subprocess.PIPE, stdout = stdout) lines = () found_match = False for line in process.communicate(): if line: if isinstance(line, bytes): line = line.decode('utf-8') lines = lines + (line,) if re.search(no_newline_regexp, line) and found_match is True: if quiet is False: sys.stdout.write(line) found_match = True else: if quiet is False: sys.stdout.write(line) print(line.rstrip()) found_match = False output = {'message': lines, 'return_code': process.returncode } return output
def run_command(cmd, sudo=False, capture=True, no_newline_regexp="Progess", quiet=False)
run_command uses subprocess to send a command to the terminal. If capture is True, we use the parent stdout, so the progress bar (and other commands of interest) are piped to the user. This means we don't return the output to parse. Parameters ========== cmd: the command to send, should be a list for subprocess sudo: if needed, add to start of command no_newline_regexp: the regular expression to determine skipping a newline. Defaults to finding Progress capture: if True, don't set stdout and have it go to console. This option can print a progress bar, but won't return the lines as output.
5.09929
1.897388
2.687531
'''get_requirements reads in requirements and versions from the lookup obtained with get_lookup''' if lookup == None: lookup = get_lookup() install_requires = [] for module in lookup['INSTALL_REQUIRES']: module_name = module[0] module_meta = module[1] if "exact_version" in module_meta: dependency = "%s==%s" %(module_name,module_meta['exact_version']) elif "min_version" in module_meta: if module_meta['min_version'] == None: dependency = module_name else: dependency = "%s>=%s" %(module_name,module_meta['min_version']) install_requires.append(dependency) return install_requires
def get_requirements(lookup=None)
get_requirements reads in requirements and versions from the lookup obtained with get_lookup
2.959792
2.318492
1.276602
'''load an image, either an actual path on the filesystem or a uri. Parameters ========== image: the image path or uri to load (e.g., docker://ubuntu ''' from spython.image import Image from spython.instance import Instance self.simage = Image(image) if image is not None: if image.startswith('instance://'): self.simage = Instance(image) bot.info(self.simage)
def load(self, image=None)
load an image, either an actual path on the filesystem or a uri. Parameters ========== image: the image path or uri to load (e.g., docker://ubuntu
9.28265
4.77056
1.94582
'''set an environment variable for Singularity Parameters ========== variable: the variable to set value: the value to set ''' os.environ[variable] = value os.putenv(variable, value) bot.debug('%s set to %s' % (variable, value))
def setenv(self, variable, value)
set an environment variable for Singularity Parameters ========== variable: the variable to set value: the value to set
5.092955
3.513938
1.449358
''' check if the loaded image object (self.simage) has an associated uri return if yes, None if not. ''' if hasattr(self, 'simage'): if self.simage is not None: if self.simage.image not in ['', None]: # Concatenates the <uri>://<image> return str(self.simage)
def get_uri(self)
check if the loaded image object (self.simage) has an associated uri return if yes, None if not.
9.783039
4.32499
2.261979
'''parse_verbosity will take an argument object, and return the args passed (from a dictionary) to a list Parameters ========== args: the argparse argument objects ''' flags = [] if args.silent is True: flags.append('--silent') elif args.quiet is True: flags.append('--quiet') elif args.debug is True: flags.append('--debug') elif args.verbose is True: flags.append('-' + 'v' * args.verbose) return flags
def parse_verbosity(self, args)
parse_verbosity will take an argument object, and return the args passed (from a dictionary) to a list Parameters ========== args: the argparse argument objects
5.609828
2.560637
2.190794
''' The oci command group will allow interaction with an image using OCI commands. ''' from spython.oci import OciImage from spython.main.base.logger import println # run_command uses run_cmd, but wraps to catch error from spython.main.base.command import ( run_command, send_command ) from spython.main.base.generate import RobotNamer # Oci Command Groups from .mounts import ( mount, umount ) from .states import ( kill, state, start, pause, resume, _state_command ) from .actions import ( attach, create, delete, execute, run, _run, update ) # Oci Commands OciImage.start = start OciImage.mount = mount OciImage.umount = umount OciImage.state = state OciImage.resume = resume OciImage.pause = pause OciImage.attach = attach OciImage.create = create OciImage.delete = delete OciImage.execute = execute OciImage.update = update OciImage.kill = kill OciImage.run = run OciImage._run = _run OciImage._state_command = _state_command OciImage.RobotNamer = RobotNamer() OciImage._send_command = send_command # send and disregard stderr, stdout OciImage._run_command = run_command OciImage._println = println OciImage.OciImage = OciImage return OciImage
def generate_oci_commands()
The oci command group will allow interaction with an image using OCI commands.
4.65195
4.115308
1.130401
'''convert a Singularity recipe to a (best estimated) Dockerfile''' recipe = [ "FROM %s" %self.fromHeader ] # Comments go up front! recipe += self.comments # First add files, labels recipe += write_lines('ADD', self.files) recipe += write_lines('LABEL', self.labels) recipe += write_lines('ENV', self.environ) # Install routine is added as RUN commands recipe += write_lines('RUN', self.install) # Take preference for user, entrypoint, command, then default runscript = self._create_runscript(runscript, force) recipe.append('CMD %s' %runscript) if self.test is not None: recipe.append(write_lines('HEALTHCHECK', self.test)) # Clean up extra white spaces return '\n'.join(recipe).replace('\n\n','\n')
def singularity2docker(self, runscript="/bin/bash", force=False)
convert a Singularity recipe to a (best estimated) Dockerfile
8.267765
6.979428
1.184591
'''write a list of lines with a header for a section. Parameters ========== lines: one or more lines to write, with header appended ''' result = [] continued = False for line in lines: if continued: result.append(line) else: result.append('%s %s' %(label, line)) continued = False if line.endswith('\\'): continued = True return result
def write_lines(label, lines)
write a list of lines with a header for a section. Parameters ========== lines: one or more lines to write, with header appended
4.982404
2.913193
1.71029
'''create_entrypoint is intended to create a singularity runscript based on a Docker entrypoint or command. We first use the Docker ENTRYPOINT, if defined. If not, we use the CMD. If neither is found, we use function default. Parameters ========== default: set a default entrypoint, if the container does not have an entrypoint or cmd. force: If true, use default and ignore Dockerfile settings ''' entrypoint = default # Only look at Docker if not enforcing default if force is False: if self.entrypoint is not None: entrypoint = ''.join(self.entrypoint) elif self.cmd is not None: entrypoint = ''.join(self.cmd) # Entrypoint should use exec if not entrypoint.startswith('exec'): entrypoint = "exec %s" %entrypoint # Should take input arguments into account if not re.search('"?[$]@"?', entrypoint): entrypoint = '%s "$@"' %entrypoint return entrypoint
def create_runscript(self, default="/bin/bash", force=False)
create_entrypoint is intended to create a singularity runscript based on a Docker entrypoint or command. We first use the Docker ENTRYPOINT, if defined. If not, we use the CMD. If neither is found, we use function default. Parameters ========== default: set a default entrypoint, if the container does not have an entrypoint or cmd. force: If true, use default and ignore Dockerfile settings
7.848205
3.070869
2.555695
'''create a section based on key, value recipe pairs, This is used for files or label Parameters ========== attribute: the name of the data section, either labels or files name: the name to write to the recipe file (e.g., %name). if not defined, the attribute name is used. ''' # Default section name is the same as attribute if name is None: name = attribute # Put a space between sections section = ['\n'] # Only continue if we have the section and it's not empty try: section = getattr(self, attribute) except AttributeError: bot.debug('Recipe does not have section for %s' %attribute) return section # if the section is empty, don't print it if len(section) == 0: return section # Files or Labels if attribute in ['labels', 'files']: return create_keyval_section(section, name) # An environment section needs exports if attribute in ['environ']: return create_env_section(section, name) # Post, Setup return finish_section(section, name)
def create_section(self, attribute, name=None)
create a section based on key, value recipe pairs, This is used for files or label Parameters ========== attribute: the name of the data section, either labels or files name: the name to write to the recipe file (e.g., %name). if not defined, the attribute name is used.
8.03537
4.038916
1.989487
'''finish_section will add the header to a section, to finish the recipe take a custom command or list and return a section. Parameters ========== section: the section content, without a header name: the name of the section for the header ''' if not isinstance(section, list): section = [section] header = ['%' + name ] return header + section
def finish_section(section, name)
finish_section will add the header to a section, to finish the recipe take a custom command or list and return a section. Parameters ========== section: the section content, without a header name: the name of the section for the header
13.856107
2.898001
4.781263
'''create a section based on key, value recipe pairs, This is used for files or label Parameters ========== section: the list of values to return as a parsed list of lines name: the name of the section to write (e.g., files) ''' section = ['%' + name ] for pair in pairs: section.append(' '.join(pair).strip().strip('\\')) return section
def create_keyval_section(pairs, name)
create a section based on key, value recipe pairs, This is used for files or label Parameters ========== section: the list of values to return as a parsed list of lines name: the name of the section to write (e.g., files)
13.839599
2.849583
4.856709
'''environment key value pairs need to be joined by an equal, and exported at the end. Parameters ========== section: the list of values to return as a parsed list of lines name: the name of the section to write (e.g., files) ''' section = ['%' + name ] for pair in pairs: section.append("export %s" %pair) return section
def create_env_section(pairs, name)
environment key value pairs need to be joined by an equal, and exported at the end. Parameters ========== section: the list of values to return as a parsed list of lines name: the name of the section to write (e.g., files)
15.247137
2.925048
5.212611
'''docker2singularity will return a Singularity build recipe based on a the loaded recipe object. It doesn't take any arguments as the recipe object contains the sections, and the calling function determines saving / output logic. ''' recipe = ['Bootstrap: docker'] recipe += [ "From: %s" %self.fromHeader ] # Sections with key value pairs recipe += self._create_section('files') recipe += self._create_section('labels') recipe += self._create_section('install', 'post') recipe += self._create_section('environ', 'environment') # Take preference for user, entrypoint, command, then default runscript = self._create_runscript(runscript, force) recipe += finish_section(runscript, 'runscript') if self.test is not None: recipe += finish_section(self.test, 'test') # Clean up extra white spaces return '\n'.join(recipe).replace('\n\n','\n')
def docker2singularity(self, runscript="/bin/bash", force=False)
docker2singularity will return a Singularity build recipe based on a the loaded recipe object. It doesn't take any arguments as the recipe object contains the sections, and the calling function determines saving / output logic.
10.664465
5.099061
2.091456
return "%s-%s" % (re.sub('[^\w.]', '', datetime.now().isoformat()).replace(".", "Z-"), new_uid(bits))
def new_timestamped_uid(bits=32)
A unique id that begins with an ISO timestamp followed by fractions of seconds and bits of randomness. The advantage of this is it sorts nicely by time, while still being unique. Example: 20150912T084555Z-378465-43vtwbx
8.8853
9.352724
0.950023
if not string or not max_len or len(string) <= max_len: return string elif max_len <= len(indicator): return string[0:max_len] else: return string[0:max_len - len(indicator)] + indicator
def abbreviate_str(string, max_len=80, indicator="...")
Abbreviate a string, adding an indicator like an ellipsis if required.
2.476681
2.189726
1.131046
if not items: return items else: shortened = [abbreviate_str("%s" % item, max_len=item_max_len) for item in items[0:max_items]] if len(items) > max_items: shortened.append(indicator) return joiner.join(shortened)
def abbreviate_list(items, max_items=10, item_max_len=40, joiner=", ", indicator="...")
Abbreviate a list, truncating each element and adding an indicator at the end if the whole list was truncated. Set item_max_len to None or 0 not to truncate items.
2.415026
2.352283
1.026673
if template_str is None: return None else: if transformer is None: transformer = lambda v: v try: # Don't bother iterating items for Python 2+3 compatibility. transformed_value_map = {k: transformer(value_map[k]) for k in value_map} return Template(template_str).substitute(transformed_value_map) except Exception as e: raise ValueError("could not expand variable names in command '%s': %s" % (template_str, e))
def expand_variables(template_str, value_map, transformer=None)
Expand a template string like "blah blah $FOO blah" using given value mapping.
3.614875
3.456297
1.045881
return [expand_variables(item, values) for item in shlex.split(template)]
def shell_expand_to_popen(template, values)
Expand a template like "cp $SOURCE $TARGET/blah" into a list of popen arguments.
6.706645
5.66352
1.184183
if backup_suffix and os.path.exists(path): backup_path = path + backup_suffix # Some messy corner cases need to be handled for existing backups. # TODO: Note if this is a directory, and we do this twice at once, there is a potential race # that could leave one backup inside the other. if os.path.islink(backup_path): os.unlink(backup_path) elif os.path.isdir(backup_path): shutil.rmtree(backup_path) shutil.move(path, backup_path)
def move_to_backup(path, backup_suffix=BACKUP_SUFFIX)
Move the given file or directory to the same name, with a backup suffix. If backup_suffix not supplied, move it to the extension ".bak". NB: If backup_suffix is supplied and is None, don't do anything.
4.640954
4.619931
1.004551
# Avoid races inherent to doing this in two steps (check then create). # Python 3 has exist_ok but the approach below works for Python 2+3. # https://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python try: os.makedirs(path, mode=mode) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(path): pass else: raise return path
def make_all_dirs(path, mode=0o777)
Ensure local dir, with all its parent dirs, are created. Unlike os.makedirs(), will not fail if the path already exists.
4.232748
4.069954
1.039999
parent = os.path.dirname(path) if parent: make_all_dirs(parent, mode) return path
def make_parent_dirs(path, mode=0o777)
Ensure parent directories of a file are created as needed.
4.386332
3.9158
1.120162
if dest_path == os.devnull: # Handle the (probably rare) case of writing to /dev/null. yield dest_path else: tmp_path = ("%s" + suffix) % (dest_path, new_uid()) if make_parents: make_parent_dirs(tmp_path) yield tmp_path # Note this is not in a finally block, so that result won't be renamed to final location # in case of abnormal exit. if not os.path.exists(tmp_path): raise IOError("failure in writing file '%s': target file '%s' missing" % (dest_path, tmp_path)) if backup_suffix: move_to_backup(dest_path, backup_suffix=backup_suffix) # If the target already exists, and is a directory, it has to be removed. if os.path.isdir(dest_path): shutil.rmtree(dest_path) shutil.move(tmp_path, dest_path)
def atomic_output_file(dest_path, make_parents=False, backup_suffix=None, suffix=".partial.%s")
A context manager for convenience in writing a file or directory in an atomic way. Set up a temporary name, then rename it after the operation is done, optionally making a backup of the previous file or directory, if present.
4.060838
3.91431
1.037434
return _temp_output(False, prefix=prefix, suffix=suffix, dir=dir, make_parents=make_parents, always_clean=always_clean)
def temp_output_file(prefix="tmp", suffix="", dir=None, make_parents=False, always_clean=False)
A context manager for convenience in creating a temporary file, which is deleted when exiting the context. Usage: with temp_output_file() as (fd, path): ...
2.989358
6.095438
0.490425
return _temp_output(True, prefix=prefix, suffix=suffix, dir=dir, make_parents=make_parents, always_clean=always_clean)
def temp_output_dir(prefix="tmp", suffix="", dir=None, make_parents=False, always_clean=False)
A context manager for convenience in creating a temporary directory, which is deleted when exiting the context. Usage: with temp_output_dir() as dirname: ...
3.047746
5.962112
0.511186
with codecs.open(path, "rb", encoding=encoding) as f: value = f.read() return value
def read_string_from_file(path, encoding="utf8")
Read entire contents of file into a string.
3.397278
3.310477
1.02622
with atomic_output_file(path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path: with codecs.open(tmp_path, "wb", encoding=encoding) as f: f.write(string)
def write_string_to_file(path, string, make_parents=False, backup_suffix=BACKUP_SUFFIX, encoding="utf8")
Write entire file with given string contents, atomically. Keeps backup by default.
2.307094
2.117357
1.08961
if not atime: atime = mtime f = open(path, 'a') try: os.utime(path, (atime, mtime)) finally: f.close()
def set_file_mtime(path, mtime, atime=None)
Set access and modification times on a file.
2.147285
1.976942
1.086165
with atomic_output_file(dest_path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path: shutil.copyfile(source_path, tmp_path) set_file_mtime(tmp_path, os.path.getmtime(source_path))
def copyfile_atomic(source_path, dest_path, make_parents=False, backup_suffix=None)
Copy file on local filesystem in an atomic way, so partial copies never exist. Preserves timestamps.
2.134426
2.070286
1.030981
if os.path.isdir(source_path): with atomic_output_file(dest_path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path: shutil.copytree(source_path, tmp_path, symlinks=symlinks) else: copyfile_atomic(source_path, dest_path, make_parents=make_parents, backup_suffix=backup_suffix)
def copytree_atomic(source_path, dest_path, make_parents=False, backup_suffix=None, symlinks=False)
Copy a file or directory recursively, and atomically, reanaming file or top-level dir when done. Unlike shutil.copytree, this will not fail on a file.
1.867751
1.78811
1.044539
if make_parents: make_parent_dirs(dest_path) move_to_backup(dest_path, backup_suffix=backup_suffix) shutil.move(source_path, dest_path)
def movefile(source_path, dest_path, make_parents=False, backup_suffix=None)
Move file. With a few extra options.
2.524786
2.342444
1.077842
# TODO: Could add an rsync-based delete, as in # https://github.com/vivlabs/instaclone/blob/master/instaclone/instaclone.py#L127-L143 if ignore_errors and not os.path.exists(path): return if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path, ignore_errors=ignore_errors, onerror=onerror) else: os.unlink(path)
def rmtree_or_file(path, ignore_errors=False, onerror=None)
rmtree fails on files or symlinks. This removes the target, whatever it is.
3.490674
3.283093
1.063227
popenargs = ["chmod"] if recursive: popenargs.append("-R") popenargs.append(mode_expression) popenargs.append(path) subprocess.check_call(popenargs)
def chmod_native(path, mode_expression, recursive=False)
This is ugly and will only work on POSIX, but the built-in Python os.chmod support is very minimal, and neither supports fast recursive chmod nor "+X" type expressions, both of which are slow for large trees. So just shell out.
2.286197
2.197772
1.040234