Pushes images to a Docker registry. Returns dict containing attributes used to push images.
775283
def push_images(base_path, image_namespace, engine_obj, config, **kwargs):
    
    config_path = kwargs.get('config_path', engine_obj.auth_config_path)
    username = kwargs.get('username')
    password = kwargs.get('password')
    push_to = kwargs.get('push_to')
    url = engine_obj.default_registry_url
    registry_name = engine_obj.default_registry_name
    namespace = image_namespace
    save_conductor = config.save_conductor
    repository_prefix = None
    pull_from_url = None

    if push_to:
        if config.get('registries', dict()).get(push_to):
            url = config['registries'][push_to].get('url')
            namespace = config['registries'][push_to].get('namespace', namespace)
            repository_prefix = config['registries'][push_to].get('repository_prefix')
            pull_from_url = config['registries'][push_to].get('pull_from_url')
            if not url:
                raise AnsibleContainerRegistryAttributeException(
                    u"Registry {} missing required attribute 'url'".format(push_to)
                )
        else:
            url, namespace = resolve_push_to(push_to, engine_obj.default_registry_url, namespace)

    if username and not password:
        # If a username was supplied without a password, prompt for it
        if url != engine_obj.default_registry_url:
            registry_name = url
        while not password:
            password = getpass.getpass(u"Enter password for {0} at {1}: ".format(username, registry_name))

    if config_path:
        # Make sure the config_path exists
        #  - gives us a chance to create the file with correct permissions, if it does not exists
        #  - makes sure we mount a path to the conductor for a specific file
        config_path = os.path.normpath(os.path.expanduser(config_path))
        if os.path.exists(config_path) and os.path.isdir(config_path):
            raise AnsibleContainerException(
                u"Expecting --config-path to be a path to a file, not a directory"
            )
        elif not os.path.exists(config_path):
            # Make sure the directory path exists
            if not os.path.exists(os.path.dirname(config_path)):
                try:
                    os.makedirs(os.path.dirname(config_path), 0o750)
                except OSError:
                    raise AnsibleContainerException(
                        u"Failed to create the requested the path {}".format(os.path.dirname(config_path))
                    )
            # Touch the file
            open(config_path, 'w').close()

    # If you ran build with --save-build-container, then you're broken without first removing
    #  the old build container.
    remove_existing_container(engine_obj, 'conductor', remove_volumes=True)

    push_params = {}
    push_params.update(kwargs)
    push_params['config_path'] = config_path
    push_params['password'] = password
    push_params['url'] = url
    push_params['namespace'] = namespace
    push_params['repository_prefix'] = repository_prefix
    push_params['pull_from_url'] = pull_from_url

    # Push
    engine_obj.await_conductor_command('push', dict(config), base_path, push_params, save_container=save_conductor)

    return {'url': url,
            'namespace': namespace,
            'repository_prefix': repository_prefix,
            'pull_from_url': pull_from_url }
