Python docker.sock() Examples

The following are 8 code examples of docker.sock(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module docker , or try the search function .
Example #1
Source File: docker_monitor.py    From scalyr-agent-2 with Apache License 2.0 6 votes vote down vote up
def __get_socket_file(self):
        """Gets the Docker API socket file and validates that it is a UNIX socket
        """
        # make sure the API socket exists and is a valid socket
        api_socket = self._config.get("api_socket")
        try:
            st = os.stat(api_socket)
            if not stat.S_ISSOCK(st.st_mode):
                raise Exception()
        except Exception:
            raise Exception(
                "The file '%s' specified by the 'api_socket' configuration option does not exist or is not a socket.\n\tPlease make sure you have mapped the docker socket from the host to this container using the -v parameter.\n\tNote: Due to problems Docker has mapping symbolic links, you should specify the final file and not a path that contains a symbolic link, e.g. map /run/docker.sock rather than /var/run/docker.sock as on many unices /var/run is a symbolic link to the /run directory."
                % api_socket
            )

        return api_socket 
Example #2
Source File: kubernetes_monitor.py    From scalyr-agent-2 with Apache License 2.0 6 votes vote down vote up
def __get_socket_file(self):
        """Gets the Docker API socket file and validates that it is a UNIX socket
        """
        # make sure the API socket exists and is a valid socket
        api_socket = self._config.get("api_socket")
        try:
            st = os.stat(api_socket)
            if not stat.S_ISSOCK(st.st_mode):
                raise Exception()
        except Exception:
            raise Exception(
                "The file '%s' specified by the 'api_socket' configuration option does not exist or is not a socket.\n\tPlease make sure you have mapped the docker socket from the host to this container using the -v parameter.\n\tNote: Due to problems Docker has mapping symbolic links, you should specify the final file and not a path that contains a symbolic link, e.g. map /run/docker.sock rather than /var/run/docker.sock as on many unices /var/run is a symbolic link to the /run directory."
                % api_socket
            )

        return api_socket 
Example #3
Source File: docker.py    From gigantum-client with MIT License 6 votes vote down vote up
def _get_docker_server_api_version() -> str:
    """Retrieve the Docker server API version. """

    socket_path = '/var/run/docker.sock'
    if not os.path.exists(socket_path):
        raise ValueError('No docker.sock on machine (is a Docker server installed?)')

    socket_connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    socket_connection.connect(socket_path)
    socket_connection.send(b'GET http://*/version HTTP/1.1\r\nHost: *\r\n\r\n')

    response_data = socket_connection.recv(4000)
    content_lines = response_data.decode().split('\r\n')

    version_dict = json.loads(content_lines[-1])
    if 'ApiVersion' not in version_dict.keys():
        raise ValueError('ApiVersion not in Docker version config data')
    else:
        return version_dict['ApiVersion'] 
Example #4
Source File: runner_host.py    From popper with MIT License 6 votes vote down vote up
def _get_container_kwargs(self, step, img, name):
        args = {
            "image": img,
            "command": list(step.args),
            "name": name,
            "volumes": [
                f"{self._config.workspace_dir}:/workspace",
                "/var/run/docker.sock:/var/run/docker.sock",
            ],
            "working_dir": step.dir if step.dir else "/workspace",
            "environment": self._prepare_environment(step),
            "entrypoint": step.runs if step.runs else None,
            "detach": not self._config.pty,
            "tty": self._config.pty,
            "stdin_open": self._config.pty,
        }

        self._update_with_engine_config(args)

        log.debug(f"container args: {pu.prettystr(args)}\n")

        return args 
Example #5
Source File: docker_monitor.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def stop(self, wait_on_join=True, join_timeout=5):
        if self.__client and self.__logs and self.__logs.response:
            sock = self.__client._get_raw_response_socket(self.__logs.response)
            if sock:
                sock.shutdown(socket.SHUT_RDWR)
        self.__thread.stop(wait_on_join=wait_on_join, join_timeout=join_timeout) 
Example #6
Source File: browser.py    From airgun with GNU General Public License v3.0 5 votes vote down vote up
def _init_client(self):
        """Init docker client.

        Make sure that docker service to be published under the
        ``unix://var/run/docker.sock`` unix socket.

        Use auto for version in order to allow docker client to automatically
        figure out the server version.
        """
        if self._client:
            return
        self._client = docker.Client(
            base_url='unix://var/run/docker.sock', version='auto') 
Example #7
Source File: docker_remote.py    From universe with MIT License 4 votes vote down vote up
def get_client():
    """
    Set DOCKER_HOST (and probably DOCKER_TLS_VERIFY and DOCKER_CERT_PATH) to connect to a docker instance through TCP.
    Leave DOCKER_HOST unset and it will use the default, typically unix:/var/run/docker.sock

    It also needs to know how to connect to ports on the docker container after creating it.
    Set DOCKER_NET_HOST to provide an IP address to connect to the VNC ports on
    otherwise if DOCKER_HOST has a hostname, it will connect to the VNC ports using that name.
    otherwise it connects using localhost
    """
    info = {}
    host = os.environ.get('DOCKER_HOST')
    net_host = os.environ.get('DOCKER_NET_HOST')

    client_api_version = os.environ.get('DOCKER_API_VERSION')
    if not client_api_version:
        client_api_version = "auto"

    # IP to use for started containers
    if net_host:
        info['host'] = net_host
    elif host:
        info['host'] = urlparse.urlparse(host).netloc.split(':')[0]
    else:
        info['host'] = 'localhost'

    verify = os.environ.get('DOCKER_TLS_VERIFY') == '1'
    if verify: # use TLS
        assert_hostname = None
        cert_path = os.environ.get('DOCKER_CERT_PATH')
        if cert_path:
            client_cert = (os.path.join(cert_path, 'cert.pem'), os.path.join(cert_path, 'key.pem'))
            ca_cert = os.path.join(cert_path, 'ca.pem')
        else:
            client_cert = ca_cert = None

        tls_config = docker.tls.TLSConfig(
            client_cert=client_cert,
            ca_cert=ca_cert,
            verify=verify,
            assert_hostname=assert_hostname,
        )
        return docker.Client(base_url=host, tls=tls_config, version=client_api_version), info
    else:
        return docker.Client(base_url=host, version=client_api_version), info 
Example #8
Source File: utils.py    From appstart with Apache License 2.0 4 votes vote down vote up
def get_docker_client():
    """Get the user's docker client.

    Raises:
        AppstartAbort: If there was an error in connecting to the
            Docker Daemon.

    Returns:
        (docker.Client) a docker client that can be used to manage
        containers and images.
    """
    host = os.environ.get('DOCKER_HOST')
    cert_path = os.environ.get('DOCKER_CERT_PATH')
    tls_verify = int(os.environ.get('DOCKER_TLS_VERIFY', 0))

    params = {}
    if host:
        params['base_url'] = (host.replace('tcp://', 'https://')
                              if tls_verify else host)
    elif sys.platform.startswith('linux'):
        # if this is a linux user, the default value of DOCKER_HOST
        # should be the unix socket.  first check if the socket is
        # valid to give a better feedback to the user.
        if os.path.exists(LINUX_DOCKER_HOST):
            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            try:
                sock.connect(LINUX_DOCKER_HOST)
                params['base_url'] = 'unix://' + LINUX_DOCKER_HOST
            except socket.error:
                get_logger().warning('Found a stale '
                                     '/var/run/docker.sock, '
                                     'did you forget to start '
                                     'your docker daemon?')
            finally:
                sock.close()

    if tls_verify and cert_path:
        # assert_hostname=False is needed for boot2docker to work with
        # our custom registry.
        params['tls'] = docker.tls.TLSConfig(
            client_cert=(os.path.join(cert_path, 'cert.pem'),
                         os.path.join(cert_path, 'key.pem')),
            ca_cert=os.path.join(cert_path, 'ca.pem'),
            verify=True,
            ssl_version=ssl.PROTOCOL_TLSv1,
            assert_hostname=False)

    # pylint: disable=star-args
    client = ClientWrapper(version=DOCKER_API_VERSION,
                           timeout=TIMEOUT_SECS,
                           **params)
    try:
        client.ping()
    except requests.exceptions.ConnectionError as excep:
        raise AppstartAbort('Failed to connect to Docker '
                            'Daemon due to: {0}'.format(excep.message))
    return client