예제 #1
0
def docker():
    """
    Obbtain information on docker containers, if possible.

    :return: list of dictionaries
    """
    try:
        client = docker_from_env(
            version=os.environ.get('DOCKER_API_VERSION', '1.24'))

        containers = []

        for container in client.containers.list():
            include_container = False
            if INTERESTING_CONTAINERS.search(container.name):
                include_container = True
            else:
                for tag in container.image.attrs.get('RepoTags', []):
                    if INTERESTING_TAGS.match(tag):
                        include_container = True
                        break

            if not include_container:
                continue

            docker_metrics = {
                "stats_type": "docker",
                "docker": {
                    "id": container.short_id,
                    "name": container.name,
                    "status": container.status,
                    "labels": ["%s=%s" % (k, v)
                               for k, v in container.labels.items()],
                    "tags": container.image.attrs['RepoTags'],
                    'created': container.image.attrs['Created'],
                }
            }
            if 'version' in container.labels:
                docker_metrics['docker']['image_version'] = \
                    container.labels['version']
            containers.append(docker_metrics)

    except Exception as exc:
        logging.debug("Error gathering Docker info: %s", exc)
        return []

    return containers
예제 #2
0
def docker():
    """Fixture to return a connected docker client

    cleans up any containers we leave in docker
    """
    d = docker_from_env()
    try:
        yield d

    finally:
        # cleanup our containers
        for c in d.containers.list(all=True):
            if c.name.startswith("dockerspawner-test"):
                c.stop()
                c.remove()

        for c in d.services.list():
            if c.name.startswith("dockerspawner-test"):
                c.remove()
def docker():
    """Fixture to return a connected docker client

    cleans up any containers we leave in docker
    """
    d = docker_from_env()
    try:
        yield d

    finally:
        # cleanup our containers
        for c in d.containers.list(all=True):
            if c.name.startswith("dockerspawner-test"):
                c.stop()
                c.remove()
        try:
            services = d.services.list()
        except APIError:
            # e.g. services not available
            return
        else:
            for s in services:
                if s.name.startswith("dockerspawner-test"):
                    s.remove()
예제 #4
0
def docker():
    """Fixture to return a connected docker client

    cleans up any containers we leave in docker
    """
    d = docker_from_env()
    try:
        yield d

    finally:
        # cleanup our containers
        for c in d.containers.list(all=True):
            if c.name.startswith("dockerspawner-test"):
                c.stop()
                c.remove()
        try:
            services = d.services.list()
        except APIError:
            # e.g. services not available
            return
        else:
            for s in services:
                if s.name.startswith("dockerspawner-test"):
                    s.remove()
예제 #5
0
def docker():
    client = docker_from_env(version='auto')
    return client
예제 #6
0
    def _run_docker(
        self, bash_script, run_kwargs, log_name, root=False, append_to_log=False
    ):
        docker_image = self.docker_image
        client = docker_from_env()
        tf = tempfile.NamedTemporaryFile(mode="w")
        volumes = {
            "/anysnake/run.sh": tf.name,
            "/etc/passwd": (
                "/etc/passwd",
                "ro",
            ),  # the users inside are the users outside
            "/etc/group": ("/etc/group", "ro"),
            # "/etc/shadow": ("/etc/shadow", 'ro'),
            "/anysnake/gosu": str(self.paths["bin"] / "gosu-amd64"),
            Path("~").expanduser(): self.paths["home_inside_docker"],
        }
        volumes.update(run_kwargs["volumes"])
        volume_args = {}
        for k, v in volumes.items():
            k = str(Path(k).absolute())
            if isinstance(v, tuple):
                volume_args[str(v[0])] = {"bind": str(k), "mode": v[1]}
            else:
                volume_args[str(v)] = {"bind": k, "mode": "rw"}
        run_kwargs["volumes"] = volume_args
        # print(run_kwargs["volumes"])
        # if not root and not "user" in run_kwargs:
        # run_kwargs["user"] = "******" % (self.get_login_username(), os.getgid())
        tf.write(f"umask 0002\n")  # allow sharing by default
        tf.write(bash_script)
        tf.flush()
        container = client.containers.create(
            docker_image,
            (
                ["/bin/bash", "/anysnake/run.sh"]
                if root
                else [
                    "/anysnake/gosu",
                    self.get_login_username(),
                    "/bin/bash",
                    "/anysnake/run.sh",
                ]
            ),
            **run_kwargs,
        )
        container_result = b""
        try:
            return_code = -1
            container.start()
            gen = container.logs(stdout=True, stderr=True, stream=True)
            for piece in gen:
                container_result += piece
                print(piece.decode("utf-8"), end="")
                sys.stdout.flush()
            return_code = container.wait()
        except KeyboardInterrupt:
            container.kill()

        if hasattr(log_name, "write"):
            log_name.write(container_result)
        elif log_name:
            if append_to_log:
                with open(str(self.paths[log_name]), "ab") as op:
                    op.write(container_result)
            else:
                self.paths[log_name].write_bytes(container_result)
        return return_code, container_result