912313
def avail_images(call=None):
    '''
    

    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_images function must be called with '
            '-f or --function, or with the --list-images option'
        )

    server, user, password = _get_xml_rpc()
    auth = ':'.join([user, password])

    image_pool = server.one.imagepool.info(auth, -2, -1, -1)[1]

    images = {}
    for image in _get_xml(image_pool):
        images[image.find('NAME').text] = _xml_to_dict(image)

    return images
583499
def create_container(self, image, name=None, **kwargs):
        
        name_str = " '{0}'".format(name) if name else ""
        self.push_log("Creating container{0} from image '{1}'.".format(name_str, image))
        return super(DockerFabricClient, self).create_container(image, name=name, **kwargs)
1119621
def _pull_image(pull_type, image, name, **kwargs):
    '''
    
    '''
    _ensure_systemd(219)
    if exists(name):
        raise SaltInvocationError(
            'Container \'{0}\' already exists'.format(name)
        )
    if pull_type in ('raw', 'tar'):
        valid_kwargs = ('verify',)
    elif pull_type == 'dkr':
        valid_kwargs = ('index',)
    else:
        raise SaltInvocationError(
            'Unsupported image type \'{0}\''.format(pull_type)
        )

    kwargs = salt.utils.args.clean_kwargs(**kwargs)
    bad_kwargs = dict(
        [(x, y) for x, y in six.iteritems(salt.utils.args.clean_kwargs(**kwargs))
         if x not in valid_kwargs]
    )

    if bad_kwargs:
        salt.utils.args.invalid_kwargs(bad_kwargs)

    pull_opts = []

    if pull_type in ('raw', 'tar'):
        verify = kwargs.get('verify', False)
        if not verify:
            pull_opts.append('--verify=no')
        else:
            def _bad_verify():
                raise SaltInvocationError(
                    '\'verify\' must be one of the following: '
                    'signature, checksum'
                )
            try:
                verify = verify.lower()
            except AttributeError:
                _bad_verify()
            else:
                if verify not in ('signature', 'checksum'):
                    _bad_verify()
                pull_opts.append('--verify={0}'.format(verify))

    elif pull_type == 'dkr':
        # No need to validate the index URL, machinectl will take care of this
        # for us.
        if 'index' in kwargs:
            pull_opts.append('--dkr-index-url={0}'.format(kwargs['index']))

    cmd = 'pull-{0} {1} {2} {3}'.format(
        pull_type, ' '.join(pull_opts), image, name
    )
    result = _machinectl(cmd, use_vt=True)
    if result['retcode'] != 0:
        msg = 'Error occurred pulling image. Stderr from the pull command ' \
              '(if any) follows: '
        if result['stderr']:
            msg += '\n\n{0}'.format(result['stderr'])
        raise CommandExecutionError(msg)
    return True
748044
def image_present(name):
    '''
    
    '''
    ret = {'name': name,
           'changes': {},
           'result': None,
           'comment': ''}

    if _is_docker_uuid(name) and __salt__['imgadm.docker_to_uuid'](name):
        # docker image was imported
        ret['result'] = True
        ret['comment'] = 'image {0} ({1}) is present'.format(
            name,
            __salt__['imgadm.docker_to_uuid'](name),
        )
    elif name in __salt__['imgadm.list']():
        # image was already imported
        ret['result'] = True
        ret['comment'] = 'image {0} is present'.format(name)
    else:
        # add image
        if _is_docker_uuid(name):
            # NOTE: we cannot query available docker images
            available_images = [name]
        else:
            available_images = __salt__['imgadm.avail']()

        if name in available_images:
            if __opts__['test']:
                ret['result'] = True
                res = {}
                if _is_docker_uuid(name):
                    res['00000000-0000-0000-0000-000000000000'] = name
                else:
                    res[name] = available_images[name]
            else:
                res = __salt__['imgadm.import'](name)
                if _is_uuid(name):
                    ret['result'] = (name in res)
                elif _is_docker_uuid(name):
                    ret['result'] = __salt__['imgadm.docker_to_uuid'](name) is not None
            if ret['result']:
                ret['comment'] = 'image {0} imported'.format(name)
                ret['changes'] = res
            else:
                ret['comment'] = 'image {0} was unable to be imported'.format(name)
        else:
            ret['result'] = False
            ret['comment'] = 'image {0} does not exists'.format(name)

    return ret
192236
def rescan_images(registry):
    ''''''
    with Session() as session:
        try:
            result = session.Image.rescanImages(registry)
        except Exception as e:
            print_error(e)
            sys.exit(1)
        if result['ok']:
            print("kernel image metadata updated")
        else:
            print("rescanning failed: {0}".format(result['msg']))
948384
def parent_image_inspect(self, image):
        
        image_name = ImageName.parse(image)
        if image_name not in self._parent_images_inspect:
            if self.parents_pulled:
                self._parent_images_inspect[image_name] = self.tasker.inspect_image(image)
            else:
                self._parent_images_inspect[image_name] =\
                    atomic_reactor.util.get_inspect_for_image(image_name,
                                                              image_name.registry,
                                                              self.base_image_insecure,
                                                              self.base_image_dockercfg_path)

        return self._parent_images_inspect[image_name]
766697
def new_registry(attribute=None):
    
    registry = {}

    def register(key):
        def decorator(func):
            registry[key] = func
            if attribute:
                setattr(func, attribute, key)
            return func
        return decorator

    return registry, register
497268
def snapshot_registry(self):
        '''
        
        '''
        unserializer = banana.Unserializer(externalizer=self)
        serializer = banana.Serializer(externalizer=self)
        return unserializer.convert(serializer.convert(self.registry))
927657
public void push(CollectorRegistry registry) throws IOException {
    Socket s = new Socket(host, port);
    BufferedWriter writer = new BufferedWriter(new PrintWriter(s.getOutputStream()));
    Matcher m = INVALID_GRAPHITE_CHARS.matcher("");
    long now = System.currentTimeMillis() / 1000;
    for (Collector.MetricFamilySamples metricFamilySamples: Collections.list(registry.metricFamilySamples())) {
      for (Collector.MetricFamilySamples.Sample sample: metricFamilySamples.samples) {
        m.reset(sample.name);
        writer.write(m.replaceAll("_"));
        for (int i = 0; i < sample.labelNames.size(); ++i) {
          m.reset(sample.labelValues.get(i));
          writer.write("." + sample.labelNames.get(i) + "." + m.replaceAll("_"));
        }
        writer.write(" " + sample.value + " " + now + "\n");
      }
    }
    writer.close();
    s.close();
  }
313981
def build(self, tag, **kwargs):
        
        self.push_log("Building image '{0}'.".format(tag))
        set_raise_on_error(kwargs)
        try:
            return super(DockerFabricClient, self).build(tag, **kwargs)
        except DockerStatusError as e:
            error(e.message)
1078583
def import_image(self, name, stream_import, tags=None):
        

        # Get the JSON for the ImageStream
        imagestream_json = self.get_image_stream(name).json()
        logger.debug("imagestream: %r", imagestream_json)

        if 'dockerImageRepository' in imagestream_json.get('spec', {}):
            logger.debug("Removing 'dockerImageRepository' from ImageStream %s", name)
            source_repo = imagestream_json['spec'].pop('dockerImageRepository')
            imagestream_json['metadata']['annotations'][ANNOTATION_SOURCE_REPO] = source_repo
            imagestream_json = self.update_image_stream(name, imagestream_json).json()

        # Note the tags before import
        oldtags = imagestream_json.get('status', {}).get('tags', [])
        logger.debug("tags before import: %r", oldtags)

        stream_import['metadata']['name'] = name
        stream_import['spec']['images'] = []
        tags_set = set(tags) if tags else set()
        for tag in imagestream_json.get('spec', {}).get('tags', []):
            if tags_set and tag['name'] not in tags_set:
                continue

            image_import = {
                'from': tag['from'],
                'to': {'name': tag['name']},
                'importPolicy': tag.get('importPolicy'),
                'referencePolicy': tag.get('referencePolicy'),
            }
            stream_import['spec']['images'].append(image_import)

        if not stream_import['spec']['images']:
            logger.debug('No tags to import')
            return False

        import_url = self._build_url("imagestreamimports/")
        import_response = self._post(import_url, data=json.dumps(stream_import),
                                     use_json=True)
        self._check_import_image_response(import_response)

        new_tags = [
            image['tag']
            for image in import_response.json().get('status', {}).get('images', [])]
        logger.debug("tags after import: %r", new_tags)

        return True
591873
def get_image_entrypoint(image):
    ''''''
    info = docker_inspect_or_pull(image)
    try:
        return info['Config']['Entrypoint']
    except KeyError as ke:
        raise DockerError('Failed to inspect image: JSON result missing key {}'.format(ke))
642247
def container_move(object_id, input_params={}, always_retry=False, **kwargs):
    
    return DXHTTPRequest('/%s/move' % object_id, input_params, always_retry=always_retry, **kwargs)
208373
def _build_save_container(platform, registry, load_cache) -> Optional[str]:
    
    docker_tag = build_util.get_docker_tag(platform=platform, registry=registry)

    # Preload cache
    if load_cache:
        load_docker_cache(registry=registry, docker_tag=docker_tag)

    # Start building
    logging.debug('Building %s as %s', platform, docker_tag)
    try:
        # Increase the number of retries for building the cache.
        image_id = build_util.build_docker(docker_binary='docker', platform=platform, registry=registry, num_retries=10, no_cache=False)
        logging.info('Built %s as %s', docker_tag, image_id)

        # Push cache to registry
        _upload_image(registry=registry, docker_tag=docker_tag, image_id=image_id)
        return None
    except Exception:
        logging.exception('Unexpected exception during build of %s', docker_tag)
        return platform
870031
def pull(client, revision, auto_login):
    """"""
    registry_url = detect_registry_url(client, auto_login=auto_login)

    repo = client.repo
    sha = repo.rev_parse(revision).hexsha
    short_sha = repo.git.rev_parse(sha, short=7)

    image = '{registry}:{short_sha}'.format(
        registry=registry_url.image, short_sha=short_sha
    )

    result = subprocess.run(['docker', 'image', 'pull', image])
    if result.returncode != 0:
        raise click.ClickException(
            'The image "{image}" was not pulled.\n\n'
            'Push the repository to the server or build the image manually:\n'
            '\n\tdocker build -t {image} .'.format(image=image)
        )
222847
def _upload_image(registry, docker_tag, image_id) -> None:
    
    # We don't have to retag the image since it is already in the right format
    logging.info('Uploading %s (%s) to %s', docker_tag, image_id, registry)
    push_cmd = ['docker', 'push', docker_tag]
    subprocess.check_call(push_cmd)