Esempio n. 1
0
def run_container(client, from_img, kwargs, container_kwargs):

    cmd = kwargs.pop("cmd", None)
    if not cmd:
        raise RabixError("Commands ('cmd') not specified!")

    repo, tag = parse_repository_tag(from_img)
    img = get_image(client, from_img)
    if not img:
        raise RabixError("Unable to find image: %s" % img)

    mount_point = kwargs.pop("mount_point", MOUNT_POINT)
    run_cmd = make_cmd(cmd, join=True)

    container = Container(
        client,
        img["Id"],
        "{}:{}".format(repo, tag),
        run_cmd,
        volumes={mount_point: {}},
        working_dir=mount_point,
        **container_kwargs
    )

    container.start({abspath("."): mount_point})
    container.write_stdout()
    return container
Esempio n. 2
0
    def _parse_deploy_id(self, deploy_id):
        """Read a full deploy uri with tag and split into repository reference and tag."""

        (repo, tag) = parse_repository_tag(deploy_id)
        disable_latest_tag = self.ctx.config.get('docker', 'disable_latest_tag') == 'True'
        if (tag is None or tag == 'latest') and disable_latest_tag:
            raise GContainerException(ErrorConstants.LATEST_TAG_DISABLED)

        return repo, tag
Esempio n. 3
0
def publish_release(source, config, target):
    """
    Publish a new release as a Docker image

    Given a source image and dictionary of last-mile configuration,
    create a target Docker image on the registry.

    For example::

        publish_release('registry.local:5000/gabrtv/myapp:v22',
                        {'ENVVAR': 'values'},
                        'registry.local:5000/gabrtv/myapp:v23')

    results in a new Docker image at 'registry.local:5000/gabrtv/myapp:v23' which
    contains the new configuration as ENV entries.
    """
    try:
        repo, tag = utils.parse_repository_tag(source)
        src_image = repo
        src_tag = tag if tag is not None else 'latest'

        nameparts = repo.rsplit('/', 1)
        if len(nameparts) == 2:
            if '/' in nameparts[0]:
                # strip the hostname and just use the app name
                src_image = '{}/{}'.format(nameparts[0].rsplit('/', 1)[1],
                                           nameparts[1])
            elif '.' in nameparts[0]:
                # we got a name like registry.local:5000/registry
                src_image = nameparts[1]

        target_image = target.rsplit(':', 1)[0]
        target_tag = target.rsplit(':', 1)[1]
        image_id = _get_tag(src_image, src_tag)
    except RuntimeError:
        if src_tag == 'latest':
            # no image exists yet, so let's build one!
            _put_first_image(src_image)
            image_id = _get_tag(src_image, src_tag)
        else:
            raise
    image = _get_image(image_id)
    # construct the new image
    image['parent'] = image['id']
    image['id'] = _new_id()
    config['DEIS_APP'] = target_image
    config['DEIS_RELEASE'] = target_tag
    config['DEIS_ENV'] = target_environment
    image['config']['Env'] = _construct_env(config)
    # update and tag the new image
    _commit(target_image, image, _empty_tar_archive(), target_tag, target_environment)
Esempio n. 4
0
File: private.py Progetto: inz/deis
def publish_release(source, config, target):
    """
    Publish a new release as a Docker image

    Given a source image and dictionary of last-mile configuration,
    create a target Docker image on the registry.

    For example publish_release('registry.local:5000/gabrtv/myapp:v22',
                                {'ENVVAR': 'values'},
                                'registry.local:5000/gabrtv/myapp:v23',)
    results in a new Docker image at 'registry.local:5000/gabrtv/myapp:v23' which
    contains the new configuration as ENV entries.
    """
    try:
        repo, tag = utils.parse_repository_tag(source)
        src_image = repo
        src_tag = tag if tag is not None else "latest"

        nameparts = repo.rsplit("/", 1)
        if len(nameparts) == 2:
            if "/" in nameparts[0]:
                # strip the hostname and just use the app name
                src_image = "{}/{}".format(nameparts[0].rsplit("/", 1)[1], nameparts[1])
            elif "." in nameparts[0]:
                # we got a name like registry.local:5000/registry
                src_image = nameparts[1]

        target_image = target.rsplit(":", 1)[0]
        target_tag = target.rsplit(":", 1)[1]
        image_id = _get_tag(src_image, src_tag)
    except RuntimeError:
        if src_tag == "latest":
            # no image exists yet, so let's build one!
            _put_first_image(src_image)
            image_id = _get_tag(src_image, src_tag)
        else:
            raise
    image = _get_image(image_id)
    # construct the new image
    image["parent"] = image["id"]
    image["id"] = _new_id()
    image["config"]["Env"] = _construct_env(image["config"]["Env"], config)
    # update and tag the new image
    _commit(target_image, image, _empty_tar_archive(), target_tag)
