Command: docker_image_ids
502046
def docker_image_ids(broker):
        """"""
        images = broker[DefaultSpecs.docker_list_images]
        try:
            result = set()
            for l in images.content[1:]:
                result.add(l.split(None)[3].strip())
        except:
            raise ContentException("No docker images.")
        if result:
            return list(result)
        raise ContentException("No docker images.")
1206992
def _save_image(self, image_id, directory):
        

        for x in [0, 1, 2]:
            self.log.info("Saving image %s to %s directory..." %
                          (image_id, directory))
            self.log.debug("Try #%s..." % (x + 1))

            try:
                image = self.docker.get_image(image_id)

                if docker.version_info[0] < 3:
                    # Docker library prior to 3.0.0 returned the requests
                    # object directly which cold be used to read from
                    self.log.debug("Extracting image using HTTPResponse object directly")
                    self._extract_tar(image, directory)
                else:
                    # Docker library >=3.0.0 returns iterator over raw data
                    self.log.debug("Extracting image using iterator over raw data")

                    fd_r, fd_w = os.pipe()

                    r = os.fdopen(fd_r, 'rb')
                    w = os.fdopen(fd_w, 'wb')

                    extracter = threading.Thread(target=self._extract_tar, args=(r,directory))
                    extracter.start()

                    for chunk in image:
                        w.write(chunk)

                    w.flush()
                    w.close()

                    extracter.join()
                    r.close()
                self.log.info("Image saved!")
                return True
            except Exception as e:
                self.log.exception(e)
                self.log.warn(
                    "An error occured while saving the %s image, retrying..." % image_id)

        raise SquashError("Couldn't save %s image!" % image_id)
987015
def image_id(self):
        
        try:
            # docker >= 1.9
            image_id = self.data["ImageID"]
        except KeyError:
            # docker <= 1.8
            image_id = self.metadata_get(["Image"])
        return image_id
1343940
def image_dir(image)
      relative = File.join "docker", env, image
      File.expand_path relative, Dir.pwd
    end
537064
def get_image(docker_requirement,     # type: Dict[Text, Text]
                  pull_image,             # type: bool
                  force_pull=False,       # type: bool
                  tmp_outdir_prefix=DEFAULT_TMP_PREFIX  # type: Text
                 ):  # type: (...) -> bool
        
        found = False

        if "dockerImageId" not in docker_requirement \
                and "dockerPull" in docker_requirement:
            docker_requirement["dockerImageId"] = docker_requirement["dockerPull"]

        with _IMAGES_LOCK:
            if docker_requirement["dockerImageId"] in _IMAGES:
                return True

        for line in subprocess.check_output(
                ["docker", "images", "--no-trunc", "--all"]).decode('utf-8').splitlines():
            try:
                match = re.match(r"^([^ ]+)\s+([^ ]+)\s+([^ ]+)", line)
                split = docker_requirement["dockerImageId"].split(":")
                if len(split) == 1:
                    split.append("latest")
                elif len(split) == 2:
                    #  if split[1] doesn't  match valid tag names, it is a part of repository
                    if not re.match(r'[\w][\w.-]{0,127}', split[1]):
                        split[0] = split[0] + ":" + split[1]
                        split[1] = "latest"
                elif len(split) == 3:
                    if re.match(r'[\w][\w.-]{0,127}', split[2]):
                        split[0] = split[0] + ":" + split[1]
                        split[1] = split[2]
                        del split[2]

                # check for repository:tag match or image id match
                if (match
                        and (
                            (split[0] == match.group(1) and split[1] == match.group(2))
                            or docker_requirement["dockerImageId"] == match.group(3))):
                    found = True
                    break
            except ValueError:
                pass

        if (force_pull or not found) and pull_image:
            cmd = []  # type: List[Text]
            if "dockerPull" in docker_requirement:
                cmd = ["docker", "pull", str(docker_requirement["dockerPull"])]
                _logger.info(Text(cmd))
                subprocess.check_call(cmd, stdout=sys.stderr)
                found = True
            elif "dockerFile" in docker_requirement:
                dockerfile_dir = str(tempfile.mkdtemp(prefix=tmp_outdir_prefix))
                with open(os.path.join(
                        dockerfile_dir, "Dockerfile"), "wb") as dfile:
                    dfile.write(docker_requirement["dockerFile"].encode('utf-8'))
                cmd = ["docker", "build", "--tag=%s" %
                       str(docker_requirement["dockerImageId"]), dockerfile_dir]
                _logger.info(Text(cmd))
                subprocess.check_call(cmd, stdout=sys.stderr)
                found = True
            elif "dockerLoad" in docker_requirement:
                cmd = ["docker", "load"]
                _logger.info(Text(cmd))
                if os.path.exists(docker_requirement["dockerLoad"]):
                    _logger.info(u"Loading docker image from %s", docker_requirement["dockerLoad"])
                    with open(docker_requirement["dockerLoad"], "rb") as dload:
                        loadproc = subprocess.Popen(cmd, stdin=dload, stdout=sys.stderr)
                else:
                    loadproc = subprocess.Popen(cmd, stdin=subprocess.PIPE,
                                                stdout=sys.stderr)
                    assert loadproc.stdin is not None  # nosec
                    _logger.info(u"Sending GET request to %s", docker_requirement["dockerLoad"])
                    req = requests.get(docker_requirement["dockerLoad"], stream=True)
                    size = 0
                    for chunk in req.iter_content(1024 * 1024):
                        size += len(chunk)
                        _logger.info("\r%i bytes", size)
                        loadproc.stdin.write(chunk)
                    loadproc.stdin.close()
                rcode = loadproc.wait()
                if rcode != 0:
                    raise WorkflowException(
                        "Docker load returned non-zero exit status %i" % (rcode))
                found = True
            elif "dockerImport" in docker_requirement:
                cmd = ["docker", "import", str(docker_requirement["dockerImport"]),
                       str(docker_requirement["dockerImageId"])]
                _logger.info(Text(cmd))
                subprocess.check_call(cmd, stdout=sys.stderr)
                found = True

        if found:
            with _IMAGES_LOCK:
                _IMAGES.add(docker_requirement["dockerImageId"])

        return found
