Import image tags from a Docker registry into an ImageStream

        :return: bool, whether tags were imported
550169
def import_image(self, name, tags=None):
        
        stream_import_file = os.path.join(self.os_conf.get_build_json_store(),
                                          'image_stream_import.json')
        with open(stream_import_file) as f:
            stream_import = json.load(f)
        return self.os.import_image(name, stream_import, tags=tags)
567732
def _read_tags(self):
        
        tags = self._config.get('tags', {})
        logging.info('Tags:')
        for tag_name in tags.keys():
            tag = {}
            tag['Key'] = tag_name
            tag['Value'] = tags[tag_name]
            self._tags.append(tag)
            logging.info('{} = {}'.format(tag_name, tags[tag_name]))

        logging.debug(json.dumps(
            self._tags,
            indent=2,
            sort_keys=True
        ))
        return True
1232445
def framework_version_from_tag(image_tag):
    
    tag_pattern = re.compile('^(.*)-(cpu|gpu)-(py2|py3)$')
    tag_match = tag_pattern.match(image_tag)
    return None if tag_match is None else tag_match.group(1)
640062
def render_import_image(self, use_auth=None):
        
        # import_image is a multi-phase plugin
        if self.user_params.imagestream_name.value is None:
            self.pt.remove_plugin('exit_plugins', 'import_image',
                                  'imagestream not in user parameters')
        elif self.pt.has_plugin_conf('exit_plugins', 'import_image'):
            self.pt.set_plugin_arg('exit_plugins', 'import_image', 'imagestream',
                                   self.user_params.imagestream_name.value)
260649
async function getLabels(registry, repository, tag) {
  logger.debug(`getLabels(${registry}, ${repository}, ${tag})`);
  const cacheNamespace = 'datasource-docker-labels';
  const cacheKey = `${registry}:${repository}:${tag}`;
  const cachedResult = await renovateCache.get(cacheNamespace, cacheKey);
  // istanbul ignore if
  if (cachedResult) {
    return cachedResult;
  }
  try {
    const manifestResponse = await getManifestResponse(
      registry,
      repository,
      tag
    );
    // If getting the manifest fails here, then abort
    // This means that the latest tag doesn't have a manifest, which shouldn't
    // be possible
    if (!manifestResponse) {
      logger.info(
        {
          registry,
          dockerRepository: repository,
          tag,
        },
        'docker registry failure: failed to get manifest for tag'
      );
      return {};
    }
    const manifest = JSON.parse(manifestResponse.body);
    let labels = {};
    if (manifest.schemaVersion === 1) {
      try {
        labels = JSON.parse(manifest.history[0].v1Compatibility)
          .container_config.Labels;
      } catch (err) {
        logger.debug('Could not retrieve labels from v1 manifest');
      }
      if (!labels) {
        labels = {};
      }
    }
    if (manifest.schemaVersion === 2) {
      const configDigest = manifest.config.digest;
      const headers = await getAuthHeaders(registry, repository);
      if (!headers) {
        logger.info('No docker auth found - returning');
        return {};
      }
      const url = `${registry}/v2/${repository}/blobs/${configDigest}`;
      const configResponse = await got(url, {
        headers,
        timeout: 10000,
      });
      labels = JSON.parse(configResponse.body).config.Labels;
    }

    if (labels) {
      logger.debug(
        {
          labels,
        },
        'found labels in manifest'
      );
    }
    const cacheMinutes = 60;
    await renovateCache.set(cacheNamespace, cacheKey, labels, cacheMinutes);
    return labels;
  } catch (err) {
    if (err.statusCode === 401) {
      logger.info(
        { registry, dockerRepository: repository },
        'Unauthorized docker lookup'
      );
      logger.debug({ err });
    } else if (err.statusCode === 404) {
      logger.warn(
        {
          err,
          registry,
          dockerRepository: repository,
          tag,
        },
        'Config Manifest is unknown'
      );
    } else if (err.statusCode === 429 && registry.endsWith('docker.io')) {
      logger.warn({ err }, 'docker registry failure: too many requests');
    } else if (err.statusCode >= 500 && err.statusCode < 600) {
      logger.warn(
        {
          err,
          registry,
          dockerRepository: repository,
          tag,
        },
        'docker registry failure: internal error'
      );
    } else if (err.code === 'ETIMEDOUT') {
      logger.info(
        { registry },
        'Timeout when attempting to connect to docker registry'
      );
      logger.debug({ err });
    } else {
      logger.warn({ err }, 'Unknown error getting Docker labels');
    }
    return {};
  }
}
124203
async def tag(self, name: str, repo: str, *, tag: str = None) -> bool:
        
        params = {"repo": repo}

        if tag:
            params["tag"] = tag

        await self.docker._query(
            "images/{name}/tag".format(name=name),
            "POST",
            params=params,
            headers={"content-type": "application/json"},
        )
        return True
