More or less stolen from docker-py's kwargs_from_env
    https://github.com/docker/docker-py/blob/c0ec5512ae7ab90f7fac690064e37181186b1928/docker/utils/utils.py
    :type client : docker.Client
170677
def kwargs_from_client(client, assert_hostname=False):
    
    from docker import tls
    if client.base_url in ('http+docker://localunixsocket', 'http+docker://localhost'):
        return {'base_url': 'unix://var/run/docker.sock'}

    params = {'base_url': client.base_url}
    if client.cert:
        # TODO: problem - client.cert is filepaths, and it would be insecure to send those files.
        params['tls'] = tls.TLSConfig(
            client_cert=client.cert,
            ca_cert=client.verify,
            verify=bool(client.verify),
            assert_hostname=assert_hostname)

    return params
217209
async def get_docker_version(self):
        """"""
        if self.image not in IMAGES:
            _LOGGER.warning("%s is not a valid image using default", self.image)
            self.image = "default"

        self._version_data["beta"] = self.beta
        self._version_data["source"] = "Docker"
        self._version_data["image"] = IMAGES[self.image]["docker"]
        try:
            async with async_timeout.timeout(5, loop=self.loop):
                response = await self.session.get(
                    URL["docker"].format(IMAGES[self.image]["docker"])
                )
                data = await response.json()
                for version in data["results"]:
                    if version["name"] in ["latest", "landingpage", "rc", "dev"]:
                        continue
                    elif re.search(r"\b.+b\d", version["name"]):
                        if self.beta:
                            self._version = version["name"]
                            break
                        else:
                            continue
                    else:
                        self._version = version["name"]

                    if self._version is not None:
                        break
                    else:
                        continue

            _LOGGER.debug("Version: %s", self.version)
            _LOGGER.debug("Version data: %s", self.version_data)
        except asyncio.TimeoutError as error:
            _LOGGER.error("Timeouterror fetching version information for docker")
        except KeyError as error:
            _LOGGER.error("Error parsing version information for docker, %s", error)
        except TypeError as error:
            _LOGGER.error("Error parsing version information for docker, %s", error)
        except aiohttp.ClientError as error:
            _LOGGER.error("Error fetching version information for docker, %s", error)
        except socket.gaierror as error:
            _LOGGER.error("Error fetching version information for docker, %s", error)
        except Exception as error:  # pylint: disable=broad-except
            _LOGGER.critical("Something really wrong happend! - %s", error)
1260654
function dockerCommand(options) {
  const cmd = 'docker';
  const ps = spawnSync(cmd, options, { encoding: 'utf-8' });
  if (ps.error) {
    if (ps.error.code === 'ENOENT') {
      throw new Error('docker not found! Please install it.');
    }
    throw new Error(ps.error);
  } else if (ps.status !== 0) {
    throw new Error(ps.stderr);
  }
  return ps;
}
357860
def container(dec):
    
    # Credits: http://stackoverflow.com/a/1167248/1798683
    @wraps(dec)
    def meta_decorator(f):
        decorator = dec(f)
        decorator.orig_func = f
        return decorator
    return meta_decorator
275536
def docker_py_dict(self):
        
        return {
            'image': self.image,
            'command': self.cmd,
            'hostname': self.hostname,
            'user': self.user,
            'detach': self.detach,
            'stdin_open': self.open_stdin,
            'tty': self.tty,
            'ports': self.exposed_ports,
            'environment': self.env,
            'volumes': self.volumes,
            'network_disabled': self.network_disabled,
            'entrypoint': self.entry_point,
            'working_dir': self.working_dir,
            'domainname': self.domain_name,
            'labels': self.labels
        }
32095
def pull_stream(image):
    
    return (json.loads(s) for s in _get_docker().pull(image, stream=True))
1286072
def ensure_docker_can_run() -> None:
    
    logger.info("checking docker can run")
    version = docker_client.version()["ApiVersion"]
    docker_client.containers.run("hello-world")
    logger.debug(f"using docker API version {version}")
509656
function pullImageIfMissing(docker, image, options) {
  debug('ensure image', image);
  var pullStream = new PullStatusStream();

  // first attempt to find the image locally...
  docker.getImage(image).inspect().then(
    function inspection(gotImg) {
      // push a value directly to the result without the transform.
      pullStream.push(image + ' exists in the cache.\r\n');
      // end the stream.
      pullStream.end();
    },

    function missingImage() {
      debug('image is missing pull', image);
      // image is missing so pull it
      return docker.pull(image, options || {}).then(function(rawPullStream) {
        rawPullStream.pipe(pullStream);
      });
    }
  ).then(
    null,
    function handleErrors(err) {
      pullStream.emit('error', err);
    }
  );

  return pullStream;
}
691574
def getImage(path, dockerfile, tag):
    '''
    '''
    image = getImageByTag(tag)

    if not image:
        # Build an Image using the dockerfile in the path
        try:
            image = client.images.build(
              path=path,
              dockerfile=dockerfile,
              tag=tag
            )
        except BuildError as exc:
            eprint("Failed to build docker image")
            raise exc
        except TypeError as exc:
            eprint("You must give a path to the build environemnt.")
            raise exc
        except APIError as exc:
            eprint("Unhandled error while building image", tag)
            raise exc

    return image