520582
def push_image(self, image, insecure=False):
        
        logger.info("pushing image '%s'", image)
        logger.debug("image: '%s', insecure: '%s'", image, insecure)
        try:
            # push returns string composed of newline separated jsons; exactly what 'docker push'
            # outputs
            command_result = self.retry_generator(self.d.push,
                                                  image.to_str(tag=False),
                                                  tag=image.tag, insecure_registry=insecure,
                                                  decode=True, stream=True)
        except TypeError:
            # because changing api is fun
            command_result = self.retry_generator(self.d.push,
                                                  image.to_str(tag=False),
                                                  tag=image.tag, decode=True, stream=True)

        self.last_logs = command_result.logs
        return command_result.parsed_logs
1145898
def build_from_id(id)
      @image = ::Docker::Image.get(id)
      add_repository_tag
    rescue ::Docker::Error::NotFoundError
      @image = ::Docker::Image.create('fromImage' => id)
      add_repository_tag
    rescue ::Docker::Error::DockerError => e
      DockerExceptionParser.new(e)
    end
521667
def handle(self, *args, **options):
        """"""
        verbosity = int(options.get('verbosity'))

        # Check that the specified output format is valid
        if options['format'] != 'plain' and options['format'] != 'yaml':
            raise CommandError("Unknown output format: %s" % options['format'])

        # Gather only unique latest custom Docker requirements that the processes are using
        # The 'image' field is optional, so be careful about that as well
        unique_docker_images = set(
            p.requirements['executor']['docker']['image']
            for p in Process.objects.filter(is_active=True).order_by(
                'slug', '-version'
            ).distinct(
                'slug'
            ).only(
                'requirements'
            ).filter(
                requirements__icontains='docker'
            )
            if 'image' in p.requirements.get('executor', {}).get('docker', {})
        )

        # Add the default image.
        unique_docker_images.add(DEFAULT_CONTAINER_IMAGE)

        # Pull images if requested or just output the list in specified format
        if options['pull']:
            # Remove set of already pulled images.
            with PULLED_IMAGES_LOCK:
                unique_docker_images.difference_update(PULLED_IMAGES)

            # Get the desired 'docker' command from settings or use the default
            docker = getattr(settings, 'FLOW_DOCKER_COMMAND', 'docker')

            # Pull each image
            for img in unique_docker_images:
                ret = subprocess.call(
                    shlex.split('{} pull {}'.format(docker, img)),
                    stdout=None if verbosity > 0 else subprocess.DEVNULL,
                    stderr=None if verbosity > 0 else subprocess.DEVNULL,
                )

                # Update set of pulled images.
                with PULLED_IMAGES_LOCK:
                    PULLED_IMAGES.add(img)

                if ret != 0:
                    errmsg = "Failed to pull Docker image '{}'!".format(img)

                    if not options['ignore_pull_errors']:
                        # Print error and stop execution
                        raise CommandError(errmsg)
                    else:
                        # Print error, but keep going
                        logger.error(errmsg)
                        if verbosity > 0:
                            self.stderr.write(errmsg)
                else:
                    msg = "Docker image '{}' pulled successfully!".format(img)
                    logger.info(msg)
                    if verbosity > 0:
                        self.stdout.write(msg)
        else:
            # Sort the set of unique Docker images for nicer output.
            unique_docker_images = sorted(unique_docker_images)

            # Convert the set of unique Docker images into a list of dicts for easier output
            imgs = [
                dict(name=s[0], tag=s[1] if len(s) == 2 else 'latest')
                for s in (img.split(':') for img in unique_docker_images)
            ]

            # Output in YAML or plaintext (one image per line), as requested
            if options['format'] == 'yaml':
                out = yaml.safe_dump(imgs, default_flow_style=True, default_style="'")
            else:
                out = functools.reduce(operator.add,
                                       ('{name}:{tag}\n'.format(**i) for i in imgs), '')

            self.stdout.write(out, ending='')