422072
function(tag, confImage, callback) {

      grunt.log.subhead(actioning[action] + ' image [' + tag + ']');

      async.waterfall([

      // Step 1: search for a running container with the same image
      function(cb) {
        docker.listContainers({
          all : 1,
        // filters: (action !== 'unpause') ? '{"status":["running"]}' : null
        }, function(err, containers) {

          if (err) {
            return cb(err);
          }

          var container = null;

          for (var c = 0; c < containers.length; c++) {
            if (containers[c].Image.indexOf(utils.qualifiedImageName(tag,
                  options.registry, null)) === 0) {
              container = containers[c];
              break;
            }
          }

          cb(null, container);
        });
      },

      // Step 2: stop it
      function(container, cb) {
        if (container) {
          grunt.log.writeln("Found a matched container, " + action + " it.");

          var dockcontainer = docker.getContainer(container.Id);

          var opts = confImage.options && confImage.options[action] || {};
          dockcontainer[action](opts, function(e, stream) {
            if (stream && stream.readable) {
              stream.setEncoding('utf8');
              stream.on('error', cb);
              stream.on('end', cb);
              stream.on('data', grunt.log.write);
            } else {
              cb(e);
            }

          });
        } else {
          grunt.log.writeln("No matched container with this image.");
          cb(null);
        }
      }, ], callback);

    }
249978
def is_installed(self, name: str) -> bool:
        
        assert name is not None
        try:
            self.__docker.images.get(name)
            return True
        except docker.errors.ImageNotFound:
            return False
1204853
def get_imagestreamtag_from_image(image):
    
    ret = image

    # Remove the registry part
    ret = strip_registry_from_image(image)

    # ImageStream names cannot contain '/'
    ret = ret.replace('/', '-')

    # If there is no ':' suffix value, add one
    if ret.find(':') == -1:
        ret += ":latest"

    return ret
410565
def fetch_image(client, name):
    
    try:
        image = client.images.get(name)
    except docker.errors.ImageNotFound:
        name, tag = _parse_image_tag(name)
        tag = 'latest' if tag is None else tag

        log.info("Pulling tag '{}' for image '{}'...".format(tag, name))
        image = client.images.pull(name, tag=tag)

    log.debug("Found image '{}' for tag '{}'".format(image.id, name))
    return image
709579
def _get_tag(repo, name):
    '''
    
    '''
    try:
        return [x for x in _all_tags(repo) if x[0] == name][0]
    except IndexError:
        return False
16099
def has_image(self, name: str) -> bool:
        
        path = "docker/images/{}".format(name)
        r = self.__api.head(path)
        if r.status_code == 204:
            return True
        elif r.status_code == 404:
            return False
        self.__api.handle_erroneous_response(r)
