Search is not available for this dataset
text
stringlengths
75
104k
def search_all(self): '''a "show all" search that doesn't require a query''' results = set() # Here we get names of collections, and then look up containers for container in self.conn.get_account()[1]: # The result here is just the name for result in self.conn.get_container(container[...
def container_query(self, query): '''search for a specific container. This function would likely be similar to the above, but have different filter criteria from the user (based on the query) ''' results = set() query = remove_uri(query) # Here we get names of collections, and then look u...
def list_containers(self): '''return a list of containers, determined by finding the metadata field "type" with value "container." We alert the user to no containers if results is empty, and exit {'metadata': {'items': [ {'key': 't...
def search_all(self): '''a "list all" search that doesn't require a query. Here we return to the user all objects that have custom metadata value of "container" IMPORTANT: the upload function adds this metadata. For a container to be found by the client, it must have the type as container in m...
def container_query(self, query, quiet=False): '''search for a specific container. This function would likely be similar to the above, but have different filter criteria from the user (based on the query) ''' results = self._list_containers() matches = [] for result in results: ...
def search_all(self): '''a "show all" search that doesn't require a query''' results = [] # Parse through folders (collections): for entry in self.dbx.files_list_folder('').entries: # Parse through containers for item in self.dbx.files_list_folder(entry.path_lower).entries: ...
def main(args,parser,subparser): '''the list command corresponds with listing images for an external resource. This is different from listing images that are local to the database, which should be done with "images" ''' from sregistry.main import get_client cli = get_client(quiet=args.quie...
def pull(self, images, file_name=None, save=True, **kwargs): '''pull an image from google storage, based on the identifier Parameters ========== images: refers to the uri given by the user to pull in the format <collection>/<namespace>. You should have an API that is able to ...
def main(args, parser, subparser): '''sharing an image means sending a remote share from an image you control to a contact, usually an email. ''' from sregistry.main import get_client images = args.image if not isinstance(images,list): images = [images] for image in images: ...
def init_db(self, db_path): '''initialize the database, with the default database path or custom of the format sqlite:////scif/data/expfactory.db The custom path can be set with the environment variable SREGISTRY_DATABASE when a user creates the client, we must initialize this db the database s...
def get_uri(self): '''generate a uri on the fly from database parameters if one is not saved with the initial model (it should be, but might not be possible) ''' uri = "%s/%s:%s" %(self.collection.name, self.name, self.tag) if self.version not in [None,'']: uri = "%s@...
def get_build_template(): '''get default build template. ''' base = get_installdir() name = "%s/main/templates/build/singularity-cloudbuild.json" % base if os.path.exists(name): bot.debug("Found template %s" %name) return read_json(name) bot.warning("Template %s not found." % n...
def search(self, query=None, args=None): '''query will show images determined by the extension of img or simg. Parameters ========== query: the container name (path) or uri to search for args.endpoint: can be an endpoint id and optional path, e.g.: --endpoint 6881a...
def list_endpoints(self, query=None): '''list all endpoints, providing a list of endpoints to the user to better filter the search. This function takes no arguments, as the user has not provided an endpoint id or query. ''' bot.info('Please select an endpoint id to query from') endpoints...
def list_endpoint(self, endpoint, query=None): '''An endpoint is required here to list files within. Optionally, we can take a path relative to the endpoint root. Parameters ========== endpoint: a single endpoint ID or an endpoint id and relative path. If no path is pro...
def share(self, query, share_to=None): '''share will use the client to get a shareable link for an image of choice. the functions returns a url of choice to send to a recipient. ''' names = parse_image_name(remove_uri(query)) # Dropbox path is the path in storage with a slash dropbox_path =...
def _set_base(self): '''set the API base or default to use Docker Hub. The user is able to set the base, api version, and protocol via a settings file of environment variables: SREGISTRY_NVIDIA_BASE: defaults to nvcr.io SREGISTRY_NVIDIA_TOKEN: defaults to $oauthtoke...
def _update_secrets(self): '''update secrets will take a secrets credential file either located at .sregistry or the environment variable SREGISTRY_CLIENT_SECRETS and update the current client secrets as well as the associated API base. For the case of using Docker H...
def pull(self, images, file_name=None, save=True, **kwargs): '''pull an image from a Globus endpoint. The user must have the default local endpoint set up. For example: 6881ae2e-db26-11e5-9772-22000b9da45e:.singularity/shub/sherlock_vep.simg Parameters ========== images: refers to the gl...
def get_credential_cache(): '''if the user has specified settings to provide a cache for credentials files, initialize it. The root for the folder is created if it doesn't exist. The path for the specific client is returned, and it's not assumed to be either a folder or a file (this is up to th...
def update_client_secrets(backend, updates, secrets=None, save=True): '''update client secrets will update the data structure for a particular authentication. This should only be used for a (quasi permanent) token or similar. The secrets file, if found, is updated and saved by default. ''' if ...
def read_client_secrets(): '''for private or protected registries, a client secrets file is required to be located at .sregistry. If no secrets are found, we use default of Singularity Hub, and return a dummy secrets. ''' client_secrets = _default_client_secrets() # If token file not prov...
def _init_client(self): '''init client will check if the user has defined a bucket that differs from the default, use the application credentials to get the bucket, and then instantiate the client. ''' # Get storage and compute services self._get_services() ...
def _get_services(self, version='v1'): '''get version 1 of the google compute and storage service Parameters ========== version: version to use (default is v1) ''' self._bucket_service = storage.Client() creds = GoogleCredentials.get_application_default() ...
def _get_bucket(self): '''get a bucket based on a bucket name. If it doesn't exist, create it. ''' # Case 1: The bucket already exists try: self._bucket = self._bucket_service.get_bucket(self._bucket_name) # Case 2: The bucket needs to be created except goog...
def delete_object(service, bucket_name, object_name): '''delete object will delete a file from a bucket Parameters ========== storage_service: the service obtained with get_storage_service bucket_name: the name of the bucket object_name: the "name" parameter of the object. '...
def delete(self, name): '''delete an image from Google Storage. Parameters ========== name: the name of the file (or image) to delete ''' bot.debug("DELETE %s" % name) for file_object in files: if isinstance(file_object, dict): if "kind" in file_object: ...
def destroy(self, name): '''destroy an instance, meaning take down the instance and stop the build. Parameters ========== name: the name of the instance to stop building. ''' instances = self._get_instances() project = self._get_project() zone = self._get_zone() found = Fa...
def get_subparsers(parser): '''get_subparser will get a dictionary of subparsers, to help with printing help ''' actions = [action for action in parser._actions if isinstance(action, argparse._SubParsersAction)] subparsers = dict() for action in actions: # get all subparser...
def main(): '''main is the entrypoint to the sregistry client. The flow works to first to determine the subparser in use based on the command. The command then imports the correct main (files imported in this folder) associated with the action of choice. When the client is imported, it is actually impor...
def generate(self, delim='-', length=4, chars='0123456789'): ''' Generate a robot name. Inspiration from Haikunator, but much more poorly implemented ;) Parameters ========== delim: Delimiter length: TokenLength chars: TokenChars ''' ...
def mkdir_p(path): '''mkdir_p attempts to get the same functionality as mkdir -p :param path: the path to create. ''' try: os.makedirs(path) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(path): pass else: bot.error("Error creating p...
def get_tmpfile(requested_tmpdir=None, prefix=""): '''get a temporary file with an optional prefix. By default will be created in /tmp unless SREGISTRY_TMPDIR is set. By default, the file is closed (and just a name returned). Parameters ========== requested_tmpdir: an optional re...
def get_tmpdir(requested_tmpdir=None, prefix="", create=True): '''get a temporary directory for an operation. If SREGISTRY_TMPDIR is set, return that. Otherwise, return the output of tempfile.mkdtemp Parameters ========== requested_tmpdir: an optional requested temporary directory, firs...
def extract_tar(archive, output_folder, handle_whiteout=False): '''extract a tar archive to a specified output folder Parameters ========== archive: the archive file to extract output_folder: the output folder to extract to handle_whiteout: use docker2oci variation to handle...
def _extract_tar(archive, output_folder): '''use blob2oci to handle whiteout files for extraction. Credit for this script goes to docker2oci by Olivier Freyermouth, and see script folder for license. Parameters ========== archive: the archive to extract output_folder the o...
def create_tar(files, output_folder=None): '''create_memory_tar will take a list of files (each a dictionary with name, permission, and content) and write the tarfile (a sha256 sum name is used) to the output_folder. If there is no output folde specified, the tar is written to a temp...
def get_content_hash(contents): '''get_content_hash will return a hash for a list of content (bytes/other) ''' hasher = hashlib.sha256() for content in contents: if isinstance(content, io.BytesIO): content = content.getvalue() if not isinstance(content, bytes): co...
def get_file_hash(filename): '''find the SHA256 hash string of a file ''' hasher = hashlib.sha256() with open(filename, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hasher.update(chunk) return hasher.hexdigest()
def write_json(json_obj, filename, mode="w", print_pretty=True): '''write_json will (optionally,pretty print) a json object to file Parameters ========== json_obj: the dict to print to json filename: the output file to write to pretty_print: if True, will use nicer formatting ...
def read_file(filename, mode="r", readlines=True): '''write_file will open a file, "filename" and write content, "content" and properly close the file ''' with open(filename, mode) as filey: if readlines is True: content = filey.readlines() else: content = file...
def read_json(filename, mode='r'): '''read_json reads in a json file and returns the data structure as dict. ''' with open(filename, mode) as filey: data = json.load(filey) return data
def clean_up(files): '''clean up will delete a list of files, only if they exist ''' if not isinstance(files, list): files = [files] for f in files: if os.path.exists(f): bot.verbose3("Cleaning up %s" % f) os.remove(f)
def pull(self, images, file_name=None, save=True, force=False, **kwargs): '''pull an image from a docker hub. This is a (less than ideal) workaround that actually does the following: - creates a sandbox folder - adds docker layers, metadata folder, and custom metadata to it - converts t...
def pull(self, images, file_name=None, save=True, **kwargs): '''pull an image from a singularity registry Parameters ========== images: refers to the uri given by the user to pull in the format <collection>/<namespace>. You should have an API that is able to retrieve a container based on pars...
def push(self, path, name, tag=None): '''push an image to an S3 endpoint''' path = os.path.abspath(path) image = os.path.basename(path) bot.debug("PUSH %s" % path) if not os.path.exists(path): bot.error('%s does not exist.' %path) sys.exit(1) # Extract the metadata names =...
def get_or_create_collection(self, name): '''get a collection if it exists. If it doesn't exist, create it first. Parameters ========== name: the collection name, usually parsed from get_image_names()['name'] ''' from sregistry.database.models import Collection collection = self.get_collec...
def get_collection(self, name): '''get a collection, if it exists, otherwise return None. ''' from sregistry.database.models import Collection return Collection.query.filter(Collection.name == name).first()
def get_container(self, name, collection_id, tag="latest", version=None): '''get a container, otherwise return None. ''' from sregistry.database.models import Container if version is None: container = Container.query.filter_by(collection_id = collection_id, ...
def get(self, name, quiet=False): '''Do a get for a container, and then a collection, and then return None if no result is found. Parameters ========== name: should coincide with either the collection name, or the container name with the collection. A query is done first for the collect...
def images(self, query=None): '''List local images in the database, optionally with a query. Paramters ========= query: a string to search for in the container or collection name|tag|uri ''' from sregistry.database.models import Collection, Container rows = [] if query is not...
def inspect(self, name): '''Inspect a local image in the database, which typically includes the basic fields in the model. ''' print(name) container = self.get(name) if container is not None: collection = container.collection.name fields = container.__dict__.copy() fi...
def rename(self, image_name, path): '''rename performs a move, but ensures the path is maintained in storage Parameters ========== image_name: the image name (uri) to rename to. path: the name to rename (basename is taken) ''' container = self.get(image_name, quiet=True) i...
def mv(self, image_name, path): '''Move an image from it's current location to a new path. Removing the image from organized storage is not the recommended approach however is still a function wanted by some. Parameters ========== image_name: the parsed image name. path: t...
def cp(self, move_to, image_name=None, container=None, command="copy"): '''_cp is the shared function between mv (move) and rename, and performs the move, and returns the updated container Parameters ========== image_name: an image_uri to look up a container in the database c...
def rmi(self, image_name): '''Remove an image from the database and filesystem. ''' container = self.rm(image_name, delete=True) if container is not None: bot.info("[rmi] %s" % container)
def rm(self, image_name, delete=False): '''Remove an image from the database, akin to untagging the image. This does not delete the file from the cache, unless delete is set to True (as called by rmi). ''' container = self.get(image_name) if container is not None: name = container.uri or...
def add(self, image_path=None, image_uri=None, image_name=None, url=None, metadata=None, save=True, copy=False): '''get or create a container, including the collection to add it to. This function can be used from a file on the...
def push(self, path, name, tag=None): '''push an image to Singularity Registry''' path = os.path.abspath(path) image = os.path.basename(path) bot.debug("PUSH %s" % path) if not os.path.exists(path): bot.error('%s does not exist.' %path) sys.exit(1) # Interaction with a registr...
def parse_header(recipe, header="from", remove_header=True): '''take a recipe, and return the complete header, line. If remove_header is True, only return the value. Parameters ========== recipe: the recipe file headers: the header key to find and parse remove_header: if t...
def find_recipes(folders, pattern=None, base=None): '''find recipes will use a list of base folders, files, or patterns over a subset of content to find recipe files (indicated by Starting with Singularity Parameters ========== base: if defined, consider folders recursively ...
def find_folder_recipes(base_folder, pattern="Singularity", manifest=None, base=None): '''find folder recipes will find recipes based on a particular pattern. Parameters ========== base_folder: the base folder to r...
def find_single_recipe(filename, pattern="Singularity", manifest=None): '''find_single_recipe will parse a single file, and if valid, return an updated manifest Parameters ========== filename: the filename to assess for a recipe pattern: a default pattern to search for man...
def build(self, name, recipe="Singularity", context=None, preview=False): '''trigger a build on Google Cloud (builder then storage) given a name recipe, and Github URI where the recipe can be found. Parameters ========== recipe: the ...
def create_build_package(package_files): '''given a list of files, copy them to a temporary folder, compress into a .tar.gz, and rename based on the file hash. Return the full path to the .tar.gz in the temporary folder. Parameters ========== package_files: a list of files to inc...
def load_build_config(self, name, recipe): '''load a google compute config, meaning that we start with a template, and mimic the following example cloudbuild.yaml: steps: - name: "singularityware/singularity:${_SINGULARITY_VERSION}" args: ['build', 'julia-centos-another.sif', 'juli...
def run_build(self, config, bucket, names): '''run a build, meaning creating a build. Retry if there is failure ''' project = self._get_project() # prefix, message, color bot.custom('PROJECT', project, "CYAN") bot.custom('BUILD ', config['steps'][0]['name'], "CYAN") response ...
def update_blob_metadata(blob, response, config, bucket, names): '''a specific function to take a blob, along with a SUCCESS response from Google build, the original config, and update the blob metadata with the artifact file name, dependencies, and image hash. ''' manifest = os.path.basenam...
def search(self, query=None, args=None): '''query a Singularity registry for a list of images. If query is None, collections are listed. EXAMPLE QUERIES: ''' # You can optionally better parse the image uri (query), but not # necessary # names = parse_image_name(remove_uri(query)) ...
def search_all(self): '''a "show all" search that doesn't require a query''' # This should be your apis url for a search url = '...' # paginte get is what it sounds like, and what you want for multiple # pages of results results = self._paginate_get(url) if len(results) == 0: b...
def parse_image_name(image_name, tag=None, version=None, defaults=True, ext="sif", default_collection="library", default_tag="latest", base=None, lowe...
def format_container_name(name, special_characters=None): '''format_container_name will take a name supplied by the user, remove all special characters (except for those defined by "special-characters" and return the new image name. ''' if special_characters is None: special_characters = [] ...
def get_uri(image): '''get the uri for an image, if within acceptable Parameters ========== image: the image uri, in the format <uri>://<registry>/<namespace>:<tag> ''' # Ensure we have a string image = image or '' # Find uri prefix, including :// regexp = re.compile('^....
def pull(self, images, file_name=None, save=True, **kwargs): '''pull an image from storage using Swift. The image is found based on the storage uri Parameters ========== images: refers to the uri given by the user to pull in the format <collection>/<namespace>. You should have a...
def push(self, path, name, tag=None): '''push an image to Google Cloud Drive, meaning uploading it path: should correspond to an absolte image path (or derive it) name: should be the complete uri that the user has requested to push. tag: should correspond with an image tag. This is provided to mirr...
def _set_base(self, zone=None): '''set the API base or default to use Docker Hub. The user is able to set the base, api version, and protocol via a settings file of environment variables: ''' if hasattr(self.aws._client_config, 'region_name'): zone = self.aws._c...
def _update_secrets(self): '''update secrets will take a secrets credential file either located at .sregistry or the environment variable SREGISTRY_CLIENT_SECRETS and update the current client secrets as well as the associated API base. For the case of using Docker H...
def get_logging_level(): '''get_logging_level will configure a logging to standard out based on the user's selected level, which should be in an environment variable called MESSAGELEVEL. if MESSAGELEVEL is not set, the maximum level (5) is assumed (all messages). ''' level = os.environ.get("MESS...
def useColor(self): '''useColor will determine if color should be added to a print. Will check if being run in a terminal, and if has support for asci''' COLORIZE = get_user_color_preference() if COLORIZE is not None: return COLORIZE streams = [self.errorStrea...
def addColor(self, level, text): '''addColor to the prompt (usually prefix) if terminal supports, and specified to do so''' if self.colorize: if level in self.colors: text = "%s%s%s" % (self.colors[level], text, ...
def emitError(self, level): '''determine if a level should print to stderr, includes all levels but INFO and QUIET''' if level in [ABORT, ERROR, WARNING, VERBOSE, VERBOSE1, VERBOSE2, ...
def emit(self, level, message, prefix=None, color=None): '''emit is the main function to print the message optionally with a prefix :param level: the level of the message :param message: the message to print :param prefix: a prefix for the message ''' if color is ...
def write(self, stream, message): '''write will write a message to a stream, first checking the encoding ''' if isinstance(message, bytes): message = message.decode('utf-8') stream.write(message)
def get_logs(self, join_newline=True): ''''get_logs will return the complete history, joined by newline (default) or as is. ''' if join_newline: return '\n'.join(self.history) return self.history
def show_progress(self, iteration, total, length=40, min_level=0, prefix=None, carriage_return=True, suffix=None, symbol=None): '''creat...
def table(self, rows, col_width=2): '''table will print a table of entries. If the rows is a dictionary, the keys are interpreted as column names. if not, a numbered list is used. ''' labels = [str(x) for x in range(1,len(rows)+1)] if isinstance(rows, dict): ...
def push(self, path, name, tag=None): '''push an image to Singularity Registry path: should correspond to an absolte image path (or derive it) name: should be the complete uri that the user has requested to push. tag: should correspond with an image tag. This is provided to mirror Docker ''' ...
def push(self, path, name, tag=None): '''push an image to Globus endpoint. In this case, the name is the globus endpoint id and path. --name <endpointid>:/path/for/image ''' # Split the name into endpoint and rest endpoint, remote = self._parse_endpoint_name(name) path = os.path.a...
def get_template(name): '''return a default template for some function in sregistry If there is no template, None is returned. Parameters ========== name: the name of the template to retrieve ''' name = name.lower() templates = dict() templates['tarinfo'] = {"gid": 0, ...
def update_token(self): '''update_token uses HTTP basic authentication to get a token for Docker registry API V2 operations. We get here if a 401 is returned for a request. Parameters ========== response: the http request response to parse for the challenge. https://docs.docker.com/reg...
def download_layers(self, repo_name, digest=None, destination=None): ''' download layers is a wrapper to do the following for a client loaded with a manifest for an image: 1. use the manifests to retrieve list of digests (get_digests) 2. atomically download the list to destination (ge...
def get_manifest(self, repo_name, tag): '''return the image manifest via the aws client, saved in self.manifest ''' image = None repo = self.aws.describe_images(repositoryName=repo_name) if 'imageDetails' in repo: for contender in repo.get('imageDetails'): if tag in contender['i...
def get_digests(self, repo_name, tag): ''' return a list of layers from a manifest. The function is intended to work with both version 1 and 2 of the schema. All layers (including redundant) are returned. By default, we try version 2 first, then fall back to version 1. For...
def prepare_metadata(metadata): '''prepare a key/value list of metadata for the request. The metadata object that comes in is only parsed one level. ''' pairs = { 'metadata': { 'items': [{ 'key': 'client', 'value': 'sregistry' } ...
def get_build_template(name=None, manager='apt'): '''get a particular build template, by default we return templates that are based on package managers. Parameters ========== name: the full path of the template file to use. manager: the package manager to use in the template (yum...
def get_metadata(self, image_file, names={}): '''extract metadata using Singularity inspect, if the executable is found. If not, return a reasonable default (the parsed image name) Parameters ========== image_file: the full path to a Singularity image names: optional, an extracte...
def _pull(self, file_name, names, save=True, force=False, uri="docker://", **kwargs): '''pull an image from a docker hub. This is a (less than ideal) workaround that actually does the following: - creates a sandbox folder - add...
def _update_secrets(self): '''update secrets will take a secrets credential file either located at .sregistry or the environment variable SREGISTRY_CLIENT_SECRETS and update the current client secrets as well as the associated API base. This is where you should do an...
def _make_repr(class_name, *args, **kwargs): """ Generate a repr string. Positional arguments should be the positional arguments used to construct the class. Keyword arguments should consist of tuples of the attribute value and default. If the value is the default, then it won't be rendered in ...
def s3errors(path): """Translate S3 errors to FSErrors.""" try: yield except ClientError as error: _error = error.response.get("Error", {}) error_code = _error.get("Code", None) response_meta = error.response.get("ResponseMetadata", {}) http_status = response_meta.get...