82853
def build_docker(ctx, image):
    
    if image not in DOCKER_IMGS:
        print('Error: unknown docker image "{0}"!'.format(image), file=sys.stderr)
        sys.exit(1)

    dinfo = DOCKER_IMGS[image]
    ctx.run('docker rmi -f {0}'.format(dinfo['name']), warn=True)
    dinfo_work_dir = os.path.join(dinfo['path'], '_work')
    ctx.run('mkdir -p {0}'.format(dinfo_work_dir))
    ctx.run('cp {0} {1}'.format(os.path.join(DOCKER_COMMON_DIR, 'sudo-as-user.sh'), dinfo_work_dir))
    ctx.run('docker build -t {0} {1}'.format(dinfo['name'], dinfo['path']))
43488
def run_bump(args):
    
    commit_id = args.commit_id
    image = args.image
    branch = args.branch

    try:
        print(version_bump(image, branch, commit_id))
    except DockerTagNamingException, de:
        print(de)
        sys.exit(1)
1078493
def _get_local_image_id(docker_binary, docker_tag):
    
    cmd = [docker_binary, "images", "-q", docker_tag]
    image_id_b = check_output(cmd)
    image_id = image_id_b.decode('utf-8').strip()
    if not image_id:
        raise RuntimeError('Unable to find docker image id matching with tag {}'.format(docker_tag))
    return image_id
112294
def list_containers(self):
        
        containers = []
        for container in self._list_podman_containers():
            identifier = container["ID"]
            name = container["Names"]
            image_name = container["Image"]

            try:
                image_name, image_tag = parse_reference(image_name)
            except (IndexError, TypeError):
                image_name, image_tag = None, None

            image = PodmanImage(image_name, tag=image_tag, identifier=None)
            container = PodmanContainer(image, identifier, name=name)
            containers.append(container)

        return containers
756882
def inspect_container(self, container_alias):

        '''
            
        '''

        title = '%s.inspect_container' % self.__class__.__name__

    # validate inputs
        input_fields = {
            'container_alias': container_alias
        }
        for key, value in input_fields.items():
            object_title = '%s(%s=%s)' % (title, key, str(value))
            self.fields.validate(value, '.%s' % key, object_title)
    
    # send inspect command
        import json
        sys_command = 'docker inspect %s' % container_alias
        output_dict = json.loads(self.command(sys_command))
        container_settings = output_dict[0]

        return container_settings
854271
async def Delete(self, image_ids):
        '''
        
        '''
        # map input types to rpc msg
        _params = dict()
        msg = dict(type='ImageMetadata',
                   request='Delete',
                   version=2,
                   params=_params)
        _params['image-ids'] = image_ids
        reply = await self.rpc(msg)
        return reply
352722
def build_images():
    # type: () -> None
    
    registry = conf.get('docker.registry')
    docker_images = conf.get('docker.images', [])

    for image in docker_images:
        build_image(registry, image)
1330992
def loadImgs(self, ids=[]):
        
        if type(ids) == list:
            return [self.imgs[id] for id in ids]
        elif type(ids) == int:
            return [self.imgs[ids]]
38936
def dockerfile_lines(self):
        
        w1 = colored(
                'WARNING: this build includes files that are built in other images!!! The generated'
                '\n         Dockerfile must be built in a directory that contains'
                ' the file/directory:',
                'red', attrs=['bold'])
        w2 = colored('         ' + self.sourcepath, 'red')
        w3 = (colored('         from image ', 'red')
              + colored(self.sourcepath, 'blue', attrs=['bold']))
        print('\n'.join((w1, w2, w3)))
        return ["",
                "# Warning: the file \"%s\" from the image \"%s\""
                " must be present in this build context!!" %
                (self.sourcepath, self.sourceimage),
                "ADD %s %s" % (os.path.basename(self.sourcepath), self.destpath),
                '']