1223890
def verify_docker_image_sha(chain, link):
    
    cot = link.cot
    task = link.task
    errors = []

    if isinstance(task['payload'].get('image'), dict):
        # Using pre-built image from docker-image task
        docker_image_task_id = task['extra']['chainOfTrust']['inputs']['docker-image']
        log.debug("Verifying {} {} against docker-image {}".format(
            link.name, link.task_id, docker_image_task_id
        ))
        if docker_image_task_id != task['payload']['image']['taskId']:
            errors.append("{} {} docker-image taskId isn't consistent!: {} vs {}".format(
                link.name, link.task_id, docker_image_task_id,
                task['payload']['image']['taskId']
            ))
        else:
            path = task['payload']['image']['path']
            # we need change the hash alg everywhere if we change, and recreate
            # the docker images...
            image_hash = cot['environment']['imageArtifactHash']
            alg, sha = image_hash.split(':')
            docker_image_link = chain.get_link(docker_image_task_id)
            upstream_sha = docker_image_link.cot['artifacts'].get(path, {}).get(alg)
            if upstream_sha is None:
                errors.append("{} {} docker-image docker sha {} is missing! {}".format(
                    link.name, link.task_id, alg,
                    docker_image_link.cot['artifacts'][path]
                ))
            elif upstream_sha != sha:
                errors.append("{} {} docker-image docker sha doesn't match! {} {} vs {}".format(
                    link.name, link.task_id, alg, sha, upstream_sha
                ))
            else:
                log.debug("Found matching docker-image sha {}".format(upstream_sha))
    else:
        prebuilt_task_types = chain.context.config['prebuilt_docker_image_task_types']
        if prebuilt_task_types != "any" and link.task_type not in prebuilt_task_types:
            errors.append(
                "Task type {} not allowed to use a prebuilt docker image!".format(
                    link.task_type
                )
            )
    raise_on_errors(errors)
157637
def __get_tags(vm_):
    '''
    
    '''
    t = config.get_cloud_config_value(
        'tags', vm_, __opts__,
        default='[]', search_global=False)
    # Consider warning the user that the tags in the cloud profile
    # could not be interpreted, bad formatting?
    try:
        tags = literal_eval(t)
    except Exception:  # pylint: disable=W0703
        tags = None
    if not tags or not isinstance(tags, list):
        tags = None
    return tags
936073
def docker_list(registry_pass):
    # type: (str) -> None
    
    registry = conf.get('docker.registry', None)

    if registry is None:
        log.err("You must define docker.registry conf variable to list images")
        sys.exit(-1)

    registry_user = conf.get('docker.registry_user', None)

    if registry_user is None:
        registry_user = click.prompt("Username")

    rc = client.RegistryClient(registry, registry_user, registry_pass)
    images = {x: rc.list_tags(x) for x in rc.list_images()}

    shell.cprint("<32>Images in <34>{} <32>registry:", registry)
    for image, tags in images.items():
        shell.cprint('  <92>{}', image)
        for tag in tags:
            shell.cprint('      <90>{}:<35>{}', image, tag)
485986
def push_images():
    # type: () -> None
    
    registry = conf.get('docker.registry')
    docker_images = conf.get('docker.images', [])

    if registry is None:
        log.err("You must define docker.registry conf variable to push images")
        sys.exit(-1)

    for image in docker_images:
        push_image(registry, image)
792806
def check_existing_vr_tag(self):
        
        primary_images = get_primary_images(self.workflow)

        if not primary_images:
            return

        vr_image = None
        for image in primary_images:
            if '-' in image.tag:
                vr_image = image
                break
        if not vr_image:
            return

        should_fail = False
        for registry_name, registry in self.registries.items():
            pullspec = vr_image.copy()
            pullspec.registry = registry_name
            insecure = registry.get('insecure', False)
            secret = registry.get('secret', None)

            manifest_list = get_manifest_list(pullspec, registry_name, insecure, secret)

            if manifest_list:
                self.log.error("Primary tag already exists in registry: %s", pullspec)
                should_fail = True

        if should_fail:
            raise RuntimeError("Primary tag already exists in registry")