176703
def build_env(client, req)
      rack_env = DefaultRackEnv.dup
      req.fill_rack_env(rack_env)
      rack_env["SERVER_PORT"] ||= @port.to_s
      
      if (rack_env["rack.input"].respond_to? :set_encoding)
        rack_env["rack.input"].set_encoding "ASCII-8BIT"
      end
      
      rack_env["REMOTE_PORT"], rack_env["REMOTE_ADDR"] = Socket::unpack_sockaddr_in(client.getpeername)
      rack_env["REMOTE_PORT"] &&= rack_env["REMOTE_PORT"].to_s
      rack_env["SERVER_PROTOCOL"] = "HTTP/" << req.version.join('.')
      
      return rack_env      
    end
1074793
def download_containers(self, to_download, current_options):
        
        if current_options["backend"] == "local":
            self._display_info("Connecting to the local Docker daemon...")
            try:
                docker_connection = docker.from_env()
            except:
                self._display_error("Cannot connect to local Docker daemon. Skipping download.")
                return

            for image in to_download:
                try:
                    self._display_info("Downloading image %s. This can take some time." % image)
                    docker_connection.images.pull(image + ":latest")
                except Exception as e:
                    self._display_error("An error occurred while pulling the image: %s." % str(e))
        else:
            self._display_warning(
                "This installation tool does not support the backend configuration directly, if it's not local. You will have to "
                "pull the images by yourself. Here is the list: %s" % str(to_download))
1351066
def pull_image(self, name, tag='latest'):
        
        name = "{0}/{1}:{2}".format(DOCKER_NEG, name, tag)
        return "/dockerapi/v2/images", dict(image=name)
1192722
def shared_client(ClientType, *args, **kwargs):
    
    kwarg_key = tuple((key, kwargs[key]) for key in sorted(kwargs))
    cache_key = (ClientType, args, kwarg_key)
    client = None
    if cache_key in _client_cache:
        # resolve cached weakref
        # client can still be None after this!
        client = _client_cache[cache_key]()

    if client is None:
        Client = getattr(kubernetes.client, ClientType)
        client = Client(*args, **kwargs)
        # cache weakref so that clients can be garbage collected
        _client_cache[cache_key] = weakref.ref(client)
    return client
244890
def Client(api_version, *args, **kwargs):
    
    neutron_client = utils.get_client_class(
        API_NAME,
        api_version,
        API_VERSIONS,
    )
    return neutron_client(*args, **kwargs)
784952
def unpack_auth_b64(self, docker_registry):
        
        UnpackedAuth = namedtuple('UnpackedAuth', ['raw_str', 'username', 'password'])
        credentials = self.get_credentials(docker_registry)
        auth_b64 = credentials.get('auth')
        if auth_b64:
            raw_str = b64decode(auth_b64).decode('utf-8')
            unpacked_credentials = raw_str.split(':', 1)
            if len(unpacked_credentials) == 2:
                return UnpackedAuth(raw_str, *unpacked_credentials)
            else:
                raise ValueError("Failed to parse 'auth' in '%s'" % self.json_secret_path)
899701
def docker_client():
    
    cert_path = os.environ.get('DOCKER_CERT_PATH', '')
    if cert_path == '':
        cert_path = os.path.join(os.environ.get('HOME', ''), '.docker')

    base_url = os.environ.get('DOCKER_HOST')
    tls_config = None

    if os.environ.get('DOCKER_TLS_VERIFY', '') != '':
        parts = base_url.split('://', 1)
        base_url = '%s://%s' % ('https', parts[1])

        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')

        tls_config = tls.TLSConfig(
            ssl_version=ssl.PROTOCOL_TLSv1,
            verify=True,
            assert_hostname=False,
            client_cert=client_cert,
            ca_cert=ca_cert,
        )

    timeout = int(os.environ.get('DOCKER_CLIENT_TIMEOUT', 60))
    return Client(
        base_url=base_url, tls=tls_config, version='1.15', timeout=timeout
    )
22470
def from_ps(cls, client, dictionary, **kwargs):
        
        name = get_container_name(dictionary)
        if name is None:
            return None

        new_dictionary = {
            'Id': dictionary['Id'],
            'Image': dictionary['Image'],
            'Name': '/' + name,
        }
        return cls(client, new_dictionary, **kwargs)