Esempio n. 5
0
    def push_image(self, name, tag=None):
        '''
        If the name of the image contains a repository path, then push the image.

        :param name Name of the image to push.
        :param tag Use a specific tag.
        :return: None
        '''

        repository = name
        if not tag:
            repository, tag = parse_repository_tag(name)
        registry, repo_name = resolve_repository_name(repository)

        self.log("push %s to %s/%s:%s" % (self.name, registry, repo_name, tag))

        if registry:
            self.results['actions'].append("Pushed image %s to %s/%s:%s" % (self.name, registry, repo_name, tag))
            self.results['changed'] = True
            if not self.check_mode:
                status = None
                try:
                    for line in self.client.push(repository, tag=tag, stream=True, decode=True):
                        self.log(line, pretty_print=True)
                        if line.get('errorDetail'):
                            raise Exception(line['errorDetail']['message'])
                        status = line.get('status')
                except Exception as exc:
                    if re.search('unauthorized', str(exc)):
                        if re.search('authentication required', str(exc)):
                            self.fail("Error pushing image %s/%s:%s - %s. Try logging into %s first." %
                                      (registry, repo_name, tag, str(exc), registry))
                        else:
                            self.fail("Error pushing image %s/%s:%s - %s. Does the repository exist?" %
                                      (registry, repo_name, tag, str(exc)))
                    self.fail("Error pushing image %s: %s" % (repository, str(exc)))
                self.results['image'] = self.client.find_image(name=repository, tag=tag)
                if not self.results['image']:
                    self.results['image'] = dict()
                self.results['image']['push_status'] = status
Esempio n. 6
0
    def tag_image(self, name, tag, repository, force=False, push=False):
        '''
        Tag an image into a repository.

        :param name: name of the image. required.
        :param tag: image tag.
        :param repository: path to the repository. required.
        :param force: bool. force tagging, even it image already exists with the repository path.
        :param push: bool. push the image once it's tagged.
        :return: None
        '''
        repo, repo_tag = parse_repository_tag(repository)
        if not repo_tag:
            repo_tag = "latest"
            if tag:
                repo_tag = tag
        image = self.client.find_image(name=repo, tag=repo_tag)
        found = 'found' if image else 'not found'
        self.log("image %s was %s" % (repo, found))

        if not image or force:
            self.log("tagging %s:%s to %s:%s" % (name, tag, repo, repo_tag))
            self.results['changed'] = True
            self.results['actions'].append("Tagged image %s:%s to %s:%s" % (name, tag, repo, repo_tag))
            if not self.check_mode:
                try:
                    # Finding the image does not always work, especially running a localhost registry. In those
                    # cases, if we don't set force=True, it errors.
                    image_name = name
                    if tag and not re.search(tag, name):
                        image_name = "%s:%s" % (name, tag)
                    tag_status = self.client.tag(image_name, repo, tag=repo_tag, force=True)
                    if not tag_status:
                        raise Exception("Tag operation failed.")
                except Exception as exc:
                    self.fail("Error: failed to tag image - %s" % str(exc))
                self.results['image'] = self.client.find_image(name=repo, tag=repo_tag)
                if push:
                    self.push_image(repo, repo_tag)
Esempio n. 7
0
    def __init__(self, client, results):

        super(ImageManager, self).__init__()

        self.client = client
        self.results = results
        parameters = self.client.module.params
        self.check_mode = self.client.check_mode

        self.archive_path = parameters.get('archive_path')
        self.container_limits = parameters.get('container_limits')
        self.dockerfile = parameters.get('dockerfile')
        self.force = parameters.get('force')
        self.load_path = parameters.get('load_path')
        self.name = parameters.get('name')
        self.nocache = parameters.get('nocache')
        self.path = parameters.get('path')
        self.pull = parameters.get('pull')
        self.repository = parameters.get('repository')
        self.rm = parameters.get('rm')
        self.state = parameters.get('state')
        self.tag = parameters.get('tag')
        self.http_timeout = parameters.get('http_timeout')
        self.push = parameters.get('push')
        self.buildargs = parameters.get('buildargs')

        # If name contains a tag, it takes precedence over tag parameter.
        repo, repo_tag = parse_repository_tag(self.name)
        if repo_tag:
            self.name = repo
            self.tag = repo_tag

        if self.state in ['present', 'build']:
            self.present()
        elif self.state == 'absent':
            self.absent()
Esempio n. 8
0
def get_image(client, repo=None, tag=None, image_id=None):
    """Returns the image dict. Pulls from repo if not found locally."""

    if not image_id and not repo:
        raise ValueError('Need either repository or image ID.')

    if repo and not tag:
        repo, tag = parse_repository_tag(repo)

    queries = [image_id, repo]
    if tag:
        queries.append((repo, tag))

    img = find_image(client, queries)

    if not img:
        log.info('Pulling %s', repo)
        client.pull(repo, tag)
        img = find_image(client, queries)

    if not img:
        raise ResourceUnavailable(repo, 'Image not found.')

    return img
Esempio n. 9
0
 def _has_hostname(image):
     repo, tag = dockerutils.parse_repository_tag(image)
     return True if '/' in repo and '.' in repo.split('/')[0] else False
Esempio n. 10
0
 def _has_hostname(image):
     repo, tag = utils.parse_repository_tag(image)
     return True if "/" in repo and "." in repo.split("/")[0] else False
Esempio n. 11
0
 def _has_hostname(image):
     repo, tag = utils.parse_repository_tag(image)
     return True if '/' in repo and '.' in repo.split('/')[0] else False