Showing preview only (1,272K chars total). Download the full file or copy to clipboard to get everything.
Repository: docker/docker-py
Branch: main
Commit: df3f8e2abc5a
Files: 192
Total size: 1.2 MB
Directory structure:
gitextract_9q1ur1_6/
├── .coveragerc
├── .dockerignore
├── .editorconfig
├── .github/
│ └── workflows/
│ ├── ci.yml
│ └── release.yml
├── .gitignore
├── .readthedocs.yml
├── CONTRIBUTING.md
├── Dockerfile
├── Dockerfile-docs
├── LICENSE
├── MAINTAINERS
├── Makefile
├── README.md
├── docker/
│ ├── __init__.py
│ ├── api/
│ │ ├── __init__.py
│ │ ├── build.py
│ │ ├── client.py
│ │ ├── config.py
│ │ ├── container.py
│ │ ├── daemon.py
│ │ ├── exec_api.py
│ │ ├── image.py
│ │ ├── network.py
│ │ ├── plugin.py
│ │ ├── secret.py
│ │ ├── service.py
│ │ ├── swarm.py
│ │ └── volume.py
│ ├── auth.py
│ ├── client.py
│ ├── constants.py
│ ├── context/
│ │ ├── __init__.py
│ │ ├── api.py
│ │ ├── config.py
│ │ └── context.py
│ ├── credentials/
│ │ ├── __init__.py
│ │ ├── constants.py
│ │ ├── errors.py
│ │ ├── store.py
│ │ └── utils.py
│ ├── errors.py
│ ├── models/
│ │ ├── __init__.py
│ │ ├── configs.py
│ │ ├── containers.py
│ │ ├── images.py
│ │ ├── networks.py
│ │ ├── nodes.py
│ │ ├── plugins.py
│ │ ├── resource.py
│ │ ├── secrets.py
│ │ ├── services.py
│ │ ├── swarm.py
│ │ └── volumes.py
│ ├── tls.py
│ ├── transport/
│ │ ├── __init__.py
│ │ ├── basehttpadapter.py
│ │ ├── npipeconn.py
│ │ ├── npipesocket.py
│ │ ├── sshconn.py
│ │ └── unixconn.py
│ ├── types/
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── containers.py
│ │ ├── daemon.py
│ │ ├── healthcheck.py
│ │ ├── networks.py
│ │ ├── services.py
│ │ └── swarm.py
│ ├── utils/
│ │ ├── __init__.py
│ │ ├── build.py
│ │ ├── config.py
│ │ ├── decorators.py
│ │ ├── fnmatch.py
│ │ ├── json_stream.py
│ │ ├── ports.py
│ │ ├── proxy.py
│ │ ├── socket.py
│ │ └── utils.py
│ └── version.py
├── docs/
│ ├── _static/
│ │ └── custom.css
│ ├── _templates/
│ │ └── page.html
│ ├── api.rst
│ ├── change-log.md
│ ├── client.rst
│ ├── conf.py
│ ├── configs.rst
│ ├── containers.rst
│ ├── images.rst
│ ├── index.rst
│ ├── networks.rst
│ ├── nodes.rst
│ ├── plugins.rst
│ ├── secrets.rst
│ ├── services.rst
│ ├── swarm.rst
│ ├── tls.rst
│ ├── user_guides/
│ │ ├── index.rst
│ │ ├── multiplex.rst
│ │ └── swarm_services.md
│ └── volumes.rst
├── pyproject.toml
├── pytest.ini
├── scripts/
│ ├── release.sh
│ └── versions.py
├── tests/
│ ├── Dockerfile
│ ├── Dockerfile-dind-certs
│ ├── Dockerfile-ssh-dind
│ ├── __init__.py
│ ├── gpg-keys/
│ │ ├── ownertrust
│ │ └── secret
│ ├── helpers.py
│ ├── integration/
│ │ ├── __init__.py
│ │ ├── api_build_test.py
│ │ ├── api_client_test.py
│ │ ├── api_config_test.py
│ │ ├── api_container_test.py
│ │ ├── api_exec_test.py
│ │ ├── api_healthcheck_test.py
│ │ ├── api_image_test.py
│ │ ├── api_network_test.py
│ │ ├── api_plugin_test.py
│ │ ├── api_secret_test.py
│ │ ├── api_service_test.py
│ │ ├── api_swarm_test.py
│ │ ├── api_volume_test.py
│ │ ├── base.py
│ │ ├── client_test.py
│ │ ├── conftest.py
│ │ ├── context_api_test.py
│ │ ├── credentials/
│ │ │ ├── __init__.py
│ │ │ ├── create_gpg_key.sh
│ │ │ ├── store_test.py
│ │ │ └── utils_test.py
│ │ ├── errors_test.py
│ │ ├── models_containers_test.py
│ │ ├── models_images_test.py
│ │ ├── models_networks_test.py
│ │ ├── models_nodes_test.py
│ │ ├── models_resources_test.py
│ │ ├── models_services_test.py
│ │ ├── models_swarm_test.py
│ │ ├── models_volumes_test.py
│ │ ├── regression_test.py
│ │ └── testdata/
│ │ └── dummy-plugin/
│ │ ├── config.json
│ │ └── rootfs/
│ │ └── dummy/
│ │ └── file.txt
│ ├── ssh/
│ │ ├── __init__.py
│ │ ├── api_build_test.py
│ │ ├── base.py
│ │ ├── config/
│ │ │ ├── client/
│ │ │ │ ├── id_rsa
│ │ │ │ └── id_rsa.pub
│ │ │ └── server/
│ │ │ ├── known_ed25519
│ │ │ ├── known_ed25519.pub
│ │ │ ├── sshd_config
│ │ │ ├── unknown_ed25519
│ │ │ └── unknown_ed25519.pub
│ │ └── connect_test.py
│ └── unit/
│ ├── __init__.py
│ ├── api_build_test.py
│ ├── api_container_test.py
│ ├── api_exec_test.py
│ ├── api_image_test.py
│ ├── api_network_test.py
│ ├── api_test.py
│ ├── api_volume_test.py
│ ├── auth_test.py
│ ├── client_test.py
│ ├── context_test.py
│ ├── dockertypes_test.py
│ ├── errors_test.py
│ ├── fake_api.py
│ ├── fake_api_client.py
│ ├── fake_stat.py
│ ├── models_configs_test.py
│ ├── models_containers_test.py
│ ├── models_images_test.py
│ ├── models_networks_test.py
│ ├── models_resources_test.py
│ ├── models_secrets_test.py
│ ├── models_services_test.py
│ ├── sshadapter_test.py
│ ├── swarm_test.py
│ ├── testdata/
│ │ └── certs/
│ │ ├── ca.pem
│ │ ├── cert.pem
│ │ └── key.pem
│ ├── types_containers_test.py
│ ├── utils_build_test.py
│ ├── utils_config_test.py
│ ├── utils_json_stream_test.py
│ ├── utils_proxy_test.py
│ └── utils_test.py
└── tox.ini
================================================
FILE CONTENTS
================================================
================================================
FILE: .coveragerc
================================================
[run]
branch = True
source = docker
[report]
exclude_lines =
if __name__ == .__main__.:
[html]
directory = html
================================================
FILE: .dockerignore
================================================
.git/
build
dist
*.egg-info
*.egg/
*.pyc
*.swp
.tox
.coverage
html/*
__pycache__
# Compiled Documentation
docs/_build
================================================
FILE: .editorconfig
================================================
root = true
[*]
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
max_line_length = 80
[*.md]
trim_trailing_whitespace = false
[*.{yaml,yml}]
indent_size = 2
================================================
FILE: .github/workflows/ci.yml
================================================
name: Python package
on: [push, pull_request]
env:
DOCKER_BUILDKIT: '1'
FORCE_COLOR: 1
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.x'
- run: pip install -U ruff==0.1.8
- name: Run ruff
run: ruff docker tests
build:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.x'
- run: pip3 install build && python -m build .
- uses: actions/upload-artifact@v4
with:
name: dist
path: dist
unit-tests:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
allow-prereleases: true
- name: Install dependencies
run: |
python3 -m pip install --upgrade pip
pip3 install '.[ssh,dev]'
- name: Run unit tests
run: |
docker logout
rm -rf ~/.docker
py.test -v --cov=docker tests/unit
integration-tests:
runs-on: ubuntu-latest
strategy:
matrix:
variant: [ "integration-dind", "integration-dind-ssl", "integration-dind-ssh" ]
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-tags: true
- name: make ${{ matrix.variant }}
run: |
docker logout
rm -rf ~/.docker
make ${{ matrix.variant }}
================================================
FILE: .github/workflows/release.yml
================================================
name: Release
on:
workflow_dispatch:
inputs:
tag:
description: "Release Tag WITHOUT `v` Prefix (e.g. 6.0.0)"
required: true
dry-run:
description: 'Dry run'
required: false
type: boolean
default: true
env:
DOCKER_BUILDKIT: '1'
FORCE_COLOR: 1
jobs:
publish:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Generate Package
run: |
pip3 install build
python -m build .
env:
# This is also supported by Hatch; see
# https://github.com/ofek/hatch-vcs#version-source-environment-variables
SETUPTOOLS_SCM_PRETEND_VERSION: ${{ inputs.tag }}
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
if: '! inputs.dry-run'
with:
password: ${{ secrets.PYPI_API_TOKEN }}
- name: Create GitHub release
uses: ncipollo/release-action@v1
if: '! inputs.dry-run'
with:
artifacts: "dist/*"
generateReleaseNotes: true
draft: true
commit: ${{ github.sha }}
token: ${{ secrets.GITHUB_TOKEN }}
tag: ${{ inputs.tag }}
================================================
FILE: .gitignore
================================================
build
dist
*.egg-info
*.egg/
*.pyc
*.swp
.tox
.coverage
html/*
# Compiled Documentation
_build/
README.rst
# setuptools_scm
_version.py
env/
venv/
.idea/
*.iml
================================================
FILE: .readthedocs.yml
================================================
version: 2
sphinx:
configuration: docs/conf.py
build:
os: ubuntu-22.04
tools:
python: '3.12'
python:
install:
- method: pip
path: .
extra_requirements:
- ssh
- docs
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing guidelines
See the [Docker contributing guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md).
The following is specific to Docker SDK for Python.
Thank you for your interest in the project. We look forward to your
contribution. In order to make the process as fast and streamlined as possible,
here is a set of guidelines we recommend you follow.
## Reporting issues
We do our best to ensure bugs don't creep up in our releases, but some may
still slip through. If you encounter one while using the SDK, please
create an issue
[in the tracker](https://github.com/docker/docker-py/issues/new) with
the following information:
- SDK version, Docker version and python version
```
pip freeze | grep docker && python --version && docker version
```
- OS, distribution and OS version
- The issue you're encountering including a stacktrace if applicable
- If possible, steps or a code snippet to reproduce the issue
To save yourself time, please be sure to check our
[documentation](https://docker-py.readthedocs.io/) and use the
[search function](https://github.com/docker/docker-py/search) to find
out if it has already been addressed, or is currently being looked at.
## Submitting pull requests
Do you have a fix for an existing issue, or want to add a new functionality
to the SDK? We happily welcome pull requests. Here are a few tips to
make the review process easier on both the maintainers and yourself.
### 1. Sign your commits
Please refer to the ["Sign your work"](https://github.com/docker/docker/blob/master/CONTRIBUTING.md#sign-your-work)
paragraph in the Docker contribution guidelines.
### 2. Make sure tests pass
Before we can review your pull request, please ensure that nothing has been
broken by your changes by running the test suite. You can do so simply by
running `make test` in the project root. This also includes coding style using
`ruff`
### 3. Write clear, self-contained commits
Your commit message should be concise and describe the nature of the change.
The commit itself should make sense in isolation from the others in your PR.
Specifically, one should be able to review your commit separately from the
context.
### 4. Rebase proactively
It's much easier to review a pull request that is up to date against the
current master branch.
### 5. Notify thread subscribers when changes are made
GitHub doesn't notify subscribers when new commits happen on a PR, and
fixes or additions might be missed. Please add a comment to the PR thread
when you push new changes.
### 6. Two maintainers LGTM are required for merging
Please wait for review and approval of two maintainers, and respond to their
comments and suggestions during review.
### 7. Add tests
Whether you're adding new functionality to the project or fixing a bug, please
add relevant tests to ensure the code you added continues to work as the
project evolves.
### 8. Add docs
This usually applies to new features rather than bug fixes, but new behavior
should always be documented.
### 9. Ask questions
If you're ever confused about something pertaining to the project, feel free
to reach out and ask questions. We will do our best to answer and help out.
## Development environment
If you're looking contribute to Docker SDK for Python but are new to the
project or Python, here are the steps to get you started.
1. Fork https://github.com/docker/docker-py to your username.
2. Clone your forked repository locally with
`git clone git@github.com:yourusername/docker-py.git`.
3. Configure a
[remote](https://help.github.com/articles/configuring-a-remote-for-a-fork/)
for your fork so that you can
[sync changes you make](https://help.github.com/articles/syncing-a-fork/)
with the original repository.
4. Enter the local directory `cd docker-py`.
5. Run `python setup.py develop` to install the dev version of the project
and required dependencies. We recommend you do so inside a
[virtual environment](http://docs.python-guide.org/en/latest/dev/virtualenvs)
## Running the tests & Code Quality
To get the source source code and run the unit tests, run:
```
$ git clone git://github.com/docker/docker-py.git
$ cd docker-py
$ make test
```
## Building the docs
```
$ make docs
$ open _build/index.html
```
## Release Checklist
Before a new release, please go through the following checklist:
* Bump version in docker/version.py
* Add a release note in docs/change_log.md
* Git tag the version
* Upload to pypi
## Vulnerability Reporting
For any security issues, please do NOT file an issue or pull request on github!
Please contact [security@docker.com](mailto:security@docker.com) or read [the
Docker security page](https://www.docker.com/resources/security/).
================================================
FILE: Dockerfile
================================================
# syntax=docker/dockerfile:1
ARG PYTHON_VERSION=3.12
FROM python:${PYTHON_VERSION}
WORKDIR /src
COPY . .
ARG VERSION=0.0.0.dev0
RUN --mount=type=cache,target=/cache/pip \
PIP_CACHE_DIR=/cache/pip \
SETUPTOOLS_SCM_PRETEND_VERSION=${VERSION} \
pip install .[ssh]
================================================
FILE: Dockerfile-docs
================================================
# syntax=docker/dockerfile:1
ARG PYTHON_VERSION=3.12
FROM python:${PYTHON_VERSION}
ARG uid=1000
ARG gid=1000
RUN addgroup --gid $gid sphinx \
&& useradd --uid $uid --gid $gid -M sphinx
WORKDIR /src
COPY . .
ARG VERSION=0.0.0.dev0
RUN --mount=type=cache,target=/cache/pip \
PIP_CACHE_DIR=/cache/pip \
SETUPTOOLS_SCM_PRETEND_VERSION=${VERSION} \
pip install .[ssh,docs]
USER sphinx
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2016 Docker, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: MAINTAINERS
================================================
# Docker SDK for Python maintainers file
#
# This file describes who runs the docker/docker-py project and how.
# This is a living document - if you see something out of date or missing, speak up!
#
# It is structured to be consumable by both humans and programs.
# To extract its contents programmatically, use any TOML-compliant parser.
#
# This file is compiled into the MAINTAINERS file in docker/opensource.
#
[Org]
[Org."Core maintainers"]
people = [
"glours",
"milas",
]
[Org.Alumni]
people = [
"aiordache",
"aanand",
"bfirsh",
"dnephin",
"mnowster",
"mpetazzoni",
"shin-",
"ulyssessouza",
]
[people]
# A reference list of all people associated with the project.
# All other sections should refer to people by their canonical key
# in the people section.
# ADD YOURSELF HERE IN ALPHABETICAL ORDER
[people.aanand]
Name = "Aanand Prasad"
Email = "aanand@docker.com"
GitHub = "aanand"
[people.aiordache]
Name = "Anca Iordache"
Email = "anca.iordache@docker.com"
GitHub = "aiordache"
[people.bfirsh]
Name = "Ben Firshman"
Email = "b@fir.sh"
GitHub = "bfirsh"
[people.dnephin]
Name = "Daniel Nephin"
Email = "dnephin@gmail.com"
GitHub = "dnephin"
[people.glours]
Name = "Guillaume Lours"
Email = "705411+glours@users.noreply.github.com"
GitHub = "glours"
[people.milas]
Name = "Milas Bowman"
Email = "devnull@milas.dev"
GitHub = "milas"
[people.mnowster]
Name = "Mazz Mosley"
Email = "mazz@houseofmnowster.com"
GitHub = "mnowster"
[people.mpetazzoni]
Name = "Maxime Petazzoni"
Email = "maxime.petazzoni@bulix.org"
GitHub = "mpetazzoni"
[people.shin-]
Name = "Joffrey F"
Email = "joffrey@docker.com"
GitHub = "shin-"
[people.ulyssessouza]
Name = "Ulysses Domiciano Souza"
Email = "ulysses.souza@docker.com"
GitHub = "ulyssessouza"
================================================
FILE: Makefile
================================================
TEST_API_VERSION ?= 1.45
TEST_ENGINE_VERSION ?= 26.1
ifeq ($(OS),Windows_NT)
PLATFORM := Windows
else
PLATFORM := $(shell sh -c 'uname -s 2>/dev/null || echo Unknown')
endif
ifeq ($(PLATFORM),Linux)
uid_args := "--build-arg uid=$(shell id -u) --build-arg gid=$(shell id -g)"
endif
SETUPTOOLS_SCM_PRETEND_VERSION_DOCKER ?= $(shell git describe --match '[0-9]*' --dirty='.m' --always --tags 2>/dev/null | sed -r 's/-([0-9]+)/.dev\1/' | sed 's/-/+/')
ifeq ($(SETUPTOOLS_SCM_PRETEND_VERSION_DOCKER),)
SETUPTOOLS_SCM_PRETEND_VERSION_DOCKER = "0.0.0.dev0"
endif
.PHONY: all
all: test
.PHONY: clean
clean:
-docker rm -f dpy-dind dpy-dind-certs dpy-dind-ssl
find -name "__pycache__" | xargs rm -rf
.PHONY: build-dind-ssh
build-dind-ssh:
docker build \
--pull \
-t docker-dind-ssh \
-f tests/Dockerfile-ssh-dind \
--build-arg VERSION=${SETUPTOOLS_SCM_PRETEND_VERSION_DOCKER} \
--build-arg ENGINE_VERSION=${TEST_ENGINE_VERSION} \
--build-arg API_VERSION=${TEST_API_VERSION} \
.
.PHONY: build
build:
docker build \
--pull \
-t docker-sdk-python3 \
-f tests/Dockerfile \
--build-arg VERSION=${SETUPTOOLS_SCM_PRETEND_VERSION_DOCKER} \
.
.PHONY: build-docs
build-docs:
docker build \
-t docker-sdk-python-docs \
-f Dockerfile-docs \
--build-arg VERSION=${SETUPTOOLS_SCM_PRETEND_VERSION_DOCKER} \
$(uid_args) \
.
.PHONY: build-dind-certs
build-dind-certs:
docker build \
-t dpy-dind-certs \
-f tests/Dockerfile-dind-certs \
--build-arg VERSION=${SETUPTOOLS_SCM_PRETEND_VERSION_DOCKER} \
.
.PHONY: test
test: ruff unit-test integration-dind integration-dind-ssl
.PHONY: unit-test
unit-test: build
docker run -t --rm docker-sdk-python3 py.test tests/unit
.PHONY: integration-test
integration-test: build
docker run -t --rm -v /var/run/docker.sock:/var/run/docker.sock docker-sdk-python3 py.test -v tests/integration/${file}
.PHONY: setup-network
setup-network:
docker network inspect dpy-tests || docker network create dpy-tests
.PHONY: integration-dind
integration-dind: build setup-network
docker rm -vf dpy-dind || :
docker run \
--detach \
--name dpy-dind \
--network dpy-tests \
--pull=always \
--privileged \
docker:${TEST_ENGINE_VERSION}-dind \
dockerd -H tcp://0.0.0.0:2375 --experimental
# Wait for Docker-in-Docker to come to life
docker run \
--network dpy-tests \
--rm \
--tty \
busybox \
sh -c 'while ! nc -z dpy-dind 2375; do sleep 1; done'
docker run \
--env="DOCKER_HOST=tcp://dpy-dind:2375" \
--env="DOCKER_TEST_API_VERSION=${TEST_API_VERSION}" \
--network dpy-tests \
--rm \
--tty \
docker-sdk-python3 \
py.test tests/integration/${file}
docker rm -vf dpy-dind
.PHONY: integration-dind-ssh
integration-dind-ssh: build-dind-ssh build setup-network
docker rm -vf dpy-dind-ssh || :
docker run -d --network dpy-tests --name dpy-dind-ssh --privileged \
docker-dind-ssh dockerd --experimental
# start SSH daemon for known key
docker exec dpy-dind-ssh sh -c "/usr/sbin/sshd -h /etc/ssh/known_ed25519 -p 22"
docker exec dpy-dind-ssh sh -c "/usr/sbin/sshd -h /etc/ssh/unknown_ed25519 -p 2222"
docker run \
--tty \
--rm \
--env="DOCKER_HOST=ssh://dpy-dind-ssh" \
--env="DOCKER_TEST_API_VERSION=${TEST_API_VERSION}" \
--env="UNKNOWN_DOCKER_SSH_HOST=ssh://dpy-dind-ssh:2222" \
--network dpy-tests \
docker-sdk-python3 py.test tests/ssh/${file}
docker rm -vf dpy-dind-ssh
.PHONY: integration-dind-ssl
integration-dind-ssl: build-dind-certs build setup-network
docker rm -vf dpy-dind-certs dpy-dind-ssl || :
docker run -d --name dpy-dind-certs dpy-dind-certs
docker run \
--detach \
--env="DOCKER_CERT_PATH=/certs" \
--env="DOCKER_HOST=tcp://localhost:2375" \
--env="DOCKER_TLS_VERIFY=1" \
--name dpy-dind-ssl \
--network dpy-tests \
--network-alias docker \
--pull=always \
--privileged \
--volume /tmp \
--volumes-from dpy-dind-certs \
docker:${TEST_ENGINE_VERSION}-dind \
dockerd \
--tlsverify \
--tlscacert=/certs/ca.pem \
--tlscert=/certs/server-cert.pem \
--tlskey=/certs/server-key.pem \
-H tcp://0.0.0.0:2375 \
--experimental
# Wait for Docker-in-Docker to come to life
docker run \
--network dpy-tests \
--rm \
--tty \
busybox \
sh -c 'while ! nc -z dpy-dind-ssl 2375; do sleep 1; done'
docker run \
--env="DOCKER_CERT_PATH=/certs" \
--env="DOCKER_HOST=tcp://docker:2375" \
--env="DOCKER_TEST_API_VERSION=${TEST_API_VERSION}" \
--env="DOCKER_TLS_VERIFY=1" \
--network dpy-tests \
--rm \
--volumes-from dpy-dind-ssl \
--tty \
docker-sdk-python3 \
py.test tests/integration/${file}
docker rm -vf dpy-dind-ssl dpy-dind-certs
.PHONY: ruff
ruff: build
docker run -t --rm docker-sdk-python3 ruff docker tests
.PHONY: docs
docs: build-docs
docker run --rm -t -v `pwd`:/src docker-sdk-python-docs sphinx-build docs docs/_build
.PHONY: shell
shell: build
docker run -it -v /var/run/docker.sock:/var/run/docker.sock docker-sdk-python3 python
================================================
FILE: README.md
================================================
# Docker SDK for Python
[](https://github.com/docker/docker-py/actions/workflows/ci.yml)
A Python library for the Docker Engine API. It lets you do anything the `docker` command does, but from within Python apps – run containers, manage containers, manage Swarms, etc.
## Installation
The latest stable version [is available on PyPI](https://pypi.python.org/pypi/docker/). Install with pip:
pip install docker
> Older versions (< 6.0) required installing `docker[tls]` for SSL/TLS support.
> This is no longer necessary and is a no-op, but is supported for backwards compatibility.
## Usage
Connect to Docker using the default socket or the configuration in your environment:
```python
import docker
client = docker.from_env()
```
You can run containers:
```python
>>> client.containers.run("ubuntu:latest", "echo hello world")
'hello world\n'
```
You can run containers in the background:
```python
>>> client.containers.run("bfirsh/reticulate-splines", detach=True)
<Container '45e6d2de7c54'>
```
You can manage containers:
```python
>>> client.containers.list()
[<Container '45e6d2de7c54'>, <Container 'db18e4f20eaa'>, ...]
>>> container = client.containers.get('45e6d2de7c54')
>>> container.attrs['Config']['Image']
"bfirsh/reticulate-splines"
>>> container.logs()
"Reticulating spline 1...\n"
>>> container.stop()
```
You can stream logs:
```python
>>> for line in container.logs(stream=True):
... print(line.strip())
Reticulating spline 2...
Reticulating spline 3...
...
```
You can manage images:
```python
>>> client.images.pull('nginx')
<Image 'nginx'>
>>> client.images.list()
[<Image 'ubuntu'>, <Image 'nginx'>, ...]
```
[Read the full documentation](https://docker-py.readthedocs.io) to see everything you can do.
================================================
FILE: docker/__init__.py
================================================
from .api import APIClient
from .client import DockerClient, from_env
from .context import Context, ContextAPI
from .tls import TLSConfig
from .version import __version__
__title__ = 'docker'
================================================
FILE: docker/api/__init__.py
================================================
from .client import APIClient
================================================
FILE: docker/api/build.py
================================================
import json
import logging
import os
import random
from .. import auth, constants, errors, utils
log = logging.getLogger(__name__)
class BuildApiMixin:
def build(self, path=None, tag=None, quiet=False, fileobj=None,
nocache=False, rm=False, timeout=None,
custom_context=False, encoding=None, pull=False,
forcerm=False, dockerfile=None, container_limits=None,
decode=False, buildargs=None, gzip=False, shmsize=None,
labels=None, cache_from=None, target=None, network_mode=None,
squash=None, extra_hosts=None, platform=None, isolation=None,
use_config_proxy=True):
"""
Similar to the ``docker build`` command. Either ``path`` or ``fileobj``
needs to be set. ``path`` can be a local path (to a directory
containing a Dockerfile) or a remote URL. ``fileobj`` must be a
readable file-like object to a Dockerfile.
If you have a tar file for the Docker build context (including a
Dockerfile) already, pass a readable file-like object to ``fileobj``
and also pass ``custom_context=True``. If the stream is compressed
also, set ``encoding`` to the correct value (e.g ``gzip``).
Example:
>>> from io import BytesIO
>>> from docker import APIClient
>>> dockerfile = '''
... # Shared Volume
... FROM busybox:buildroot-2014.02
... VOLUME /data
... CMD ["/bin/sh"]
... '''
>>> f = BytesIO(dockerfile.encode('utf-8'))
>>> cli = APIClient(base_url='tcp://127.0.0.1:2375')
>>> response = [line for line in cli.build(
... fileobj=f, rm=True, tag='yourname/volume'
... )]
>>> response
['{"stream":" ---\\u003e a9eb17255234\\n"}',
'{"stream":"Step 1 : VOLUME /data\\n"}',
'{"stream":" ---\\u003e Running in abdc1e6896c6\\n"}',
'{"stream":" ---\\u003e 713bca62012e\\n"}',
'{"stream":"Removing intermediate container abdc1e6896c6\\n"}',
'{"stream":"Step 2 : CMD [\\"/bin/sh\\"]\\n"}',
'{"stream":" ---\\u003e Running in dba30f2a1a7e\\n"}',
'{"stream":" ---\\u003e 032b8b2855fc\\n"}',
'{"stream":"Removing intermediate container dba30f2a1a7e\\n"}',
'{"stream":"Successfully built 032b8b2855fc\\n"}']
Args:
path (str): Path to the directory containing the Dockerfile
fileobj: A file object to use as the Dockerfile. (Or a file-like
object)
tag (str): A tag to add to the final image
quiet (bool): Whether to return the status
nocache (bool): Don't use the cache when set to ``True``
rm (bool): Remove intermediate containers. The ``docker build``
command now defaults to ``--rm=true``, but we have kept the old
default of `False` to preserve backward compatibility
timeout (int): HTTP timeout
custom_context (bool): Optional if using ``fileobj``
encoding (str): The encoding for a stream. Set to ``gzip`` for
compressing
pull (bool): Downloads any updates to the FROM image in Dockerfiles
forcerm (bool): Always remove intermediate containers, even after
unsuccessful builds
dockerfile (str): path within the build context to the Dockerfile
gzip (bool): If set to ``True``, gzip compression/encoding is used
buildargs (dict): A dictionary of build arguments
container_limits (dict): A dictionary of limits applied to each
container created by the build process. Valid keys:
- memory (int): set memory limit for build
- memswap (int): Total memory (memory + swap), -1 to disable
swap
- cpushares (int): CPU shares (relative weight)
- cpusetcpus (str): CPUs in which to allow execution, e.g.,
``"0-3"``, ``"0,1"``
decode (bool): If set to ``True``, the returned stream will be
decoded into dicts on the fly. Default ``False``
shmsize (int): Size of `/dev/shm` in bytes. The size must be
greater than 0. If omitted the system uses 64MB
labels (dict): A dictionary of labels to set on the image
cache_from (:py:class:`list`): A list of images used for build
cache resolution
target (str): Name of the build-stage to build in a multi-stage
Dockerfile
network_mode (str): networking mode for the run commands during
build
squash (bool): Squash the resulting images layers into a
single layer.
extra_hosts (dict): Extra hosts to add to /etc/hosts in building
containers, as a mapping of hostname to IP address.
platform (str): Platform in the format ``os[/arch[/variant]]``
isolation (str): Isolation technology used during build.
Default: `None`.
use_config_proxy (bool): If ``True``, and if the docker client
configuration file (``~/.docker/config.json`` by default)
contains a proxy configuration, the corresponding environment
variables will be set in the container being built.
Returns:
A generator for the build output.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
``TypeError``
If neither ``path`` nor ``fileobj`` is specified.
"""
remote = context = None
headers = {}
container_limits = container_limits or {}
buildargs = buildargs or {}
if path is None and fileobj is None:
raise TypeError("Either path or fileobj needs to be provided.")
if gzip and encoding is not None:
raise errors.DockerException(
'Can not use custom encoding if gzip is enabled'
)
if tag is not None:
if not utils.match_tag(tag):
raise errors.DockerException(
f"invalid tag '{tag}': invalid reference format"
)
for key in container_limits.keys():
if key not in constants.CONTAINER_LIMITS_KEYS:
raise errors.DockerException(
f"invalid tag '{tag}': invalid reference format"
)
if custom_context:
if not fileobj:
raise TypeError("You must specify fileobj with custom_context")
context = fileobj
elif fileobj is not None:
context = utils.mkbuildcontext(fileobj)
elif path.startswith(('http://', 'https://',
'git://', 'github.com/', 'git@')):
remote = path
elif not os.path.isdir(path):
raise TypeError("You must specify a directory to build in path")
else:
dockerignore = os.path.join(path, '.dockerignore')
exclude = None
if os.path.exists(dockerignore):
with open(dockerignore) as f:
exclude = list(filter(
lambda x: x != '' and x[0] != '#',
[line.strip() for line in f.read().splitlines()]
))
dockerfile = process_dockerfile(dockerfile, path)
context = utils.tar(
path, exclude=exclude, dockerfile=dockerfile, gzip=gzip
)
encoding = 'gzip' if gzip else encoding
u = self._url('/build')
params = {
't': tag,
'remote': remote,
'q': quiet,
'nocache': nocache,
'rm': rm,
'forcerm': forcerm,
'pull': pull,
'dockerfile': dockerfile,
}
params.update(container_limits)
if use_config_proxy:
proxy_args = self._proxy_configs.get_environment()
for k, v in proxy_args.items():
buildargs.setdefault(k, v)
if buildargs:
params.update({'buildargs': json.dumps(buildargs)})
if shmsize:
if utils.version_gte(self._version, '1.22'):
params.update({'shmsize': shmsize})
else:
raise errors.InvalidVersion(
'shmsize was only introduced in API version 1.22'
)
if labels:
if utils.version_gte(self._version, '1.23'):
params.update({'labels': json.dumps(labels)})
else:
raise errors.InvalidVersion(
'labels was only introduced in API version 1.23'
)
if cache_from:
if utils.version_gte(self._version, '1.25'):
params.update({'cachefrom': json.dumps(cache_from)})
else:
raise errors.InvalidVersion(
'cache_from was only introduced in API version 1.25'
)
if target:
if utils.version_gte(self._version, '1.29'):
params.update({'target': target})
else:
raise errors.InvalidVersion(
'target was only introduced in API version 1.29'
)
if network_mode:
if utils.version_gte(self._version, '1.25'):
params.update({'networkmode': network_mode})
else:
raise errors.InvalidVersion(
'network_mode was only introduced in API version 1.25'
)
if squash:
if utils.version_gte(self._version, '1.25'):
params.update({'squash': squash})
else:
raise errors.InvalidVersion(
'squash was only introduced in API version 1.25'
)
if extra_hosts is not None:
if utils.version_lt(self._version, '1.27'):
raise errors.InvalidVersion(
'extra_hosts was only introduced in API version 1.27'
)
if isinstance(extra_hosts, dict):
extra_hosts = utils.format_extra_hosts(extra_hosts)
params.update({'extrahosts': extra_hosts})
if platform is not None:
if utils.version_lt(self._version, '1.32'):
raise errors.InvalidVersion(
'platform was only introduced in API version 1.32'
)
params['platform'] = platform
if isolation is not None:
if utils.version_lt(self._version, '1.24'):
raise errors.InvalidVersion(
'isolation was only introduced in API version 1.24'
)
params['isolation'] = isolation
if context is not None:
headers = {'Content-Type': 'application/tar'}
if encoding:
headers['Content-Encoding'] = encoding
self._set_auth_headers(headers)
response = self._post(
u,
data=context,
params=params,
headers=headers,
stream=True,
timeout=timeout,
)
if context is not None and not custom_context:
context.close()
return self._stream_helper(response, decode=decode)
@utils.minimum_version('1.31')
def prune_builds(self, filters=None, keep_storage=None, all=None):
"""
Delete the builder cache
Args:
filters (dict): Filters to process on the prune list.
Needs Docker API v1.39+
Available filters:
- dangling (bool): When set to true (or 1), prune only
unused and untagged images.
- until (str): Can be Unix timestamps, date formatted
timestamps, or Go duration strings (e.g. 10m, 1h30m) computed
relative to the daemon's local time.
keep_storage (int): Amount of disk space in bytes to keep for cache.
Needs Docker API v1.39+
all (bool): Remove all types of build cache.
Needs Docker API v1.39+
Returns:
(dict): A dictionary containing information about the operation's
result. The ``SpaceReclaimed`` key indicates the amount of
bytes of disk space reclaimed.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url("/build/prune")
if (filters, keep_storage, all) != (None, None, None) \
and utils.version_lt(self._version, '1.39'):
raise errors.InvalidVersion(
'`filters`, `keep_storage`, and `all` args are only available '
'for API version > 1.38'
)
params = {}
if filters is not None:
params['filters'] = utils.convert_filters(filters)
if keep_storage is not None:
params['keep-storage'] = keep_storage
if all is not None:
params['all'] = all
return self._result(self._post(url, params=params), True)
def _set_auth_headers(self, headers):
log.debug('Looking for auth config')
# If we don't have any auth data so far, try reloading the config
# file one more time in case anything showed up in there.
if not self._auth_configs or self._auth_configs.is_empty:
log.debug("No auth config in memory - loading from filesystem")
self._auth_configs = auth.load_config(
credstore_env=self.credstore_env
)
# Send the full auth configuration (if any exists), since the build
# could use any (or all) of the registries.
if self._auth_configs:
auth_data = self._auth_configs.get_all_credentials()
# See https://github.com/docker/docker-py/issues/1683
if (auth.INDEX_URL not in auth_data and
auth.INDEX_NAME in auth_data):
auth_data[auth.INDEX_URL] = auth_data.get(auth.INDEX_NAME, {})
log.debug(
"Sending auth config (%s)",
', '.join(repr(k) for k in auth_data),
)
if auth_data:
headers['X-Registry-Config'] = auth.encode_header(
auth_data
)
else:
log.debug('No auth config found')
def process_dockerfile(dockerfile, path):
if not dockerfile:
return (None, None)
abs_dockerfile = dockerfile
if not os.path.isabs(dockerfile):
abs_dockerfile = os.path.join(path, dockerfile)
if constants.IS_WINDOWS_PLATFORM and path.startswith(
constants.WINDOWS_LONGPATH_PREFIX):
normpath = os.path.normpath(
abs_dockerfile[len(constants.WINDOWS_LONGPATH_PREFIX):])
abs_dockerfile = f'{constants.WINDOWS_LONGPATH_PREFIX}{normpath}'
if (os.path.splitdrive(path)[0] != os.path.splitdrive(abs_dockerfile)[0] or
os.path.relpath(abs_dockerfile, path).startswith('..')):
# Dockerfile not in context - read data to insert into tar later
with open(abs_dockerfile) as df:
return (
f'.dockerfile.{random.getrandbits(160):x}',
df.read()
)
# Dockerfile is inside the context - return path relative to context root
if dockerfile == abs_dockerfile:
# Only calculate relpath if necessary to avoid errors
# on Windows client -> Linux Docker
# see https://github.com/docker/compose/issues/5969
dockerfile = os.path.relpath(abs_dockerfile, path)
return (dockerfile, None)
================================================
FILE: docker/api/client.py
================================================
import json
import struct
import urllib
from functools import partial
import requests
import requests.adapters
import requests.exceptions
from .. import auth
from ..constants import (
DEFAULT_MAX_POOL_SIZE,
DEFAULT_NUM_POOLS,
DEFAULT_NUM_POOLS_SSH,
DEFAULT_TIMEOUT_SECONDS,
DEFAULT_USER_AGENT,
IS_WINDOWS_PLATFORM,
MINIMUM_DOCKER_API_VERSION,
STREAM_HEADER_SIZE_BYTES,
)
from ..errors import (
DockerException,
InvalidVersion,
TLSParameterError,
create_api_error_from_http_exception,
)
from ..tls import TLSConfig
from ..transport import UnixHTTPAdapter
from ..utils import check_resource, config, update_headers, utils
from ..utils.json_stream import json_stream
from ..utils.proxy import ProxyConfig
from ..utils.socket import consume_socket_output, demux_adaptor, frames_iter
from .build import BuildApiMixin
from .config import ConfigApiMixin
from .container import ContainerApiMixin
from .daemon import DaemonApiMixin
from .exec_api import ExecApiMixin
from .image import ImageApiMixin
from .network import NetworkApiMixin
from .plugin import PluginApiMixin
from .secret import SecretApiMixin
from .service import ServiceApiMixin
from .swarm import SwarmApiMixin
from .volume import VolumeApiMixin
try:
from ..transport import NpipeHTTPAdapter
except ImportError:
pass
try:
from ..transport import SSHHTTPAdapter
except ImportError:
pass
class APIClient(
requests.Session,
BuildApiMixin,
ConfigApiMixin,
ContainerApiMixin,
DaemonApiMixin,
ExecApiMixin,
ImageApiMixin,
NetworkApiMixin,
PluginApiMixin,
SecretApiMixin,
ServiceApiMixin,
SwarmApiMixin,
VolumeApiMixin):
"""
A low-level client for the Docker Engine API.
Example:
>>> import docker
>>> client = docker.APIClient(base_url='unix://var/run/docker.sock')
>>> client.version()
{u'ApiVersion': u'1.33',
u'Arch': u'amd64',
u'BuildTime': u'2017-11-19T18:46:37.000000000+00:00',
u'GitCommit': u'f4ffd2511c',
u'GoVersion': u'go1.9.2',
u'KernelVersion': u'4.14.3-1-ARCH',
u'MinAPIVersion': u'1.12',
u'Os': u'linux',
u'Version': u'17.10.0-ce'}
Args:
base_url (str): URL to the Docker server. For example,
``unix:///var/run/docker.sock`` or ``tcp://127.0.0.1:1234``.
version (str): The version of the API to use. Set to ``auto`` to
automatically detect the server's version. Default: ``1.35``
timeout (int): Default timeout for API calls, in seconds.
tls (bool or :py:class:`~docker.tls.TLSConfig`): Enable TLS. Pass
``True`` to enable it with default options, or pass a
:py:class:`~docker.tls.TLSConfig` object to use custom
configuration.
user_agent (str): Set a custom user agent for requests to the server.
credstore_env (dict): Override environment variables when calling the
credential store process.
use_ssh_client (bool): If set to `True`, an ssh connection is made
via shelling out to the ssh client. Ensure the ssh client is
installed and configured on the host.
max_pool_size (int): The maximum number of connections
to save in the pool.
"""
__attrs__ = requests.Session.__attrs__ + ['_auth_configs',
'_general_configs',
'_version',
'base_url',
'timeout']
def __init__(self, base_url=None, version=None,
timeout=DEFAULT_TIMEOUT_SECONDS, tls=False,
user_agent=DEFAULT_USER_AGENT, num_pools=None,
credstore_env=None, use_ssh_client=False,
max_pool_size=DEFAULT_MAX_POOL_SIZE):
super().__init__()
if tls and not base_url:
raise TLSParameterError(
'If using TLS, the base_url argument must be provided.'
)
self.base_url = base_url
self.timeout = timeout
self.headers['User-Agent'] = user_agent
self._general_configs = config.load_general_config()
proxy_config = self._general_configs.get('proxies', {})
try:
proxies = proxy_config[base_url]
except KeyError:
proxies = proxy_config.get('default', {})
self._proxy_configs = ProxyConfig.from_dict(proxies)
self._auth_configs = auth.load_config(
config_dict=self._general_configs, credstore_env=credstore_env,
)
self.credstore_env = credstore_env
base_url = utils.parse_host(
base_url, IS_WINDOWS_PLATFORM, tls=bool(tls)
)
# SSH has a different default for num_pools to all other adapters
num_pools = num_pools or DEFAULT_NUM_POOLS_SSH if \
base_url.startswith('ssh://') else DEFAULT_NUM_POOLS
if base_url.startswith('http+unix://'):
self._custom_adapter = UnixHTTPAdapter(
base_url, timeout, pool_connections=num_pools,
max_pool_size=max_pool_size
)
self.mount('http+docker://', self._custom_adapter)
self._unmount('http://', 'https://')
# host part of URL should be unused, but is resolved by requests
# module in proxy_bypass_macosx_sysconf()
self.base_url = 'http+docker://localhost'
elif base_url.startswith('npipe://'):
if not IS_WINDOWS_PLATFORM:
raise DockerException(
'The npipe:// protocol is only supported on Windows'
)
try:
self._custom_adapter = NpipeHTTPAdapter(
base_url, timeout, pool_connections=num_pools,
max_pool_size=max_pool_size
)
except NameError as err:
raise DockerException(
'Install pypiwin32 package to enable npipe:// support'
) from err
self.mount('http+docker://', self._custom_adapter)
self.base_url = 'http+docker://localnpipe'
elif base_url.startswith('ssh://'):
try:
self._custom_adapter = SSHHTTPAdapter(
base_url, timeout, pool_connections=num_pools,
max_pool_size=max_pool_size, shell_out=use_ssh_client
)
except NameError as err:
raise DockerException(
'Install paramiko package to enable ssh:// support'
) from err
self.mount('http+docker://ssh', self._custom_adapter)
self._unmount('http://', 'https://')
self.base_url = 'http+docker://ssh'
else:
# Use SSLAdapter for the ability to specify SSL version
if isinstance(tls, TLSConfig):
tls.configure_client(self)
elif tls:
self._custom_adapter = requests.adapters.HTTPAdapter(
pool_connections=num_pools)
self.mount('https://', self._custom_adapter)
self.base_url = base_url
# version detection needs to be after unix adapter mounting
if version is None or (isinstance(
version,
str
) and version.lower() == 'auto'):
self._version = self._retrieve_server_version()
else:
self._version = version
if not isinstance(self._version, str):
raise DockerException(
'Version parameter must be a string or None. '
f'Found {type(version).__name__}'
)
if utils.version_lt(self._version, MINIMUM_DOCKER_API_VERSION):
raise InvalidVersion(
f'API versions below {MINIMUM_DOCKER_API_VERSION} are '
f'no longer supported by this library.'
)
def _retrieve_server_version(self):
try:
return self.version(api_version=False)["ApiVersion"]
except KeyError as ke:
raise DockerException(
'Invalid response from docker daemon: key "ApiVersion"'
' is missing.'
) from ke
except Exception as e:
raise DockerException(
f'Error while fetching server API version: {e}'
) from e
def _set_request_timeout(self, kwargs):
"""Prepare the kwargs for an HTTP request by inserting the timeout
parameter, if not already present."""
kwargs.setdefault('timeout', self.timeout)
return kwargs
@update_headers
def _post(self, url, **kwargs):
return self.post(url, **self._set_request_timeout(kwargs))
@update_headers
def _get(self, url, **kwargs):
return self.get(url, **self._set_request_timeout(kwargs))
@update_headers
def _put(self, url, **kwargs):
return self.put(url, **self._set_request_timeout(kwargs))
@update_headers
def _delete(self, url, **kwargs):
return self.delete(url, **self._set_request_timeout(kwargs))
def _url(self, pathfmt, *args, **kwargs):
for arg in args:
if not isinstance(arg, str):
raise ValueError(
f'Expected a string but found {arg} ({type(arg)}) instead'
)
quote_f = partial(urllib.parse.quote, safe="/:")
args = map(quote_f, args)
formatted_path = pathfmt.format(*args)
if kwargs.get('versioned_api', True):
return f'{self.base_url}/v{self._version}{formatted_path}'
else:
return f'{self.base_url}{formatted_path}'
def _raise_for_status(self, response):
"""Raises stored :class:`APIError`, if one occurred."""
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
raise create_api_error_from_http_exception(e) from e
def _result(self, response, json=False, binary=False):
assert not (json and binary)
self._raise_for_status(response)
if json:
return response.json()
if binary:
return response.content
return response.text
def _post_json(self, url, data, **kwargs):
# Go <1.1 can't unserialize null to a string
# so we do this disgusting thing here.
data2 = {}
if data is not None and isinstance(data, dict):
for k, v in iter(data.items()):
if v is not None:
data2[k] = v
elif data is not None:
data2 = data
if 'headers' not in kwargs:
kwargs['headers'] = {}
kwargs['headers']['Content-Type'] = 'application/json'
return self._post(url, data=json.dumps(data2), **kwargs)
def _attach_params(self, override=None):
return override or {
'stdout': 1,
'stderr': 1,
'stream': 1
}
@check_resource('container')
def _attach_websocket(self, container, params=None):
url = self._url("/containers/{0}/attach/ws", container)
req = requests.Request("POST", url, params=self._attach_params(params))
full_url = req.prepare().url
full_url = full_url.replace("http://", "ws://", 1)
full_url = full_url.replace("https://", "wss://", 1)
return self._create_websocket_connection(full_url)
def _create_websocket_connection(self, url):
try:
import websocket
return websocket.create_connection(url)
except ImportError as ie:
raise DockerException(
'The `websocket-client` library is required '
'for using websocket connections. '
'You can install the `docker` library '
'with the [websocket] extra to install it.'
) from ie
def _get_raw_response_socket(self, response):
self._raise_for_status(response)
if self.base_url == "http+docker://localnpipe":
sock = response.raw._fp.fp.raw.sock
elif self.base_url.startswith('http+docker://ssh'):
sock = response.raw._fp.fp.channel
else:
sock = response.raw._fp.fp.raw
if self.base_url.startswith("https://"):
sock = sock._sock
try:
# Keep a reference to the response to stop it being garbage
# collected. If the response is garbage collected, it will
# close TLS sockets.
sock._response = response
except AttributeError:
# UNIX sockets can't have attributes set on them, but that's
# fine because we won't be doing TLS over them
pass
return sock
def _stream_helper(self, response, decode=False):
"""Generator for data coming from a chunked-encoded HTTP response."""
if response.raw._fp.chunked:
if decode:
yield from json_stream(self._stream_helper(response, False))
else:
reader = response.raw
while not reader.closed:
# this read call will block until we get a chunk
data = reader.read(1)
if not data:
break
if reader._fp.chunk_left:
data += reader.read(reader._fp.chunk_left)
yield data
else:
# Response isn't chunked, meaning we probably
# encountered an error immediately
yield self._result(response, json=decode)
def _multiplexed_buffer_helper(self, response):
"""A generator of multiplexed data blocks read from a buffered
response."""
buf = self._result(response, binary=True)
buf_length = len(buf)
walker = 0
while True:
if buf_length - walker < STREAM_HEADER_SIZE_BYTES:
break
header = buf[walker:walker + STREAM_HEADER_SIZE_BYTES]
_, length = struct.unpack_from('>BxxxL', header)
start = walker + STREAM_HEADER_SIZE_BYTES
end = start + length
walker = end
yield buf[start:end]
def _multiplexed_response_stream_helper(self, response):
"""A generator of multiplexed data blocks coming from a response
stream."""
# Disable timeout on the underlying socket to prevent
# Read timed out(s) for long running processes
socket = self._get_raw_response_socket(response)
self._disable_socket_timeout(socket)
while True:
header = response.raw.read(STREAM_HEADER_SIZE_BYTES)
if not header:
break
_, length = struct.unpack('>BxxxL', header)
if not length:
continue
data = response.raw.read(length)
if not data:
break
yield data
def _stream_raw_result(self, response, chunk_size=1, decode=True):
''' Stream result for TTY-enabled container and raw binary data'''
self._raise_for_status(response)
# Disable timeout on the underlying socket to prevent
# Read timed out(s) for long running processes
socket = self._get_raw_response_socket(response)
self._disable_socket_timeout(socket)
yield from response.iter_content(chunk_size, decode)
def _read_from_socket(self, response, stream, tty=True, demux=False):
"""Consume all data from the socket, close the response and return the
data. If stream=True, then a generator is returned instead and the
caller is responsible for closing the response.
"""
socket = self._get_raw_response_socket(response)
gen = frames_iter(socket, tty)
if demux:
# The generator will output tuples (stdout, stderr)
gen = (demux_adaptor(*frame) for frame in gen)
else:
# The generator will output strings
gen = (data for (_, data) in gen)
if stream:
return gen
else:
try:
# Wait for all frames, concatenate them, and return the result
return consume_socket_output(gen, demux=demux)
finally:
response.close()
def _disable_socket_timeout(self, socket):
""" Depending on the combination of python version and whether we're
connecting over http or https, we might need to access _sock, which
may or may not exist; or we may need to just settimeout on socket
itself, which also may or may not have settimeout on it. To avoid
missing the correct one, we try both.
We also do not want to set the timeout if it is already disabled, as
you run the risk of changing a socket that was non-blocking to
blocking, for example when using gevent.
"""
sockets = [socket, getattr(socket, '_sock', None)]
for s in sockets:
if not hasattr(s, 'settimeout'):
continue
timeout = -1
if hasattr(s, 'gettimeout'):
timeout = s.gettimeout()
# Don't change the timeout if it is already disabled.
if timeout is None or timeout == 0.0:
continue
s.settimeout(None)
@check_resource('container')
def _check_is_tty(self, container):
cont = self.inspect_container(container)
return cont['Config']['Tty']
def _get_result(self, container, stream, res):
return self._get_result_tty(stream, res, self._check_is_tty(container))
def _get_result_tty(self, stream, res, is_tty):
# We should also use raw streaming (without keep-alives)
# if we're dealing with a tty-enabled container.
if is_tty:
return self._stream_raw_result(res) if stream else \
self._result(res, binary=True)
self._raise_for_status(res)
sep = b''
if stream:
return self._multiplexed_response_stream_helper(res)
else:
return sep.join(
list(self._multiplexed_buffer_helper(res))
)
def _unmount(self, *args):
for proto in args:
self.adapters.pop(proto)
def get_adapter(self, url):
try:
return super().get_adapter(url)
except requests.exceptions.InvalidSchema as e:
if self._custom_adapter:
return self._custom_adapter
else:
raise e
@property
def api_version(self):
return self._version
def reload_config(self, dockercfg_path=None):
"""
Force a reload of the auth configuration
Args:
dockercfg_path (str): Use a custom path for the Docker config file
(default ``$HOME/.docker/config.json`` if present,
otherwise ``$HOME/.dockercfg``)
Returns:
None
"""
self._auth_configs = auth.load_config(
dockercfg_path, credstore_env=self.credstore_env
)
================================================
FILE: docker/api/config.py
================================================
import base64
from .. import utils
class ConfigApiMixin:
@utils.minimum_version('1.30')
def create_config(self, name, data, labels=None, templating=None):
"""
Create a config
Args:
name (string): Name of the config
data (bytes): Config data to be stored
labels (dict): A mapping of labels to assign to the config
templating (dict): dictionary containing the name of the
templating driver to be used expressed as
{ name: <templating_driver_name>}
Returns (dict): ID of the newly created config
"""
if not isinstance(data, bytes):
data = data.encode('utf-8')
data = base64.b64encode(data)
data = data.decode('ascii')
body = {
'Data': data,
'Name': name,
'Labels': labels,
'Templating': templating
}
url = self._url('/configs/create')
return self._result(
self._post_json(url, data=body), True
)
@utils.minimum_version('1.30')
@utils.check_resource('id')
def inspect_config(self, id):
"""
Retrieve config metadata
Args:
id (string): Full ID of the config to inspect
Returns (dict): A dictionary of metadata
Raises:
:py:class:`docker.errors.NotFound`
if no config with that ID exists
"""
url = self._url('/configs/{0}', id)
return self._result(self._get(url), True)
@utils.minimum_version('1.30')
@utils.check_resource('id')
def remove_config(self, id):
"""
Remove a config
Args:
id (string): Full ID of the config to remove
Returns (boolean): True if successful
Raises:
:py:class:`docker.errors.NotFound`
if no config with that ID exists
"""
url = self._url('/configs/{0}', id)
res = self._delete(url)
self._raise_for_status(res)
return True
@utils.minimum_version('1.30')
def configs(self, filters=None):
"""
List configs
Args:
filters (dict): A map of filters to process on the configs
list. Available filters: ``names``
Returns (list): A list of configs
"""
url = self._url('/configs')
params = {}
if filters:
params['filters'] = utils.convert_filters(filters)
return self._result(self._get(url, params=params), True)
================================================
FILE: docker/api/container.py
================================================
from datetime import datetime
from .. import errors, utils
from ..constants import DEFAULT_DATA_CHUNK_SIZE
from ..types import (
CancellableStream,
ContainerConfig,
EndpointConfig,
HostConfig,
NetworkingConfig,
)
class ContainerApiMixin:
@utils.check_resource('container')
def attach(self, container, stdout=True, stderr=True,
stream=False, logs=False, demux=False):
"""
Attach to a container.
The ``.logs()`` function is a wrapper around this method, which you can
use instead if you want to fetch/stream container output without first
retrieving the entire backlog.
Args:
container (str): The container to attach to.
stdout (bool): Include stdout.
stderr (bool): Include stderr.
stream (bool): Return container output progressively as an iterator
of strings, rather than a single string.
logs (bool): Include the container's previous output.
demux (bool): Keep stdout and stderr separate.
Returns:
By default, the container's output as a single string (two if
``demux=True``: one for stdout and one for stderr).
If ``stream=True``, an iterator of output strings. If
``demux=True``, two iterators are returned: one for stdout and one
for stderr.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {
'logs': logs and 1 or 0,
'stdout': stdout and 1 or 0,
'stderr': stderr and 1 or 0,
'stream': stream and 1 or 0
}
headers = {
'Connection': 'Upgrade',
'Upgrade': 'tcp'
}
u = self._url("/containers/{0}/attach", container)
response = self._post(u, headers=headers, params=params, stream=True)
output = self._read_from_socket(
response, stream, self._check_is_tty(container), demux=demux)
if stream:
return CancellableStream(output, response)
else:
return output
@utils.check_resource('container')
def attach_socket(self, container, params=None, ws=False):
"""
Like ``attach``, but returns the underlying socket-like object for the
HTTP request.
Args:
container (str): The container to attach to.
params (dict): Dictionary of request parameters (e.g. ``stdout``,
``stderr``, ``stream``).
For ``detachKeys``, ~/.docker/config.json is used by default.
ws (bool): Use websockets instead of raw HTTP.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
if params is None:
params = {
'stdout': 1,
'stderr': 1,
'stream': 1
}
if 'detachKeys' not in params \
and 'detachKeys' in self._general_configs:
params['detachKeys'] = self._general_configs['detachKeys']
if ws:
return self._attach_websocket(container, params)
headers = {
'Connection': 'Upgrade',
'Upgrade': 'tcp'
}
u = self._url("/containers/{0}/attach", container)
return self._get_raw_response_socket(
self.post(
u, None, params=self._attach_params(params), stream=True,
headers=headers
)
)
@utils.check_resource('container')
def commit(self, container, repository=None, tag=None, message=None,
author=None, pause=True, changes=None, conf=None):
"""
Commit a container to an image. Similar to the ``docker commit``
command.
Args:
container (str): The image hash of the container
repository (str): The repository to push the image to
tag (str): The tag to push
message (str): A commit message
author (str): The name of the author
pause (bool): Whether to pause the container before committing
changes (str): Dockerfile instructions to apply while committing
conf (dict): The configuration for the container. See the
`Engine API documentation
<https://docs.docker.com/reference/api/docker_remote_api/>`_
for full details.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {
'container': container,
'repo': repository,
'tag': tag,
'comment': message,
'author': author,
'pause': pause,
'changes': changes
}
u = self._url("/commit")
return self._result(
self._post_json(u, data=conf, params=params), json=True
)
def containers(self, quiet=False, all=False, trunc=False, latest=False,
since=None, before=None, limit=-1, size=False,
filters=None):
"""
List containers. Similar to the ``docker ps`` command.
Args:
quiet (bool): Only display numeric Ids
all (bool): Show all containers. Only running containers are shown
by default
trunc (bool): Truncate output
latest (bool): Show only the latest created container, include
non-running ones.
since (str): Show only containers created since Id or Name, include
non-running ones
before (str): Show only container created before Id or Name,
include non-running ones
limit (int): Show `limit` last created containers, include
non-running ones
size (bool): Display sizes
filters (dict): Filters to be processed on the image list.
Available filters:
- `exited` (int): Only containers with specified exit code
- `status` (str): One of ``restarting``, ``running``,
``paused``, ``exited``
- `label` (str|list): format either ``"key"``, ``"key=value"``
or a list of such.
- `id` (str): The id of the container.
- `name` (str): The name of the container.
- `ancestor` (str): Filter by container ancestor. Format of
``<image-name>[:tag]``, ``<image-id>``, or
``<image@digest>``.
- `before` (str): Only containers created before a particular
container. Give the container name or id.
- `since` (str): Only containers created after a particular
container. Give container name or id.
A comprehensive list can be found in the documentation for
`docker ps
<https://docs.docker.com/engine/reference/commandline/ps>`_.
Returns:
A list of dicts, one per container
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {
'limit': 1 if latest else limit,
'all': 1 if all else 0,
'size': 1 if size else 0,
'trunc_cmd': 1 if trunc else 0,
'since': since,
'before': before
}
if filters:
params['filters'] = utils.convert_filters(filters)
u = self._url("/containers/json")
res = self._result(self._get(u, params=params), True)
if quiet:
return [{'Id': x['Id']} for x in res]
if trunc:
for x in res:
x['Id'] = x['Id'][:12]
return res
def create_container(self, image, command=None, hostname=None, user=None,
detach=False, stdin_open=False, tty=False, ports=None,
environment=None, volumes=None,
network_disabled=False, name=None, entrypoint=None,
working_dir=None, domainname=None, host_config=None,
mac_address=None, labels=None, stop_signal=None,
networking_config=None, healthcheck=None,
stop_timeout=None, runtime=None,
use_config_proxy=True, platform=None):
"""
Creates a container. Parameters are similar to those for the ``docker
run`` command except it doesn't support the attach options (``-a``).
The arguments that are passed directly to this function are
host-independent configuration options. Host-specific configuration
is passed with the `host_config` argument. You'll normally want to
use this method in combination with the :py:meth:`create_host_config`
method to generate ``host_config``.
**Port bindings**
Port binding is done in two parts: first, provide a list of ports to
open inside the container with the ``ports`` parameter, then declare
bindings with the ``host_config`` parameter. For example:
.. code-block:: python
container_id = client.api.create_container(
'busybox', 'ls', ports=[1111, 2222],
host_config=client.api.create_host_config(port_bindings={
1111: 4567,
2222: None
})
)
You can limit the host address on which the port will be exposed like
such:
.. code-block:: python
client.api.create_host_config(
port_bindings={1111: ('127.0.0.1', 4567)}
)
Or without host port assignment:
.. code-block:: python
client.api.create_host_config(port_bindings={1111: ('127.0.0.1',)})
If you wish to use UDP instead of TCP (default), you need to declare
ports as such in both the config and host config:
.. code-block:: python
container_id = client.api.create_container(
'busybox', 'ls', ports=[(1111, 'udp'), 2222],
host_config=client.api.create_host_config(port_bindings={
'1111/udp': 4567, 2222: None
})
)
To bind multiple host ports to a single container port, use the
following syntax:
.. code-block:: python
client.api.create_host_config(port_bindings={
1111: [1234, 4567]
})
You can also bind multiple IPs to a single container port:
.. code-block:: python
client.api.create_host_config(port_bindings={
1111: [
('192.168.0.100', 1234),
('192.168.0.101', 1234)
]
})
**Using volumes**
Volume declaration is done in two parts. Provide a list of
paths to use as mountpoints inside the container with the
``volumes`` parameter, and declare mappings from paths on the host
in the ``host_config`` section.
.. code-block:: python
container_id = client.api.create_container(
'busybox', 'ls', volumes=['/mnt/vol1', '/mnt/vol2'],
host_config=client.api.create_host_config(binds={
'/home/user1/': {
'bind': '/mnt/vol2',
'mode': 'rw',
},
'/var/www': {
'bind': '/mnt/vol1',
'mode': 'ro',
},
'/autofs/user1': {
'bind': '/mnt/vol3',
'mode': 'rw',
'propagation': 'shared'
}
})
)
You can alternatively specify binds as a list. This code is equivalent
to the example above:
.. code-block:: python
container_id = client.api.create_container(
'busybox', 'ls', volumes=['/mnt/vol1', '/mnt/vol2', '/mnt/vol3'],
host_config=client.api.create_host_config(binds=[
'/home/user1/:/mnt/vol2',
'/var/www:/mnt/vol1:ro',
'/autofs/user1:/mnt/vol3:rw,shared',
])
)
**Networking**
You can specify networks to connect the container to by using the
``networking_config`` parameter. At the time of creation, you can
only connect a container to a single networking, but you
can create more connections by using
:py:meth:`~connect_container_to_network`.
For example:
.. code-block:: python
networking_config = client.api.create_networking_config({
'network1': client.api.create_endpoint_config(
ipv4_address='172.28.0.124',
aliases=['foo', 'bar'],
links=['container2']
)
})
ctnr = client.api.create_container(
img, command, networking_config=networking_config
)
Args:
image (str): The image to run
command (str or list): The command to be run in the container
hostname (str): Optional hostname for the container
user (str or int): Username or UID
detach (bool): Detached mode: run container in the background and
return container ID
stdin_open (bool): Keep STDIN open even if not attached
tty (bool): Allocate a pseudo-TTY
ports (list of ints): A list of port numbers
environment (dict or list): A dictionary or a list of strings in
the following format ``["PASSWORD=xxx"]`` or
``{"PASSWORD": "xxx"}``.
volumes (str or list): List of paths inside the container to use
as volumes.
network_disabled (bool): Disable networking
name (str): A name for the container
entrypoint (str or list): An entrypoint
working_dir (str): Path to the working directory
domainname (str): The domain name to use for the container
host_config (dict): A dictionary created with
:py:meth:`create_host_config`.
mac_address (str): The Mac Address to assign the container
labels (dict or list): A dictionary of name-value labels (e.g.
``{"label1": "value1", "label2": "value2"}``) or a list of
names of labels to set with empty values (e.g.
``["label1", "label2"]``)
stop_signal (str): The stop signal to use to stop the container
(e.g. ``SIGINT``).
stop_timeout (int): Timeout to stop the container, in seconds.
Default: 10
networking_config (dict): A networking configuration generated
by :py:meth:`create_networking_config`.
runtime (str): Runtime to use with this container.
healthcheck (dict): Specify a test to perform to check that the
container is healthy.
use_config_proxy (bool): If ``True``, and if the docker client
configuration file (``~/.docker/config.json`` by default)
contains a proxy configuration, the corresponding environment
variables will be set in the container being created.
platform (str): Platform in the format ``os[/arch[/variant]]``.
Returns:
A dictionary with an image 'Id' key and a 'Warnings' key.
Raises:
:py:class:`docker.errors.ImageNotFound`
If the specified image does not exist.
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
if isinstance(volumes, str):
volumes = [volumes, ]
if isinstance(environment, dict):
environment = utils.utils.format_environment(environment)
if use_config_proxy:
environment = self._proxy_configs.inject_proxy_environment(
environment
) or None
config = self.create_container_config(
image, command, hostname, user, detach, stdin_open, tty,
ports, environment, volumes,
network_disabled, entrypoint, working_dir, domainname,
host_config, mac_address, labels,
stop_signal, networking_config, healthcheck,
stop_timeout, runtime
)
return self.create_container_from_config(config, name, platform)
def create_container_config(self, *args, **kwargs):
return ContainerConfig(self._version, *args, **kwargs)
def create_container_from_config(self, config, name=None, platform=None):
u = self._url("/containers/create")
params = {
'name': name
}
if platform:
if utils.version_lt(self._version, '1.41'):
raise errors.InvalidVersion(
'platform is not supported for API version < 1.41'
)
params['platform'] = platform
res = self._post_json(u, data=config, params=params)
return self._result(res, True)
def create_host_config(self, *args, **kwargs):
"""
Create a dictionary for the ``host_config`` argument to
:py:meth:`create_container`.
Args:
auto_remove (bool): enable auto-removal of the container on daemon
side when the container's process exits.
binds (dict): Volumes to bind. See :py:meth:`create_container`
for more information.
blkio_weight_device: Block IO weight (relative device weight) in
the form of: ``[{"Path": "device_path", "Weight": weight}]``.
blkio_weight: Block IO weight (relative weight), accepts a weight
value between 10 and 1000.
cap_add (list of str): Add kernel capabilities. For example,
``["SYS_ADMIN", "MKNOD"]``.
cap_drop (list of str): Drop kernel capabilities.
cpu_period (int): The length of a CPU period in microseconds.
cpu_quota (int): Microseconds of CPU time that the container can
get in a CPU period.
cpu_shares (int): CPU shares (relative weight).
cpuset_cpus (str): CPUs in which to allow execution (``0-3``,
``0,1``).
cpuset_mems (str): Memory nodes (MEMs) in which to allow execution
(``0-3``, ``0,1``). Only effective on NUMA systems.
device_cgroup_rules (:py:class:`list`): A list of cgroup rules to
apply to the container.
device_read_bps: Limit read rate (bytes per second) from a device
in the form of: `[{"Path": "device_path", "Rate": rate}]`
device_read_iops: Limit read rate (IO per second) from a device.
device_write_bps: Limit write rate (bytes per second) from a
device.
device_write_iops: Limit write rate (IO per second) from a device.
devices (:py:class:`list`): Expose host devices to the container,
as a list of strings in the form
``<path_on_host>:<path_in_container>:<cgroup_permissions>``.
For example, ``/dev/sda:/dev/xvda:rwm`` allows the container
to have read-write access to the host's ``/dev/sda`` via a
node named ``/dev/xvda`` inside the container.
device_requests (:py:class:`list`): Expose host resources such as
GPUs to the container, as a list of
:py:class:`docker.types.DeviceRequest` instances.
dns (:py:class:`list`): Set custom DNS servers.
dns_opt (:py:class:`list`): Additional options to be added to the
container's ``resolv.conf`` file
dns_search (:py:class:`list`): DNS search domains.
extra_hosts (dict): Additional hostnames to resolve inside the
container, as a mapping of hostname to IP address.
group_add (:py:class:`list`): List of additional group names and/or
IDs that the container process will run as.
init (bool): Run an init inside the container that forwards
signals and reaps processes
ipc_mode (str): Set the IPC mode for the container.
isolation (str): Isolation technology to use. Default: ``None``.
links (dict): Mapping of links using the
``{'container': 'alias'}`` format. The alias is optional.
Containers declared in this dict will be linked to the new
container using the provided alias. Default: ``None``.
log_config (LogConfig): Logging configuration
lxc_conf (dict): LXC config.
mem_limit (float or str): Memory limit. Accepts float values
(which represent the memory limit of the created container in
bytes) or a string with a units identification char
(``100000b``, ``1000k``, ``128m``, ``1g``). If a string is
specified without a units character, bytes are assumed as an
mem_reservation (float or str): Memory soft limit.
mem_swappiness (int): Tune a container's memory swappiness
behavior. Accepts number between 0 and 100.
memswap_limit (str or int): Maximum amount of memory + swap a
container is allowed to consume.
mounts (:py:class:`list`): Specification for mounts to be added to
the container. More powerful alternative to ``binds``. Each
item in the list is expected to be a
:py:class:`docker.types.Mount` object.
network_mode (str): One of:
- ``bridge`` Create a new network stack for the container on
the bridge network.
- ``none`` No networking for this container.
- ``container:<name|id>`` Reuse another container's network
stack.
- ``host`` Use the host network stack.
This mode is incompatible with ``port_bindings``.
oom_kill_disable (bool): Whether to disable OOM killer.
oom_score_adj (int): An integer value containing the score given
to the container in order to tune OOM killer preferences.
pid_mode (str): If set to ``host``, use the host PID namespace
inside the container.
pids_limit (int): Tune a container's pids limit. Set ``-1`` for
unlimited.
port_bindings (dict): See :py:meth:`create_container`
for more information.
Imcompatible with ``host`` in ``network_mode``.
privileged (bool): Give extended privileges to this container.
publish_all_ports (bool): Publish all ports to the host.
read_only (bool): Mount the container's root filesystem as read
only.
restart_policy (dict): Restart the container when it exits.
Configured as a dictionary with keys:
- ``Name`` One of ``on-failure``, or ``always``.
- ``MaximumRetryCount`` Number of times to restart the
container on failure.
security_opt (:py:class:`list`): A list of string values to
customize labels for MLS systems, such as SELinux.
shm_size (str or int): Size of /dev/shm (e.g. ``1G``).
storage_opt (dict): Storage driver options per container as a
key-value mapping.
sysctls (dict): Kernel parameters to set in the container.
tmpfs (dict): Temporary filesystems to mount, as a dictionary
mapping a path inside the container to options for that path.
For example:
.. code-block:: python
{
'/mnt/vol2': '',
'/mnt/vol1': 'size=3G,uid=1000'
}
ulimits (:py:class:`list`): Ulimits to set inside the container,
as a list of :py:class:`docker.types.Ulimit` instances.
userns_mode (str): Sets the user namespace mode for the container
when user namespace remapping option is enabled. Supported
values are: ``host``
uts_mode (str): Sets the UTS namespace mode for the container.
Supported values are: ``host``
volumes_from (:py:class:`list`): List of container names or IDs to
get volumes from.
runtime (str): Runtime to use with this container.
Returns:
(dict) A dictionary which can be passed to the ``host_config``
argument to :py:meth:`create_container`.
Example:
>>> client.api.create_host_config(
... privileged=True,
... cap_drop=['MKNOD'],
... volumes_from=['nostalgic_newton'],
... )
{'CapDrop': ['MKNOD'], 'LxcConf': None, 'Privileged': True,
'VolumesFrom': ['nostalgic_newton'], 'PublishAllPorts': False}
"""
if not kwargs:
kwargs = {}
if 'version' in kwargs:
raise TypeError(
"create_host_config() got an unexpected "
"keyword argument 'version'"
)
kwargs['version'] = self._version
return HostConfig(*args, **kwargs)
def create_networking_config(self, *args, **kwargs):
"""
Create a networking config dictionary to be used as the
``networking_config`` parameter in :py:meth:`create_container`.
Args:
endpoints_config (dict): A dictionary mapping network names to
endpoint configurations generated by
:py:meth:`create_endpoint_config`.
Returns:
(dict) A networking config.
Example:
>>> client.api.create_network('network1')
>>> networking_config = client.api.create_networking_config({
'network1': client.api.create_endpoint_config()
})
>>> container = client.api.create_container(
img, command, networking_config=networking_config
)
"""
return NetworkingConfig(*args, **kwargs)
def create_endpoint_config(self, *args, **kwargs):
"""
Create an endpoint config dictionary to be used with
:py:meth:`create_networking_config`.
Args:
aliases (:py:class:`list`): A list of aliases for this endpoint.
Names in that list can be used within the network to reach the
container. Defaults to ``None``.
links (dict): Mapping of links for this endpoint using the
``{'container': 'alias'}`` format. The alias is optional.
Containers declared in this dict will be linked to this
container using the provided alias. Defaults to ``None``.
ipv4_address (str): The IP address of this container on the
network, using the IPv4 protocol. Defaults to ``None``.
ipv6_address (str): The IP address of this container on the
network, using the IPv6 protocol. Defaults to ``None``.
link_local_ips (:py:class:`list`): A list of link-local (IPv4/IPv6)
addresses.
driver_opt (dict): A dictionary of options to provide to the
network driver. Defaults to ``None``.
Returns:
(dict) An endpoint config.
Example:
>>> endpoint_config = client.api.create_endpoint_config(
aliases=['web', 'app'],
links={'app_db': 'db', 'another': None},
ipv4_address='132.65.0.123'
)
"""
return EndpointConfig(self._version, *args, **kwargs)
@utils.check_resource('container')
def diff(self, container):
"""
Inspect changes on a container's filesystem.
Args:
container (str): The container to diff
Returns:
(list) A list of dictionaries containing the attributes `Path`
and `Kind`.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return self._result(
self._get(self._url("/containers/{0}/changes", container)), True
)
@utils.check_resource('container')
def export(self, container, chunk_size=DEFAULT_DATA_CHUNK_SIZE):
"""
Export the contents of a filesystem as a tar archive.
Args:
container (str): The container to export
chunk_size (int): The number of bytes returned by each iteration
of the generator. If ``None``, data will be streamed as it is
received. Default: 2 MB
Returns:
(generator): The archived filesystem data stream
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
res = self._get(
self._url("/containers/{0}/export", container), stream=True
)
return self._stream_raw_result(res, chunk_size, False)
@utils.check_resource('container')
def get_archive(self, container, path, chunk_size=DEFAULT_DATA_CHUNK_SIZE,
encode_stream=False):
"""
Retrieve a file or folder from a container in the form of a tar
archive.
Args:
container (str): The container where the file is located
path (str): Path to the file or folder to retrieve
chunk_size (int): The number of bytes returned by each iteration
of the generator. If ``None``, data will be streamed as it is
received. Default: 2 MB
encode_stream (bool): Determines if data should be encoded
(gzip-compressed) during transmission. Default: False
Returns:
(tuple): First element is a raw tar data stream. Second element is
a dict containing ``stat`` information on the specified ``path``.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
Example:
>>> c = docker.APIClient()
>>> f = open('./sh_bin.tar', 'wb')
>>> bits, stat = c.api.get_archive(container, '/bin/sh')
>>> print(stat)
{'name': 'sh', 'size': 1075464, 'mode': 493,
'mtime': '2018-10-01T15:37:48-07:00', 'linkTarget': ''}
>>> for chunk in bits:
... f.write(chunk)
>>> f.close()
"""
params = {
'path': path
}
headers = {
"Accept-Encoding": "gzip, deflate"
} if encode_stream else {
"Accept-Encoding": "identity"
}
url = self._url('/containers/{0}/archive', container)
res = self._get(url, params=params, stream=True, headers=headers)
self._raise_for_status(res)
encoded_stat = res.headers.get('x-docker-container-path-stat')
return (
self._stream_raw_result(res, chunk_size, False),
utils.decode_json_header(encoded_stat) if encoded_stat else None
)
@utils.check_resource('container')
def inspect_container(self, container):
"""
Identical to the `docker inspect` command, but only for containers.
Args:
container (str): The container to inspect
Returns:
(dict): Similar to the output of `docker inspect`, but as a
single dict
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return self._result(
self._get(self._url("/containers/{0}/json", container)), True
)
@utils.check_resource('container')
def kill(self, container, signal=None):
"""
Kill a container or send a signal to a container.
Args:
container (str): The container to kill
signal (str or int): The signal to send. Defaults to ``SIGKILL``
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url("/containers/{0}/kill", container)
params = {}
if signal is not None:
if not isinstance(signal, str):
signal = int(signal)
params['signal'] = signal
res = self._post(url, params=params)
self._raise_for_status(res)
@utils.check_resource('container')
def logs(self, container, stdout=True, stderr=True, stream=False,
timestamps=False, tail='all', since=None, follow=None,
until=None):
"""
Get logs from a container. Similar to the ``docker logs`` command.
The ``stream`` parameter makes the ``logs`` function return a blocking
generator you can iterate over to retrieve log output as it happens.
Args:
container (str): The container to get logs from
stdout (bool): Get ``STDOUT``. Default ``True``
stderr (bool): Get ``STDERR``. Default ``True``
stream (bool): Stream the response. Default ``False``
timestamps (bool): Show timestamps. Default ``False``
tail (str or int): Output specified number of lines at the end of
logs. Either an integer of number of lines or the string
``all``. Default ``all``
since (datetime, int, or float): Show logs since a given datetime,
integer epoch (in seconds) or float (in fractional seconds)
follow (bool): Follow log output. Default ``False``
until (datetime, int, or float): Show logs that occurred before
the given datetime, integer epoch (in seconds), or
float (in fractional seconds)
Returns:
(generator of bytes or bytes)
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
if follow is None:
follow = stream
params = {'stderr': stderr and 1 or 0,
'stdout': stdout and 1 or 0,
'timestamps': timestamps and 1 or 0,
'follow': follow and 1 or 0,
}
if tail != 'all' and (not isinstance(tail, int) or tail < 0):
tail = 'all'
params['tail'] = tail
if since is not None:
if isinstance(since, datetime):
params['since'] = utils.datetime_to_timestamp(since)
elif (isinstance(since, int) and since > 0):
params['since'] = since
elif (isinstance(since, float) and since > 0.0):
params['since'] = since
else:
raise errors.InvalidArgument(
'since value should be datetime or positive int/float,'
f' not {type(since)}'
)
if until is not None:
if utils.version_lt(self._version, '1.35'):
raise errors.InvalidVersion(
'until is not supported for API version < 1.35'
)
if isinstance(until, datetime):
params['until'] = utils.datetime_to_timestamp(until)
elif (isinstance(until, int) and until > 0):
params['until'] = until
elif (isinstance(until, float) and until > 0.0):
params['until'] = until
else:
raise errors.InvalidArgument(
f'until value should be datetime or positive int/float, '
f'not {type(until)}'
)
url = self._url("/containers/{0}/logs", container)
res = self._get(url, params=params, stream=stream)
output = self._get_result(container, stream, res)
if stream:
return CancellableStream(output, res)
else:
return output
@utils.check_resource('container')
def pause(self, container):
"""
Pauses all processes within a container.
Args:
container (str): The container to pause
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url('/containers/{0}/pause', container)
res = self._post(url)
self._raise_for_status(res)
@utils.check_resource('container')
def port(self, container, private_port):
"""
Lookup the public-facing port that is NAT-ed to ``private_port``.
Identical to the ``docker port`` command.
Args:
container (str): The container to look up
private_port (int): The private port to inspect
Returns:
(list of dict): The mapping for the host ports
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
Example:
.. code-block:: bash
$ docker run -d -p 80:80 ubuntu:14.04 /bin/sleep 30
7174d6347063a83f412fad6124c99cffd25ffe1a0807eb4b7f9cec76ac8cb43b
.. code-block:: python
>>> client.api.port('7174d6347063', 80)
[{'HostIp': '0.0.0.0', 'HostPort': '80'}]
"""
res = self._get(self._url("/containers/{0}/json", container))
self._raise_for_status(res)
json_ = res.json()
private_port = str(private_port)
h_ports = None
# Port settings is None when the container is running with
# network_mode=host.
port_settings = json_.get('NetworkSettings', {}).get('Ports')
if port_settings is None:
return None
if '/' in private_port:
return port_settings.get(private_port)
for protocol in ['tcp', 'udp', 'sctp']:
h_ports = port_settings.get(f"{private_port}/{protocol}")
if h_ports:
break
return h_ports
@utils.check_resource('container')
def put_archive(self, container, path, data):
"""
Insert a file or folder in an existing container using a tar archive as
source.
Args:
container (str): The container where the file(s) will be extracted
path (str): Path inside the container where the file(s) will be
extracted. Must exist.
data (bytes or stream): tar data to be extracted
Returns:
(bool): True if the call succeeds.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {'path': path}
url = self._url('/containers/{0}/archive', container)
res = self._put(url, params=params, data=data)
self._raise_for_status(res)
return res.status_code == 200
@utils.minimum_version('1.25')
def prune_containers(self, filters=None):
"""
Delete stopped containers
Args:
filters (dict): Filters to process on the prune list.
Returns:
(dict): A dict containing a list of deleted container IDs and
the amount of disk space reclaimed in bytes.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {}
if filters:
params['filters'] = utils.convert_filters(filters)
url = self._url('/containers/prune')
return self._result(self._post(url, params=params), True)
@utils.check_resource('container')
def remove_container(self, container, v=False, link=False, force=False):
"""
Remove a container. Similar to the ``docker rm`` command.
Args:
container (str): The container to remove
v (bool): Remove the volumes associated with the container
link (bool): Remove the specified link and not the underlying
container
force (bool): Force the removal of a running container (uses
``SIGKILL``)
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {'v': v, 'link': link, 'force': force}
res = self._delete(
self._url("/containers/{0}", container), params=params
)
self._raise_for_status(res)
@utils.check_resource('container')
def rename(self, container, name):
"""
Rename a container. Similar to the ``docker rename`` command.
Args:
container (str): ID of the container to rename
name (str): New name for the container
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url("/containers/{0}/rename", container)
params = {'name': name}
res = self._post(url, params=params)
self._raise_for_status(res)
@utils.check_resource('container')
def resize(self, container, height, width):
"""
Resize the tty session.
Args:
container (str or dict): The container to resize
height (int): Height of tty session
width (int): Width of tty session
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {'h': height, 'w': width}
url = self._url("/containers/{0}/resize", container)
res = self._post(url, params=params)
self._raise_for_status(res)
@utils.check_resource('container')
def restart(self, container, timeout=10):
"""
Restart a container. Similar to the ``docker restart`` command.
Args:
container (str or dict): The container to restart. If a dict, the
``Id`` key is used.
timeout (int): Number of seconds to try to stop for before killing
the container. Once killed it will then be restarted. Default
is 10 seconds.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {'t': timeout}
url = self._url("/containers/{0}/restart", container)
conn_timeout = self.timeout
if conn_timeout is not None:
conn_timeout += timeout
res = self._post(url, params=params, timeout=conn_timeout)
self._raise_for_status(res)
@utils.check_resource('container')
def start(self, container, *args, **kwargs):
"""
Start a container. Similar to the ``docker start`` command, but
doesn't support attach options.
**Deprecation warning:** Passing configuration options in ``start`` is
no longer supported. Users are expected to provide host config options
in the ``host_config`` parameter of
:py:meth:`~ContainerApiMixin.create_container`.
Args:
container (str): The container to start
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
:py:class:`docker.errors.DeprecatedMethod`
If any argument besides ``container`` are provided.
Example:
>>> container = client.api.create_container(
... image='busybox:latest',
... command='/bin/sleep 30')
>>> client.api.start(container=container.get('Id'))
"""
if args or kwargs:
raise errors.DeprecatedMethod(
'Providing configuration in the start() method is no longer '
'supported. Use the host_config param in create_container '
'instead.'
)
url = self._url("/containers/{0}/start", container)
res = self._post(url)
self._raise_for_status(res)
@utils.check_resource('container')
def stats(self, container, decode=None, stream=True, one_shot=None):
"""
Stream statistics for a specific container. Similar to the
``docker stats`` command.
Args:
container (str): The container to stream statistics from
decode (bool): If set to true, stream will be decoded into dicts
on the fly. Only applicable if ``stream`` is True.
False by default.
stream (bool): If set to false, only the current stats will be
returned instead of a stream. True by default.
one_shot (bool): If set to true, Only get a single stat instead of
waiting for 2 cycles. Must be used with stream=false. False by
default.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url("/containers/{0}/stats", container)
params = {
'stream': stream
}
if one_shot is not None:
if utils.version_lt(self._version, '1.41'):
raise errors.InvalidVersion(
'one_shot is not supported for API version < 1.41'
)
params['one-shot'] = one_shot
if stream:
if one_shot:
raise errors.InvalidArgument(
'one_shot is only available in conjunction with '
'stream=False'
)
return self._stream_helper(
self._get(url, stream=True, params=params), decode=decode
)
else:
if decode:
raise errors.InvalidArgument(
"decode is only available in conjunction with stream=True"
)
return self._result(self._get(url, params=params), json=True)
@utils.check_resource('container')
def stop(self, container, timeout=None):
"""
Stops a container. Similar to the ``docker stop`` command.
Args:
container (str): The container to stop
timeout (int): Timeout in seconds to wait for the container to
stop before sending a ``SIGKILL``. If None, then the
StopTimeout value of the container will be used.
Default: None
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
if timeout is None:
params = {}
timeout = 10
else:
params = {'t': timeout}
url = self._url("/containers/{0}/stop", container)
conn_timeout = self.timeout
if conn_timeout is not None:
conn_timeout += timeout
res = self._post(url, params=params, timeout=conn_timeout)
self._raise_for_status(res)
@utils.check_resource('container')
def top(self, container, ps_args=None):
"""
Display the running processes of a container.
Args:
container (str): The container to inspect
ps_args (str): An optional arguments passed to ps (e.g. ``aux``)
Returns:
(str): The output of the top
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
u = self._url("/containers/{0}/top", container)
params = {}
if ps_args is not None:
params['ps_args'] = ps_args
return self._result(self._get(u, params=params), True)
@utils.check_resource('container')
def unpause(self, container):
"""
Unpause all processes within a container.
Args:
container (str): The container to unpause
"""
url = self._url('/containers/{0}/unpause', container)
res = self._post(url)
self._raise_for_status(res)
@utils.minimum_version('1.22')
@utils.check_resource('container')
def update_container(
self, container, blkio_weight=None, cpu_period=None, cpu_quota=None,
cpu_shares=None, cpuset_cpus=None, cpuset_mems=None, mem_limit=None,
mem_reservation=None, memswap_limit=None, kernel_memory=None,
restart_policy=None
):
"""
Update resource configs of one or more containers.
Args:
container (str): The container to inspect
blkio_weight (int): Block IO (relative weight), between 10 and 1000
cpu_period (int): Limit CPU CFS (Completely Fair Scheduler) period
cpu_quota (int): Limit CPU CFS (Completely Fair Scheduler) quota
cpu_shares (int): CPU shares (relative weight)
cpuset_cpus (str): CPUs in which to allow execution
cpuset_mems (str): MEMs in which to allow execution
mem_limit (float or str): Memory limit
mem_reservation (float or str): Memory soft limit
memswap_limit (int or str): Total memory (memory + swap), -1 to
disable swap
kernel_memory (int or str): Kernel memory limit
restart_policy (dict): Restart policy dictionary
Returns:
(dict): Dictionary containing a ``Warnings`` key.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url('/containers/{0}/update', container)
data = {}
if blkio_weight:
data['BlkioWeight'] = blkio_weight
if cpu_period:
data['CpuPeriod'] = cpu_period
if cpu_shares:
data['CpuShares'] = cpu_shares
if cpu_quota:
data['CpuQuota'] = cpu_quota
if cpuset_cpus:
data['CpusetCpus'] = cpuset_cpus
if cpuset_mems:
data['CpusetMems'] = cpuset_mems
if mem_limit:
data['Memory'] = utils.parse_bytes(mem_limit)
if mem_reservation:
data['MemoryReservation'] = utils.parse_bytes(mem_reservation)
if memswap_limit:
data['MemorySwap'] = utils.parse_bytes(memswap_limit)
if kernel_memory:
data['KernelMemory'] = utils.parse_bytes(kernel_memory)
if restart_policy:
if utils.version_lt(self._version, '1.23'):
raise errors.InvalidVersion(
'restart policy update is not supported '
'for API version < 1.23'
)
data['RestartPolicy'] = restart_policy
res = self._post_json(url, data=data)
return self._result(res, True)
@utils.check_resource('container')
def wait(self, container, timeout=None, condition=None):
"""
Block until a container stops, then return its exit code. Similar to
the ``docker wait`` command.
Args:
container (str or dict): The container to wait on. If a dict, the
``Id`` key is used.
timeout (int): Request timeout
condition (str): Wait until a container state reaches the given
condition, either ``not-running`` (default), ``next-exit``,
or ``removed``
Returns:
(dict): The API's response as a Python dictionary, including
the container's exit code under the ``StatusCode`` attribute.
Raises:
:py:class:`requests.exceptions.ReadTimeout`
If the timeout is exceeded.
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url("/containers/{0}/wait", container)
params = {}
if condition is not None:
if utils.version_lt(self._version, '1.30'):
raise errors.InvalidVersion(
'wait condition is not supported for API version < 1.30'
)
params['condition'] = condition
res = self._post(url, timeout=timeout, params=params)
return self._result(res, True)
================================================
FILE: docker/api/daemon.py
================================================
import os
from datetime import datetime
from .. import auth, types, utils
class DaemonApiMixin:
@utils.minimum_version('1.25')
def df(self):
"""
Get data usage information.
Returns:
(dict): A dictionary representing different resource categories
and their respective data usage.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url('/system/df')
return self._result(self._get(url), True)
def events(self, since=None, until=None, filters=None, decode=None):
"""
Get real-time events from the server. Similar to the ``docker events``
command.
Args:
since (UTC datetime or int): Get events from this point
until (UTC datetime or int): Get events until this point
filters (dict): Filter the events by event time, container or image
decode (bool): If set to true, stream will be decoded into dicts on
the fly. False by default.
Returns:
A :py:class:`docker.types.daemon.CancellableStream` generator
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
Example:
>>> for event in client.events(decode=True)
... print(event)
{u'from': u'image/with:tag',
u'id': u'container-id',
u'status': u'start',
u'time': 1423339459}
...
or
>>> events = client.events()
>>> for event in events:
... print(event)
>>> # and cancel from another thread
>>> events.close()
"""
if isinstance(since, datetime):
since = utils.datetime_to_timestamp(since)
if isinstance(until, datetime):
until = utils.datetime_to_timestamp(until)
if filters:
filters = utils.convert_filters(filters)
params = {
'since': since,
'until': until,
'filters': filters
}
url = self._url('/events')
response = self._get(url, params=params, stream=True, timeout=None)
stream = self._stream_helper(response, decode=decode)
return types.CancellableStream(stream, response)
def info(self):
"""
Display system-wide information. Identical to the ``docker info``
command.
Returns:
(dict): The info as a dict
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return self._result(self._get(self._url("/info")), True)
def login(self, username, password=None, email=None, registry=None,
reauth=False, dockercfg_path=None):
"""
Authenticate with a registry. Similar to the ``docker login`` command.
Args:
username (str): The registry username
password (str): The plaintext password
email (str): The email for the registry account
registry (str): URL to the registry. E.g.
``https://index.docker.io/v1/``
reauth (bool): Whether or not to refresh existing authentication on
the Docker server.
dockercfg_path (str): Use a custom path for the Docker config file
(default ``$HOME/.docker/config.json`` if present,
otherwise ``$HOME/.dockercfg``)
Returns:
(dict): The response from the login request
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
# If we don't have any auth data so far, try reloading the config file
# one more time in case anything showed up in there.
# If dockercfg_path is passed check to see if the config file exists,
# if so load that config.
if dockercfg_path and os.path.exists(dockercfg_path):
self._auth_configs = auth.load_config(
dockercfg_path, credstore_env=self.credstore_env
)
elif not self._auth_configs or self._auth_configs.is_empty:
self._auth_configs = auth.load_config(
credstore_env=self.credstore_env
)
authcfg = self._auth_configs.resolve_authconfig(registry)
# If we found an existing auth config for this registry and username
# combination, we can return it immediately unless reauth is requested.
if authcfg and authcfg.get('username', None) == username \
and not reauth:
return authcfg
req_data = {
'username': username,
'password': password,
'email': email,
'serveraddress': registry,
}
response = self._post_json(self._url('/auth'), data=req_data)
if response.status_code == 200:
self._auth_configs.add_auth(registry or auth.INDEX_NAME, req_data)
return self._result(response, json=True)
def ping(self):
"""
Checks the server is responsive. An exception will be raised if it
isn't responding.
Returns:
(bool) The response from the server.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return self._result(self._get(self._url('/_ping'))) == 'OK'
def version(self, api_version=True):
"""
Returns version information from the server. Similar to the ``docker
version`` command.
Returns:
(dict): The server version information
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url("/version", versioned_api=api_version)
return self._result(self._get(url), json=True)
================================================
FILE: docker/api/exec_api.py
================================================
from .. import errors, utils
from ..types import CancellableStream
class ExecApiMixin:
@utils.check_resource('container')
def exec_create(self, container, cmd, stdout=True, stderr=True,
stdin=False, tty=False, privileged=False, user='',
environment=None, workdir=None, detach_keys=None):
"""
Sets up an exec instance in a running container.
Args:
container (str): Target container where exec instance will be
created
cmd (str or list): Command to be executed
stdout (bool): Attach to stdout. Default: ``True``
stderr (bool): Attach to stderr. Default: ``True``
stdin (bool): Attach to stdin. Default: ``False``
tty (bool): Allocate a pseudo-TTY. Default: False
privileged (bool): Run as privileged.
user (str): User to execute command as. Default: root
environment (dict or list): A dictionary or a list of strings in
the following format ``["PASSWORD=xxx"]`` or
``{"PASSWORD": "xxx"}``.
workdir (str): Path to working directory for this exec session
detach_keys (str): Override the key sequence for detaching
a container. Format is a single character `[a-Z]`
or `ctrl-<value>` where `<value>` is one of:
`a-z`, `@`, `^`, `[`, `,` or `_`.
~/.docker/config.json is used by default.
Returns:
(dict): A dictionary with an exec ``Id`` key.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
if environment is not None and utils.version_lt(self._version, '1.25'):
raise errors.InvalidVersion(
'Setting environment for exec is not supported in API < 1.25'
)
if isinstance(cmd, str):
cmd = utils.split_command(cmd)
if isinstance(environment, dict):
environment = utils.utils.format_environment(environment)
data = {
'Container': container,
'User': user,
'Privileged': privileged,
'Tty': tty,
'AttachStdin': stdin,
'AttachStdout': stdout,
'AttachStderr': stderr,
'Cmd': cmd,
'Env': environment,
}
if workdir is not None:
if utils.version_lt(self._version, '1.35'):
raise errors.InvalidVersion(
'workdir is not supported for API version < 1.35'
)
data['WorkingDir'] = workdir
if detach_keys:
data['detachKeys'] = detach_keys
elif 'detachKeys' in self._general_configs:
data['detachKeys'] = self._general_configs['detachKeys']
url = self._url('/containers/{0}/exec', container)
res = self._post_json(url, data=data)
return self._result(res, True)
def exec_inspect(self, exec_id):
"""
Return low-level information about an exec command.
Args:
exec_id (str): ID of the exec instance
Returns:
(dict): Dictionary of values returned by the endpoint.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
if isinstance(exec_id, dict):
exec_id = exec_id.get('Id')
res = self._get(self._url("/exec/{0}/json", exec_id))
return self._result(res, True)
def exec_resize(self, exec_id, height=None, width=None):
"""
Resize the tty session used by the specified exec command.
Args:
exec_id (str): ID of the exec instance
height (int): Height of tty session
width (int): Width of tty session
"""
if isinstance(exec_id, dict):
exec_id = exec_id.get('Id')
params = {'h': height, 'w': width}
url = self._url("/exec/{0}/resize", exec_id)
res = self._post(url, params=params)
self._raise_for_status(res)
@utils.check_resource('exec_id')
def exec_start(self, exec_id, detach=False, tty=False, stream=False,
socket=False, demux=False):
"""
Start a previously set up exec instance.
Args:
exec_id (str): ID of the exec instance
detach (bool): If true, detach from the exec command.
Default: False
tty (bool): Allocate a pseudo-TTY. Default: False
stream (bool): Return response data progressively as an iterator
of strings, rather than a single string.
socket (bool): Return the connection socket to allow custom
read/write operations. Must be closed by the caller when done.
demux (bool): Return stdout and stderr separately
Returns:
(generator or str or tuple): If ``stream=True``, a generator
yielding response chunks. If ``socket=True``, a socket object for
the connection. A string containing response data otherwise. If
``demux=True``, a tuple with two elements of type byte: stdout and
stderr.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
# we want opened socket if socket == True
data = {
'Tty': tty,
'Detach': detach
}
headers = {} if detach else {
'Connection': 'Upgrade',
'Upgrade': 'tcp'
}
res = self._post_json(
self._url('/exec/{0}/start', exec_id),
headers=headers,
data=data,
stream=True
)
if detach:
try:
return self._result(res)
finally:
res.close()
if socket:
return self._get_raw_response_socket(res)
output = self._read_from_socket(res, stream, tty=tty, demux=demux)
if stream:
return CancellableStream(output, res)
else:
return output
================================================
FILE: docker/api/image.py
================================================
import logging
import os
from .. import auth, errors, utils
from ..constants import DEFAULT_DATA_CHUNK_SIZE
log = logging.getLogger(__name__)
class ImageApiMixin:
@utils.check_resource('image')
def get_image(self, image, chunk_size=DEFAULT_DATA_CHUNK_SIZE):
"""
Get a tarball of an image. Similar to the ``docker save`` command.
Args:
image (str): Image name to get
chunk_size (int): The number of bytes returned by each iteration
of the generator. If ``None``, data will be streamed as it is
received. Default: 2 MB
Returns:
(generator): A stream of raw archive data.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
Example:
>>> image = client.api.get_image("busybox:latest")
>>> f = open('/tmp/busybox-latest.tar', 'wb')
>>> for chunk in image:
>>> f.write(chunk)
>>> f.close()
"""
res = self._get(self._url("/images/{0}/get", image), stream=True)
return self._stream_raw_result(res, chunk_size, False)
@utils.check_resource('image')
def history(self, image):
"""
Show the history of an image.
Args:
image (str): The image to show history for
Returns:
(list): The history of the image
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
res = self._get(self._url("/images/{0}/history", image))
return self._result(res, True)
def images(self, name=None, quiet=False, all=False, filters=None):
"""
List images. Similar to the ``docker images`` command.
Args:
name (str): Only show images belonging to the repository ``name``
quiet (bool): Only return numeric IDs as a list.
all (bool): Show intermediate image layers. By default, these are
filtered out.
filters (dict): Filters to be processed on the image list.
Available filters:
- ``dangling`` (bool)
- `label` (str|list): format either ``"key"``, ``"key=value"``
or a list of such.
Returns:
(dict or list): A list if ``quiet=True``, otherwise a dict.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {
'only_ids': 1 if quiet else 0,
'all': 1 if all else 0,
}
if name:
if utils.version_lt(self._version, '1.25'):
# only use "filter" on API 1.24 and under, as it is deprecated
params['filter'] = name
else:
if filters:
filters['reference'] = name
else:
filters = {'reference': name}
if filters:
params['filters'] = utils.convert_filters(filters)
res = self._result(self._get(self._url("/images/json"), params=params),
True)
if quiet:
return [x['Id'] for x in res]
return res
def import_image(self, src=None, repository=None, tag=None, image=None,
changes=None, stream_src=False):
"""
Import an image. Similar to the ``docker import`` command.
If ``src`` is a string or unicode string, it will first be treated as a
path to a tarball on the local system. If there is an error reading
from that file, ``src`` will be treated as a URL instead to fetch the
image from. You can also pass an open file handle as ``src``, in which
case the data will be read from that file.
If ``src`` is unset but ``image`` is set, the ``image`` parameter will
be taken as the name of an existing image to import from.
Args:
src (str or file): Path to tarfile, URL, or file-like object
repository (str): The repository to create
tag (str): The tag to apply
image (str): Use another image like the ``FROM`` Dockerfile
parameter
"""
if not (src or image):
raise errors.DockerException(
'Must specify src or image to import from'
)
u = self._url('/images/create')
params = _import_image_params(
repository, tag, image,
src=(src if isinstance(src, str) else None),
changes=changes
)
headers = {'Content-Type': 'application/tar'}
if image or params.get('fromSrc') != '-': # from image or URL
return self._result(
self._post(u, data=None, params=params)
)
elif isinstance(src, str): # from file path
with open(src, 'rb') as f:
return self._result(
self._post(
u, data=f, params=params, headers=headers, timeout=None
)
)
else: # from raw data
if stream_src:
headers['Transfer-Encoding'] = 'chunked'
return self._result(
self._post(u, data=src, params=params, headers=headers)
)
def import_image_from_data(self, data, repository=None, tag=None,
changes=None):
"""
Like :py:meth:`~docker.api.image.ImageApiMixin.import_image`, but
allows importing in-memory bytes data.
Args:
data (bytes collection): Bytes collection containing valid tar data
repository (str): The repository to create
tag (str): The tag to apply
"""
u = self._url('/images/create')
params = _import_image_params(
repository, tag, src='-', changes=changes
)
headers = {'Content-Type': 'application/tar'}
return self._result(
self._post(
u, data=data, params=params, headers=headers, timeout=None
)
)
def import_image_from_file(self, filename, repository=None, tag=None,
changes=None):
"""
Like :py:meth:`~docker.api.image.ImageApiMixin.import_image`, but only
supports importing from a tar file on disk.
Args:
filename (str): Full path to a tar file.
repository (str): The repository to create
tag (str): The tag to apply
Raises:
IOError: File does not exist.
"""
return self.import_image(
src=filename, repository=repository, tag=tag, changes=changes
)
def import_image_from_stream(self, stream, repository=None, tag=None,
changes=None):
return self.import_image(
src=stream, stream_src=True, repository=repository, tag=tag,
changes=changes
)
def import_image_from_url(self, url, repository=None, tag=None,
changes=None):
"""
Like :py:meth:`~docker.api.image.ImageApiMixin.import_image`, but only
supports importing from a URL.
Args:
url (str): A URL pointing to a tar file.
repository (str): The repository to create
tag (str): The tag to apply
"""
return self.import_image(
src=url, repository=repository, tag=tag, changes=changes
)
def import_image_from_image(self, image, repository=None, tag=None,
changes=None):
"""
Like :py:meth:`~docker.api.image.ImageApiMixin.import_image`, but only
supports importing from another image, like the ``FROM`` Dockerfile
parameter.
Args:
image (str): Image name to import from
repository (str): The repository to create
tag (str): The tag to apply
"""
return self.import_image(
image=image, repository=repository, tag=tag, changes=changes
)
@utils.check_resource('image')
def inspect_image(self, image):
"""
Get detailed information about an image. Similar to the ``docker
inspect`` command, but only for images.
Args:
image (str): The image to inspect
Returns:
(dict): Similar to the output of ``docker inspect``, but as a
single dict
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return self._result(
self._get(self._url("/images/{0}/json", image)), True
)
@utils.minimum_version('1.30')
@utils.check_resource('image')
def inspect_distribution(self, image, auth_config=None):
"""
Get image digest and platform information by contacting the registry.
Args:
image (str): The image name to inspect
auth_config (dict): Override the credentials that are found in the
config for this request. ``auth_config`` should contain the
``username`` and ``password`` keys to be valid.
Returns:
(dict): A dict containing distribution data
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
registry, _ = auth.resolve_repository_name(image)
headers = {}
if auth_config is None:
header = auth.get_config_header(self, registry)
if header:
headers['X-Registry-Auth'] = header
else:
log.debug('Sending supplied auth config')
headers['X-Registry-Auth'] = auth.encode_header(auth_config)
url = self._url("/distribution/{0}/json", image)
return self._result(
self._get(url, headers=headers), True
)
def load_image(self, data, quiet=None):
"""
Load an image that was previously saved using
:py:meth:`~docker.api.image.ImageApiMixin.get_image` (or ``docker
save``). Similar to ``docker load``.
Args:
data (binary): Image data to be loaded.
quiet (boolean): Suppress progress details in response.
Returns:
(generator): Progress output as JSON objects. Only available for
API version >= 1.23
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {}
if quiet is not None:
if utils.version_lt(self._version, '1.23'):
raise errors.InvalidVersion(
'quiet is not supported in API version < 1.23'
)
params['quiet'] = quiet
res = self._post(
self._url("/images/load"), data=data, params=params, stream=True
)
if utils.version_gte(self._version, '1.23'):
return self._stream_helper(res, decode=True)
self._raise_for_status(res)
@utils.minimum_version('1.25')
def prune_images(self, filters=None):
"""
Delete unused images
Args:
filters (dict): Filters to process on the prune list.
Available filters:
- dangling (bool): When set to true (or 1), prune only
unused and untagged images.
Returns:
(dict): A dict containing a list of deleted image IDs and
the amount of disk space reclaimed in bytes.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url("/images/prune")
params = {}
if filters is not None:
params['filters'] = utils.convert_filters(filters)
return self._result(self._post(url, params=params), True)
def pull(self, repository, tag=None, stream=False, auth_config=None,
decode=False, platform=None, all_tags=False):
"""
Pulls an image. Similar to the ``docker pull`` command.
Args:
repository (str): The repository to pull
tag (str): The tag to pull. If ``tag`` is ``None`` or empty, it
is set to ``latest``.
stream (bool): Stream the output as a generator. Make sure to
consume the generator, otherwise pull might get cancelled.
auth_config (dict): Override the credentials that are found in the
config for this request. ``auth_config`` should contain the
``username`` and ``password`` keys to be valid.
decode (bool): Decode the JSON data from the server into dicts.
Only applies with ``stream=True``
platform (str): Platform in the format ``os[/arch[/variant]]``
all_tags (bool): Pull all image tags, the ``tag`` parameter is
ignored.
Returns:
(generator or str): The output
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
Example:
>>> resp = client.api.pull('busybox', stream=True, decode=True)
... for line in resp:
... print(json.dumps(line, indent=4))
{
"status": "Pulling image (latest) from busybox",
"progressDetail": {},
"id": "e72ac664f4f0"
}
{
"status": "Pulling image (latest) from busybox, endpoint: ...",
"progressDetail": {},
"id": "e72ac664f4f0"
}
"""
repository, image_tag = utils.parse_repository_tag(repository)
tag = tag or image_tag or 'latest'
if all_tags:
tag = None
registry, repo_name = auth.resolve_repository_name(repository)
params = {
'tag': tag,
'fromImage': repository
}
headers = {}
if auth_config is None:
header = auth.get_config_header(self, registry)
if header:
headers['X-Registry-Auth'] = header
else:
log.debug('Sending supplied auth config')
headers['X-Registry-Auth'] = auth.encode_header(auth_config)
if platform is not None:
if utils.version_lt(self._version, '1.32'):
raise errors.InvalidVersion(
'platform was only introduced in API version 1.32'
)
params['platform'] = platform
response = self._post(
self._url('/images/create'), params=params, headers=headers,
stream=stream, timeout=None
)
self._raise_for_status(response)
if stream:
return self._stream_helper(response, decode=decode)
return self._result(response)
def push(self, repository, tag=None, stream=False, auth_config=None,
decode=False):
"""
Push an image or a repository to the registry. Similar to the ``docker
push`` command.
Args:
repository (str): The repository to push to
tag (str): An optional tag to push
stream (bool): Stream the output as a blocking generator
auth_config (dict): Override the credentials that are found in the
config for this request. ``auth_config`` should contain the
``username`` and ``password`` keys to be valid.
decode (bool): Decode the JSON data from the server into dicts.
Only applies with ``stream=True``
Returns:
(generator or str): The output from the server.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
Example:
>>> resp = client.api.push(
... 'yourname/app',
... stream=True,
... decode=True,
... )
... for line in resp:
... print(line)
{'status': 'Pushing repository yourname/app (1 tags)'}
{'status': 'Pushing','progressDetail': {}, 'id': '511136ea3c5a'}
{'status': 'Image already pushed, skipping', 'progressDetail':{},
'id': '511136ea3c5a'}
...
"""
if not tag:
repository, tag = utils.parse_repository_tag(repository)
registry, repo_name = auth.resolve_repository_name(repository)
u = self._url("/images/{0}/push", repository)
params = {
'tag': tag
}
headers = {}
if auth_config is None:
header = auth.get_config_header(self, registry)
if header:
headers['X-Registry-Auth'] = header
else:
log.debug('Sending supplied auth config')
headers['X-Registry-Auth'] = auth.encode_header(auth_config)
response = self._post_json(
u, None, headers=headers, stream=stream, params=params
)
self._raise_for_status(response)
if stream:
return self._stream_helper(response, decode=decode)
return self._result(response)
@utils.check_resource('image')
def remove_image(self, image, force=False, noprune=False):
"""
Remove an image. Similar to the ``docker rmi`` command.
Args:
image (str): The image to remove
force (bool): Force removal of the image
noprune (bool): Do not delete untagged parents
"""
params = {'force': force, 'noprune': noprune}
res = self._delete(self._url("/images/{0}", image), params=params)
return self._result(res, True)
def search(self, term, limit=None):
"""
Search for images on Docker Hub. Similar to the ``docker search``
command.
Args:
term (str): A term to search for.
limit (int): The maximum number of results to return.
Returns:
(list of dicts): The response of the search.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {'term': term}
if limit is not None:
params['limit'] = limit
return self._result(
self._get(self._url("/images/search"), params=params),
True
)
@utils.check_resource('image')
def tag(self, image, repository, tag=None, force=False):
"""
Tag an image into a repository. Similar to the ``docker tag`` command.
Args:
image (str): The image to tag
repository (str): The repository to set for the tag
tag (str): The tag name
force (bool): Force
Returns:
(bool): ``True`` if successful
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
Example:
>>> client.api.tag('ubuntu', 'localhost:5000/ubuntu', 'latest',
force=True)
"""
params = {
'tag': tag,
'repo': repository,
'force': 1 if force else 0
}
url = self._url("/images/{0}/tag", image)
res = self._post(url, params=params)
self._raise_for_status(res)
return res.status_code == 201
def is_file(src):
try:
return (
isinstance(src, str) and
os.path.isfile(src)
)
except TypeError: # a data string will make isfile() raise a TypeError
return False
def _import_image_params(repo, tag, image=None, src=None,
changes=None):
params = {
'repo': repo,
'tag': tag,
}
if image:
params['fromImage'] = image
elif src and not is_file(src):
params['fromSrc'] = src
else:
params['fromSrc'] = '-'
if changes:
params['changes'] = changes
return params
================================================
FILE: docker/api/network.py
================================================
from .. import utils
from ..errors import InvalidVersion
from ..utils import check_resource, minimum_version, version_lt
class NetworkApiMixin:
def networks(self, names=None, ids=None, filters=None):
"""
List networks. Similar to the ``docker network ls`` command.
Args:
names (:py:class:`list`): List of names to filter by
ids (:py:class:`list`): List of ids to filter by
filters (dict): Filters to be processed on the network list.
Available filters:
- ``driver=[<driver-name>]`` Matches a network's driver.
- ``label=[<key>]``, ``label=[<key>=<value>]`` or a list of
such.
- ``type=["custom"|"builtin"]`` Filters networks by type.
Returns:
(dict): List of network objects.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
if filters is None:
filters = {}
if names:
filters['name'] = names
if ids:
filters['id'] = ids
params = {'filters': utils.convert_filters(filters)}
url = self._url("/networks")
res = self._get(url, params=params)
return self._result(res, json=True)
def create_network(self, name, driver=None, options=None, ipam=None,
check_duplicate=None, internal=False, labels=None,
enable_ipv6=False, attachable=None, scope=None,
ingress=None):
"""
Create a network. Similar to the ``docker network create``.
Args:
name (str): Name of the network
driver (str): Name of the driver used to create the network
options (dict): Driver options as a key-value dictionary
ipam (IPAMConfig): Optional custom IP scheme for the network.
check_duplicate (bool): Request daemon to check for networks with
same name. Default: ``None``.
internal (bool): Restrict external access to the network. Default
``False``.
labels (dict): Map of labels to set on the network. Default
``None``.
enable_ipv6 (bool): Enable IPv6 on the network. Default ``False``.
attachable (bool): If enabled, and the network is in the global
scope, non-service containers on worker nodes will be able to
connect to the network.
scope (str): Specify the network's scope (``local``, ``global`` or
``swarm``)
ingress (bool): If set, create an ingress network which provides
the routing-mesh in swarm mode.
Returns:
(dict): The created network reference object
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
Example:
A network using the bridge driver:
>>> client.api.create_network("network1", driver="bridge")
You can also create more advanced networks with custom IPAM
configurations. For example, setting the subnet to
``192.168.52.0/24`` and gateway address to ``192.168.52.254``.
.. code-block:: python
>>> ipam_pool = docker.types.IPAMPool(
subnet='192.168.52.0/24',
gateway='192.168.52.254'
)
>>> ipam_config = docker.types.IPAMConfig(
pool_configs=[ipam_pool]
)
>>> client.api.create_network("network1", driver="bridge",
ipam=ipam_config)
"""
if options is not None and not isinstance(options, dict):
raise TypeError('options must be a dictionary')
data = {
'Name': name,
'Driver': driver,
'Options': options,
'IPAM': ipam,
'CheckDuplicate': check_duplicate,
}
if labels is not None:
if version_lt(self._version, '1.23'):
raise InvalidVersion(
'network labels were introduced in API 1.23'
)
if not isinstance(labels, dict):
raise TypeError('labels must be a dictionary')
data["Labels"] = labels
if enable_ipv6:
if version_lt(self._version, '1.23'):
raise InvalidVersion(
'enable_ipv6 was introduced in API 1.23'
)
data['EnableIPv6'] = True
if internal:
if version_lt(self._version, '1.22'):
raise InvalidVersion('Internal networks are not '
'supported in API version < 1.22')
data['Internal'] = True
if attachable is not None:
if version_lt(self._version, '1.24'):
raise InvalidVersion(
'attachable is not supported in API version < 1.24'
)
data['Attachable'] = attachable
if ingress is not None:
if version_lt(self._version, '1.29'):
raise InvalidVersion(
'ingress is not supported in API version < 1.29'
)
data['Ingress'] = ingress
if scope is not None:
if version_lt(self._version, '1.30'):
raise InvalidVersion(
'scope is not supported in API version < 1.30'
)
data['Scope'] = scope
url = self._url("/networks/create")
res = self._post_json(url, data=data)
return self._result(res, json=True)
@minimum_version('1.25')
def prune_networks(self, filters=None):
"""
Delete unused networks
Args:
filters (dict): Filters to process on the prune list.
Returns:
(dict): A dict containing a list of deleted network names and
the amount of disk space reclaimed in bytes.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {}
if filters:
params['filters'] = utils.convert_filters(filters)
url = self._url('/networks/prune')
return self._result(self._post(url, params=params), True)
@check_resource('net_id')
def remove_network(self, net_id):
"""
Remove a network. Similar to the ``docker network rm`` command.
Args:
net_id (str): The network's id
"""
url = self._url("/networks/{0}", net_id)
res = self._delete(url)
self._raise_for_status(res)
@check_resource('net_id')
def inspect_network(self, net_id, verbose=None, scope=None):
"""
Get detailed information about a network.
Args:
net_id (str): ID of network
verbose (bool): Show the service details across the cluster in
swarm mode.
scope (str): Filter the network by scope (``swarm``, ``global``
or ``local``).
"""
params = {}
if verbose is not None:
if version_lt(self._version, '1.28'):
raise InvalidVersion('verbose was introduced in API 1.28')
params['verbose'] = verbose
if scope is not None:
if version_lt(self._version, '1.31'):
raise InvalidVersion('scope was introduced in API 1.31')
params['scope'] = scope
url = self._url("/networks/{0}", net_id)
res = self._get(url, params=params)
return self._result(res, json=True)
@check_resource('container')
def connect_container_to_network(self, container, net_id,
ipv4_address=None, ipv6_address=None,
aliases=None, links=None,
link_local_ips=None, driver_opt=None,
mac_address=None):
"""
Connect a container to a network.
Args:
container (str): container-id/name to be connected to the network
net_id (str): network id
aliases (:py:class:`list`): A list of aliases for this endpoint.
Names in that list can be used within the network to reach the
container. Defaults to ``None``.
links (:py:class:`list`): A list of links for this endpoint.
Containers declared in this list will be linked to this
container. Defaults to ``None``.
ipv4_address (str): The IP address of this container on the
network, using the IPv4 protocol. Defaults to ``None``.
ipv6_address (str): The IP address of this container on the
network, using the IPv6 protocol. Defaults to ``None``.
link_local_ips (:py:class:`list`): A list of link-local
(IPv4/IPv6) addresses.
mac_address (str): The MAC address of this container on the
network. Defaults to ``None``.
"""
data = {
"Container": container,
"EndpointConfig": self.create_endpoint_config(
aliases=aliases, links=links, ipv4_address=ipv4_address,
ipv6_address=ipv6_address, link_local_ips=link_local_ips,
driver_opt=driver_opt,
mac_address=mac_address
),
}
url = self._url("/networks/{0}/connect", net_id)
res = self._post_json(url, data=data)
self._raise_for_status(res)
@check_resource('container')
def disconnect_container_from_network(self, container, net_id,
force=False):
"""
Disconnect a container from a network.
Args:
container (str): container ID or name to be disconnected from the
network
net_id (str): network ID
force (bool): Force the container to disconnect from a network.
Default: ``False``
"""
data = {"Container": container}
if force:
if version_lt(self._version, '1.22'):
raise InvalidVersion(
'Forced disconnect was introduced in API 1.22'
)
data['Force'] = force
url = self._url("/networks/{0}/disconnect", net_id)
res = self._post_json(url, data=data)
self._raise_for_status(res)
================================================
FILE: docker/api/plugin.py
================================================
from .. import auth, utils
class PluginApiMixin:
@utils.minimum_version('1.25')
@utils.check_resource('name')
def configure_plugin(self, name, options):
"""
Configure a plugin.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
options (dict): A key-value mapping of options
Returns:
``True`` if successful
"""
url = self._url('/plugins/{0}/set', name)
data = options
if isinstance(data, dict):
data = [f'{k}={v}' for k, v in data.items()]
res = self._post_json(url, data=data)
self._raise_for_status(res)
return True
@utils.minimum_version('1.25')
def create_plugin(self, name, plugin_data_dir, gzip=False):
"""
Create a new plugin.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
plugin_data_dir (string): Path to the plugin data directory.
Plugin data directory must contain the ``config.json``
manifest file and the ``rootfs`` directory.
gzip (bool): Compress the context using gzip. Default: False
Returns:
``True`` if successful
"""
url = self._url('/plugins/create')
with utils.create_archive(
root=plugin_data_dir, gzip=gzip,
files=set(utils.build.walk(plugin_data_dir, []))
) as archv:
res = self._post(url, params={'name': name}, data=archv)
self._raise_for_status(res)
return True
@utils.minimum_version('1.25')
def disable_plugin(self, name, force=False):
"""
Disable an installed plugin.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
force (bool): To enable the force query parameter.
Returns:
``True`` if successful
"""
url = self._url('/plugins/{0}/disable', name)
res = self._post(url, params={'force': force})
self._raise_for_status(res)
return True
@utils.minimum_version('1.25')
def enable_plugin(self, name, timeout=0):
"""
Enable an installed plugin.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
timeout (int): Operation timeout (in seconds). Default: 0
Returns:
``True`` if successful
"""
url = self._url('/plugins/{0}/enable', name)
params = {'timeout': timeout}
res = self._post(url, params=params)
self._raise_for_status(res)
return True
@utils.minimum_version('1.25')
def inspect_plugin(self, name):
"""
Retrieve plugin metadata.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
Returns:
A dict containing plugin info
"""
url = self._url('/plugins/{0}/json', name)
return self._result(self._get(url), True)
@utils.minimum_version('1.25')
def pull_plugin(self, remote, privileges, name=None):
"""
Pull and install a plugin. After the plugin is installed, it can be
enabled using :py:meth:`~enable_plugin`.
Args:
remote (string): Remote reference for the plugin to install.
The ``:latest`` tag is optional, and is the default if
omitted.
privileges (:py:class:`list`): A list of privileges the user
consents to grant to the plugin. Can be retrieved using
:py:meth:`~plugin_privileges`.
name (string): Local name for the pulled plugin. The
``:latest`` tag is optional, and is the default if omitted.
Returns:
An iterable object streaming the decoded API logs
"""
url = self._url('/plugins/pull')
params = {
'remote': remote,
}
if name:
params['name'] = name
headers = {}
registry, repo_name = auth.resolve_repository_name(remote)
header = auth.get_config_header(self, registry)
if header:
headers['X-Registry-Auth'] = header
response = self._post_json(
url, params=params, headers=headers, data=privileges,
stream=True
)
self._raise_for_status(response)
return self._stream_helper(response, decode=True)
@utils.minimum_version('1.25')
def plugins(self):
"""
Retrieve a list of installed plugins.
Returns:
A list of dicts, one per plugin
"""
url = self._url('/plugins')
return self._result(self._get(url), True)
@utils.minimum_version('1.25')
def plugin_privileges(self, name):
"""
Retrieve list of privileges to be granted to a plugin.
Args:
name (string): Name of the remote plugin to examine. The
``:latest`` tag is optional, and is the default if omitted.
Returns:
A list of dictionaries representing the plugin's
permissions
"""
params = {
'remote': name,
}
headers = {}
registry, repo_name = auth.resolve_repository_name(name)
header = auth.get_config_header(self, registry)
if header:
headers['X-Registry-Auth'] = header
url = self._url('/plugins/privileges')
return self._result(
self._get(url, params=params, headers=headers), True
)
@utils.minimum_version('1.25')
@utils.check_resource('name')
def push_plugin(self, name):
"""
Push a plugin to the registry.
Args:
name (string): Name of the plugin to upload. The ``:latest``
tag is optional, and is the default if omitted.
Returns:
``True`` if successful
"""
url = self._url('/plugins/{0}/pull', name)
headers = {}
registry, repo_name = auth.resolve_repository_name(name)
header = auth.get_config_header(self, registry)
if header:
headers['X-Registry-Auth'] = header
res = self._post(url, headers=headers)
self._raise_for_status(res)
return self._stream_helper(res, decode=True)
@utils.minimum_version('1.25')
@utils.check_resource('name')
def remove_plugin(self, name, force=False):
"""
Remove an installed plugin.
Args:
name (string): Name of the plugin to remove. The ``:latest``
tag is optional, and is the default if omitted.
force (bool): Disable the plugin before removing. This may
result in issues if the plugin is in use by a container.
Returns:
``True`` if successful
"""
url = self._url('/plugins/{0}', name)
res = self._delete(url, params={'force': force})
self._raise_for_status(res)
return True
@utils.minimum_version('1.26')
@utils.check_resource('name')
def upgrade_plugin(self, name, remote, privileges):
"""
Upgrade an installed plugin.
Args:
name (string): Name of the plugin to upgrade. The ``:latest``
tag is optional and is the default if omitted.
remote (string): Remote reference to upgrade to. The
``:latest`` tag is optional and is the default if omitted.
privileges (:py:class:`list`): A list of privileges the user
consents to grant to the plugin. Can be retrieved using
:py:meth:`~plugin_privileges`.
Returns:
An iterable object streaming the decoded API logs
"""
url = self._url('/plugins/{0}/upgrade', name)
params = {
'remote': remote,
}
headers = {}
registry, repo_name = auth.resolve_repository_name(remote)
header = auth.get_config_header(self, registry)
if header:
headers['X-Registry-Auth'] = header
response = self._post_json(
url, params=params, headers=headers, data=privileges,
stream=True
)
self._raise_for_status(response)
return self._stream_helper(response, decode=True)
================================================
FILE: docker/api/secret.py
================================================
import base64
from .. import errors, utils
class SecretApiMixin:
@utils.minimum_version('1.25')
def create_secret(self, name, data, labels=None, driver=None):
"""
Create a secret
Args:
name (string): Name of the secret
data (bytes): Secret data to be stored
labels (dict): A mapping of labels to assign to the secret
driver (DriverConfig): A custom driver configuration. If
unspecified, the default ``internal`` driver will be used
Returns (dict): ID of the newly created secret
"""
if not isinstance(data, bytes):
data = data.encode('utf-8')
data = base64.b64encode(data)
data = data.decode('ascii')
body = {
'Data': data,
'Name': name,
'Labels': labels
}
if driver is not None:
if utils.version_lt(self._version, '1.31'):
raise errors.InvalidVersion(
'Secret driver is only available for API version > 1.31'
)
body['Driver'] = driver
url = self._url('/secrets/create')
return self._result(
self._post_json(url, data=body), True
)
@utils.minimum_version('1.25')
@utils.check_resource('id')
def inspect_secret(self, id):
"""
Retrieve secret metadata
Args:
id (string): Full ID of the secret to inspect
Returns (dict): A dictionary of metadata
Raises:
:py:class:`docker.errors.NotFound`
if no secret with that ID exists
"""
url = self._url('/secrets/{0}', id)
return self._result(self._get(url), True)
@utils.minimum_version('1.25')
@utils.check_resource('id')
def remove_secret(self, id):
"""
Remove a secret
Args:
id (string): Full ID of the secret to remove
Returns (boolean): True if successful
Raises:
:py:class:`docker.errors.NotFound`
if no secret with that ID exists
"""
url = self._url('/secrets/{0}', id)
res = self._delete(url)
self._raise_for_status(res)
return True
@utils.minimum_version('1.25')
def secrets(self, filters=None):
"""
List secrets
Args:
filters (dict): A map of filters to process on the secrets
list. Available filters: ``names``
Returns (list): A list of secrets
"""
url = self._url('/secrets')
params = {}
if filters:
params['filters'] = utils.convert_filters(filters)
return self._result(self._get(url, params=params), True)
================================================
FILE: docker/api/service.py
================================================
from .. import auth, errors, utils
from ..types import ServiceMode
def _check_api_features(version, task_template, update_config, endpoint_spec,
rollback_config):
def raise_version_error(param, min_version):
raise errors.InvalidVersion(
f'{param} is not supported in API version < {min_version}'
)
if update_config is not None:
if utils.version_lt(version, '1.25'):
if 'MaxFailureRatio' in update_config:
raise_version_error('UpdateConfig.max_failure_ratio', '1.25')
if 'Monitor' in update_config:
raise_version_error('UpdateConfig.monitor', '1.25')
if utils.version_lt(version, '1.28'):
if update_config.get('FailureAction') == 'rollback':
raise_version_error(
'UpdateConfig.failure_action rollback', '1.28'
)
if utils.version_lt(version, '1.29'):
if 'Order' in update_config:
raise_version_error('UpdateConfig.order', '1.29')
if rollback_config is not None:
if utils.version_lt(version, '1.28'):
raise_version_error('rollback_config', '1.28')
if utils.version_lt(version, '1.29'):
if 'Order' in update_config:
raise_version_error('RollbackConfig.order', '1.29')
if endpoint_spec is not None:
if utils.version_lt(version, '1.32') and 'Ports' in endpoint_spec:
if any(p.get('PublishMode') for p in endpoint_spec['Ports']):
raise_version_error('EndpointSpec.Ports[].mode', '1.32')
if task_template is not None:
if 'ForceUpdate' in task_template and utils.version_lt(
version, '1.25'):
raise_version_error('force_update', '1.25')
if task_template.get('Placement'):
if utils.version_lt(version, '1.30'):
if task_template['Placement'].get('Platforms'):
raise_version_error('Placement.platforms', '1.30')
if utils.version_lt(version, '1.27'):
if task_template['Placement'].get('Preferences'):
raise_version_error('Placement.preferences', '1.27')
if task_template.get('ContainerSpec'):
container_spec = task_template.get('ContainerSpec')
if utils.version_lt(version, '1.25'):
if container_spec.get('TTY'):
raise_version_error('ContainerSpec.tty', '1.25')
if container_spec.get('Hostname') is not None:
raise_version_error('ContainerSpec.hostname', '1.25')
if container_spec.get('Hosts') is not None:
raise_version_error('ContainerSpec.hosts', '1.25')
if container_spec.get('Groups') is not None:
raise_version_error('ContainerSpec.groups', '1.25')
if container_spec.get('DNSConfig') is not None:
raise_version_error('ContainerSpec.dns_config', '1.25')
if container_spec.get('Healthcheck') is not None:
raise_version_error('ContainerSpec.healthcheck', '1.25')
if utils.version_lt(version, '1.28'):
if container_spec.get('ReadOnly') is not None:
raise_version_error('ContainerSpec.dns_config', '1.28')
if container_spec.get('StopSignal') is not None:
raise_version_error('ContainerSpec.stop_signal', '1.28')
if utils.version_lt(version, '1.30'):
if container_spec.get('Configs') is not None:
raise_version_error('ContainerSpec.configs', '1.30')
if container_spec.get('Privileges') is not None:
raise_version_error('ContainerSpec.privileges', '1.30')
if utils.version_lt(version, '1.35'):
if container_spec.get('Isolation') is not None:
raise_version_error('ContainerSpec.isolation', '1.35')
if utils.version_lt(version, '1.38'):
if container_spec.get('Init') is not None:
raise_version_error('ContainerSpec.init', '1.38')
if task_template.get('Resources'):
if utils.version_lt(version, '1.32'):
if task_template['Resources'].get('GenericResources'):
raise_version_error('Resources.generic_resources', '1.32')
def _merge_task_template(current, override):
merged = current.copy()
if override is not None:
for ts_key, ts_value in override.items():
if ts_key == 'ContainerSpec':
if 'ContainerSpec' not in merged:
merged['ContainerSpec'] = {}
for cs_key, cs_value in override['ContainerSpec'].items():
if cs_value is not None:
merged['ContainerSpec'][cs_key] = cs_value
elif ts_value is not None:
merged[ts_key] = ts_value
return merged
class ServiceApiMixin:
@utils.minimum_version('1.24')
def create_service(
self, task_template, name=None, labels=None, mode=None,
update_config=None, networks=None, endpoint_config=None,
endpoint_spec=None, rollback_config=None
):
"""
Create a service.
Args:
task_template (TaskTemplate): Specification of the task to start as
part of the new service.
name (string): User-defined name for the service. Optional.
labels (dict): A map of labels to associate with the service.
Optional.
mode (ServiceMode): Scheduling mode for the service (replicated
or global). Defaults to replicated.
update_config (UpdateConfig): Specification for the update strategy
of the service. Default: ``None``
rollback_config (RollbackConfig): Specification for the rollback
strategy of the service. Default: ``None``
networks (:py:class:`list`): List of network names or IDs or
:py:class:`~docker.types.NetworkAttachmentConfig` to attach the
service to. Default: ``None``.
endpoint_spec (EndpointSpec): Properties that can be configured to
access and load balance a service. Default: ``None``.
Returns:
A dictionary containing an ``ID`` key for the newly created
service.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
_check_api_features(
self._version, task_template, update_config, endpoint_spec,
rollback_config
)
url = self._url('/services/create')
headers = {}
image = task_template.get('ContainerSpec', {}).get('Image', None)
if image is None:
raise errors.DockerException(
'Missing mandatory Image key in ContainerSpec'
)
if mode and not isinstance(mode, dict):
mode = ServiceMode(mode)
registry, repo_name = auth.resolve_repository_name(image)
auth_header = auth.get_config_header(self, registry)
if auth_header:
headers['X-Registry-Auth'] = auth_header
if utils.version_lt(self._version, '1.25'):
networks = networks or task_template.pop('Networks', None)
data = {
'Name': name,
'Labels': labels,
'TaskTemplate': task_template,
'Mode': mode,
'Networks': utils.convert_service_networks(networks),
'EndpointSpec': endpoint_spec
}
if update_config is not None:
data['UpdateConfig'] = update_config
if rollback_config is not None:
data['RollbackConfig'] = rollback_config
return self._result(
self._post_json(url, data=data, headers=headers), True
)
@utils.minimum_version('1.24')
@utils.check_resource('service')
def inspect_service(self, service, insert_defaults=None):
"""
Return information about a service.
Args:
service (str): Service name or ID.
insert_defaults (boolean): If true, default values will be merged
into the service inspect output.
Returns:
(dict): A dictionary of the server-side representation of the
service, including all relevant properties.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url('/services/{0}', service)
params = {}
if insert_defaults is not None:
if utils.version_lt(self._version, '1.29'):
raise errors.InvalidVersion(
'insert_defaults is not supported in API version < 1.29'
)
params['insertDefaults'] = insert_defaults
return self._result(self._get(url, params=params), True)
@utils.minimum_version('1.24')
@utils.check_resource('task')
def inspect_task(self, task):
"""
Retrieve information about a task.
Args:
task (str): Task ID
Returns:
(dict): Information about the task.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url('/tasks/{0}', task)
return self._result(self._get(url), True)
@utils.minimum_version('1.24')
@utils.check_resource('service')
def remove_service(self, service):
"""
Stop and remove a service.
Args:
service (str): Service name or ID
Returns:
``True`` if successful.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url('/services/{0}', service)
resp = self._delete(url)
self._raise_for_status(resp)
return True
@utils.minimum_version('1.24')
def services(self, filters=None, status=None):
"""
List services.
Args:
filters (dict): Filters to process on the nodes list. Valid
filters: ``id``, ``name`` , ``label`` and ``mode``.
Default: ``None``.
status (bool): Include the service task count of running and
desired tasks. Default: ``None``.
Returns:
A list of dictionaries containing data about each service.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {
'filters': utils.convert_filters(filters) if filters else None
}
if status is not None:
if utils.version_lt(self._version, '1.41'):
raise errors.InvalidVersion(
'status is not supported in API version < 1.41'
)
params['status'] = status
url = self._url('/services')
return self._result(self._get(url, params=params), True)
@utils.minimum_version('1.25')
@utils.check_resource('service')
def service_logs(self, service, details=False, follow=False, stdout=False,
stderr=False, since=0, timestamps=False, tail='all',
is_tty=None):
"""
Get log stream for a service.
Note: This endpoint works only for services with the ``json-file``
or ``journald`` logging drivers.
Args:
service (str): ID or name of the service
details (bool): Show extra details provided to logs.
Default: ``False``
follow (bool): Keep connection open to read logs as they are
sent by the Engine. Default: ``False``
stdout (bool): Return logs from ``stdout``. Default: ``False``
stderr (bool): Return logs from ``stderr``. Default: ``False``
since (int): UNIX timestamp for the logs staring point.
Default: 0
timestamps (bool): Add timestamps to every log line.
tail (string or int): Number of log lines to be returned,
counting from the current end of the logs. Specify an
integer or ``'all'`` to output all log lines.
Default: ``all``
is_tty (bool): Whether the service's :py:class:`ContainerSpec`
enables the TTY option. If omitted, the method will query
the Engine for the information, causing an additional
roundtrip.
Returns (generator): Logs for the service.
"""
params = {
'details': details,
'follow': follow,
'stdout': stdout,
'stderr': stderr,
'since': since,
'timestamps': timestamps,
'tail': tail
}
url = self._url('/services/{0}/logs', service)
res = self._get(url, params=params, stream=True)
if is_tty is None:
is_tty = self.inspect_service(
service
)['Spec']['TaskTemplate']['ContainerSpec'].get('TTY', False)
return self._get_result_tty(True, res, is_tty)
@utils.minimum_version('1.24')
def tasks(self, filters=None):
"""
Retrieve a list of tasks.
Args:
filters (dict): A map of filters to process on the tasks list.
Valid filters: ``id``, ``name``, ``service``, ``node``,
``label`` and ``desired-state``.
Returns:
(:py:class:`list`): List of task dictionaries.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
params = {
'filters': utils.convert_filters(filters) if filters else None
}
url = self._url('/tasks')
return self._result(self._get(url, params=params), True)
@utils.minimum_version('1.24')
@utils.check_resource('service')
def update_service(self, service, version, task_template=None, name=None,
labels=None, mode=None, update_config=None,
networks=None, endpoint_config=None,
endpoint_spec=None, fetch_current_spec=False,
rollback_config=None):
"""
Update a service.
Args:
service (string): A service identifier (either its name or service
ID).
version (int): The version number of the service object being
updated. This is required to avoid conflicting writes.
task_template (TaskTemplate): Specification of the updated task to
start as part of the service.
name (string): New name for the service. Optional.
labels (dict): A map of labels to associate with the service.
Optional.
mode (ServiceMode): Scheduling mode for the service (replicated
or global). Defaults to replicated.
update_config (UpdateConfig): Specification for the update strategy
of the service. Default: ``None``.
rollback_config (RollbackConfig): Specification for the rollback
strategy of the service. Default: ``None``
networks (:py:class:`list`): List of network names or IDs or
:py:class:`~docker.types.NetworkAttachmentConfig` to attach the
service to. Default: ``None``.
endpoint_spec (EndpointSpec): Properties that can be configured to
access and load balance a service. Default: ``None``.
fetch_current_spec (boolean): Use the undefined settings from the
current specification of the service. Default: ``False``
Returns:
A dictionary containing a ``Warnings`` key.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
_check_api_features(
self._version, task_template, update_config, endpoint_spec,
rollback_config
)
if fetch_current_spec:
inspect_defaults = True
if utils.version_lt(self._version, '1.29'):
inspect_defaults = None
current = self.inspect_service(
service, insert_defaults=inspect_defaults
)['Spec']
else:
current = {}
url = self._url('/services/{0}/update', service)
data = {}
headers = {}
data['Name'] = current.get('Name') if name is None else name
data['Labels'] = current.get('Labels') if labels is None else labels
if mode is not None:
if not isinstance(mode, dict):
mode = ServiceMode(mode)
data['Mode'] = mode
else:
data['Mode'] = current.get('Mode')
data['TaskTemplate'] = _merge_task_template(
current.get('TaskTemplate', {}), task_template
)
container_spec = data['TaskTemplate'].get('ContainerSpec', {})
image = container_spec.get('Image', None)
if image is not None:
registry, repo_name = auth.resolve_repository_name(image)
auth_header = auth.get_config_header(self, registry)
if auth_header:
headers['X-Registry-Auth'] = auth_header
if update_config is not None:
data['UpdateConfig'] = update_config
else:
data['UpdateConfig'] = current.get('UpdateConfig')
if rollback_config is not None:
data['RollbackConfig'] = rollback_config
else:
data['RollbackConfig'] = current.get('RollbackConfig')
if networks is not None:
converted_networks = utils.convert_service_networks(networks)
if utils.version_lt(self._version, '1.25'):
data['Networks'] = converted_networks
else:
data['TaskTemplate']['Networks'] = converted_networks
elif utils.version_lt(self._version, '1.25'):
data['Networks'] = current.get('Networks')
elif data['TaskTemplate'].get('Networks') is None:
current_task_template = current.get('TaskTemplate', {})
current_networks = current_task_template.get('Networks')
if current_networks is None:
current_networks = current.get('Networks')
if current_networks is not None:
data['TaskTemplate']['Networks'] = current_networks
if endpoint_spec is not None:
data['EndpointSpec'] = endpoint_spec
else:
data['EndpointSpec'] = current.get('EndpointSpec')
resp = self._post_json(
url, data=data, params={'version': version}, headers=headers
)
return self._result(resp, json=True)
================================================
FILE: docker/api/swarm.py
================================================
import http.client as http_client
import logging
from .. import errors, types, utils
from ..constants import DEFAULT_SWARM_ADDR_POOL, DEFAULT_SWARM_SUBNET_SIZE
log = logging.getLogger(__name__)
class SwarmApiMixin:
def create_swarm_spec(self, *args, **kwargs):
"""
Create a :py:class:`docker.types.SwarmSpec` instance that can be used
as the ``swarm_spec`` argument in
:py:meth:`~docker.api.swarm.SwarmApiMixin.init_swarm`.
Args:
task_history_retention_limit (int): Maximum number of tasks
history stored.
snapshot_interval (int): Number of logs entries between snapshot.
keep_old_snapshots (int): Number of snapshots to keep beyond the
current snapshot.
log_entries_for_slow_followers (int): Number of log entries to
keep around to sync up slow followers after a snapshot is
created.
heartbeat_tick (int): Amount of ticks (in seconds) between each
heartbeat.
election_tick (int): Amount of ticks (in seconds) needed without a
leader to trigger a new election.
dispatcher_heartbeat_period (int): The delay for an agent to send
a heartbeat to the dispatcher.
node_cert_expiry (int): Automatic expiry for nodes certificates.
external_cas (:py:class:`list`): Configuration for forwarding
signing requests to an external certificate authority. Use
a list of :py:class:`docker.types.SwarmExternalCA`.
name (string): Swarm's name
labels (dict): User-defined key/value metadata.
signing_ca_cert (str): The desired signing CA certificate for all
swarm node TLS leaf certificates, in PEM format.
signing_ca_key (str): The desired signing CA key for all swarm
node TLS leaf certificates, in PEM format.
ca_force_rotate (int): An integer whose purpose is to force swarm
to gener
gitextract_9q1ur1_6/ ├── .coveragerc ├── .dockerignore ├── .editorconfig ├── .github/ │ └── workflows/ │ ├── ci.yml │ └── release.yml ├── .gitignore ├── .readthedocs.yml ├── CONTRIBUTING.md ├── Dockerfile ├── Dockerfile-docs ├── LICENSE ├── MAINTAINERS ├── Makefile ├── README.md ├── docker/ │ ├── __init__.py │ ├── api/ │ │ ├── __init__.py │ │ ├── build.py │ │ ├── client.py │ │ ├── config.py │ │ ├── container.py │ │ ├── daemon.py │ │ ├── exec_api.py │ │ ├── image.py │ │ ├── network.py │ │ ├── plugin.py │ │ ├── secret.py │ │ ├── service.py │ │ ├── swarm.py │ │ └── volume.py │ ├── auth.py │ ├── client.py │ ├── constants.py │ ├── context/ │ │ ├── __init__.py │ │ ├── api.py │ │ ├── config.py │ │ └── context.py │ ├── credentials/ │ │ ├── __init__.py │ │ ├── constants.py │ │ ├── errors.py │ │ ├── store.py │ │ └── utils.py │ ├── errors.py │ ├── models/ │ │ ├── __init__.py │ │ ├── configs.py │ │ ├── containers.py │ │ ├── images.py │ │ ├── networks.py │ │ ├── nodes.py │ │ ├── plugins.py │ │ ├── resource.py │ │ ├── secrets.py │ │ ├── services.py │ │ ├── swarm.py │ │ └── volumes.py │ ├── tls.py │ ├── transport/ │ │ ├── __init__.py │ │ ├── basehttpadapter.py │ │ ├── npipeconn.py │ │ ├── npipesocket.py │ │ ├── sshconn.py │ │ └── unixconn.py │ ├── types/ │ │ ├── __init__.py │ │ ├── base.py │ │ ├── containers.py │ │ ├── daemon.py │ │ ├── healthcheck.py │ │ ├── networks.py │ │ ├── services.py │ │ └── swarm.py │ ├── utils/ │ │ ├── __init__.py │ │ ├── build.py │ │ ├── config.py │ │ ├── decorators.py │ │ ├── fnmatch.py │ │ ├── json_stream.py │ │ ├── ports.py │ │ ├── proxy.py │ │ ├── socket.py │ │ └── utils.py │ └── version.py ├── docs/ │ ├── _static/ │ │ └── custom.css │ ├── _templates/ │ │ └── page.html │ ├── api.rst │ ├── change-log.md │ ├── client.rst │ ├── conf.py │ ├── configs.rst │ ├── containers.rst │ ├── images.rst │ ├── index.rst │ ├── networks.rst │ ├── nodes.rst │ ├── plugins.rst │ ├── secrets.rst │ ├── services.rst │ ├── swarm.rst │ ├── tls.rst │ ├── user_guides/ │ │ ├── index.rst │ │ ├── multiplex.rst │ │ └── swarm_services.md │ └── volumes.rst ├── pyproject.toml ├── pytest.ini ├── scripts/ │ ├── release.sh │ └── versions.py ├── tests/ │ ├── Dockerfile │ ├── Dockerfile-dind-certs │ ├── Dockerfile-ssh-dind │ ├── __init__.py │ ├── gpg-keys/ │ │ ├── ownertrust │ │ └── secret │ ├── helpers.py │ ├── integration/ │ │ ├── __init__.py │ │ ├── api_build_test.py │ │ ├── api_client_test.py │ │ ├── api_config_test.py │ │ ├── api_container_test.py │ │ ├── api_exec_test.py │ │ ├── api_healthcheck_test.py │ │ ├── api_image_test.py │ │ ├── api_network_test.py │ │ ├── api_plugin_test.py │ │ ├── api_secret_test.py │ │ ├── api_service_test.py │ │ ├── api_swarm_test.py │ │ ├── api_volume_test.py │ │ ├── base.py │ │ ├── client_test.py │ │ ├── conftest.py │ │ ├── context_api_test.py │ │ ├── credentials/ │ │ │ ├── __init__.py │ │ │ ├── create_gpg_key.sh │ │ │ ├── store_test.py │ │ │ └── utils_test.py │ │ ├── errors_test.py │ │ ├── models_containers_test.py │ │ ├── models_images_test.py │ │ ├── models_networks_test.py │ │ ├── models_nodes_test.py │ │ ├── models_resources_test.py │ │ ├── models_services_test.py │ │ ├── models_swarm_test.py │ │ ├── models_volumes_test.py │ │ ├── regression_test.py │ │ └── testdata/ │ │ └── dummy-plugin/ │ │ ├── config.json │ │ └── rootfs/ │ │ └── dummy/ │ │ └── file.txt │ ├── ssh/ │ │ ├── __init__.py │ │ ├── api_build_test.py │ │ ├── base.py │ │ ├── config/ │ │ │ ├── client/ │ │ │ │ ├── id_rsa │ │ │ │ └── id_rsa.pub │ │ │ └── server/ │ │ │ ├── known_ed25519 │ │ │ ├── known_ed25519.pub │ │ │ ├── sshd_config │ │ │ ├── unknown_ed25519 │ │ │ └── unknown_ed25519.pub │ │ └── connect_test.py │ └── unit/ │ ├── __init__.py │ ├── api_build_test.py │ ├── api_container_test.py │ ├── api_exec_test.py │ ├── api_image_test.py │ ├── api_network_test.py │ ├── api_test.py │ ├── api_volume_test.py │ ├── auth_test.py │ ├── client_test.py │ ├── context_test.py │ ├── dockertypes_test.py │ ├── errors_test.py │ ├── fake_api.py │ ├── fake_api_client.py │ ├── fake_stat.py │ ├── models_configs_test.py │ ├── models_containers_test.py │ ├── models_images_test.py │ ├── models_networks_test.py │ ├── models_resources_test.py │ ├── models_secrets_test.py │ ├── models_services_test.py │ ├── sshadapter_test.py │ ├── swarm_test.py │ ├── testdata/ │ │ └── certs/ │ │ ├── ca.pem │ │ ├── cert.pem │ │ └── key.pem │ ├── types_containers_test.py │ ├── utils_build_test.py │ ├── utils_config_test.py │ ├── utils_json_stream_test.py │ ├── utils_proxy_test.py │ └── utils_test.py └── tox.ini
SYMBOL INDEX (2084 symbols across 118 files)
FILE: docker/api/build.py
class BuildApiMixin (line 11) | class BuildApiMixin:
method build (line 12) | def build(self, path=None, tag=None, quiet=False, fileobj=None,
method prune_builds (line 278) | def prune_builds(self, filters=None, keep_storage=None, all=None):
method _set_auth_headers (line 321) | def _set_auth_headers(self, headers):
function process_dockerfile (line 355) | def process_dockerfile(dockerfile, path):
FILE: docker/api/client.py
class APIClient (line 57) | class APIClient(
method __init__ (line 115) | def __init__(self, base_url=None, version=None,
method _retrieve_server_version (line 221) | def _retrieve_server_version(self):
method _set_request_timeout (line 234) | def _set_request_timeout(self, kwargs):
method _post (line 241) | def _post(self, url, **kwargs):
method _get (line 245) | def _get(self, url, **kwargs):
method _put (line 249) | def _put(self, url, **kwargs):
method _delete (line 253) | def _delete(self, url, **kwargs):
method _url (line 256) | def _url(self, pathfmt, *args, **kwargs):
method _raise_for_status (line 272) | def _raise_for_status(self, response):
method _result (line 279) | def _result(self, response, json=False, binary=False):
method _post_json (line 289) | def _post_json(self, url, data, **kwargs):
method _attach_params (line 305) | def _attach_params(self, override=None):
method _attach_websocket (line 313) | def _attach_websocket(self, container, params=None):
method _create_websocket_connection (line 321) | def _create_websocket_connection(self, url):
method _get_raw_response_socket (line 333) | def _get_raw_response_socket(self, response):
method _stream_helper (line 355) | def _stream_helper(self, response, decode=False):
method _multiplexed_buffer_helper (line 376) | def _multiplexed_buffer_helper(self, response):
method _multiplexed_response_stream_helper (line 392) | def _multiplexed_response_stream_helper(self, response):
method _stream_raw_result (line 413) | def _stream_raw_result(self, response, chunk_size=1, decode=True):
method _read_from_socket (line 424) | def _read_from_socket(self, response, stream, tty=True, demux=False):
method _disable_socket_timeout (line 449) | def _disable_socket_timeout(self, socket):
method _check_is_tty (line 478) | def _check_is_tty(self, container):
method _get_result (line 482) | def _get_result(self, container, stream, res):
method _get_result_tty (line 485) | def _get_result_tty(self, stream, res, is_tty):
method _unmount (line 501) | def _unmount(self, *args):
method get_adapter (line 505) | def get_adapter(self, url):
method api_version (line 515) | def api_version(self):
method reload_config (line 518) | def reload_config(self, dockercfg_path=None):
FILE: docker/api/config.py
class ConfigApiMixin (line 6) | class ConfigApiMixin:
method create_config (line 8) | def create_config(self, name, data, labels=None, templating=None):
method inspect_config (line 41) | def inspect_config(self, id):
method remove_config (line 59) | def remove_config(self, id):
method configs (line 78) | def configs(self, filters=None):
FILE: docker/api/container.py
class ContainerApiMixin (line 14) | class ContainerApiMixin:
method attach (line 16) | def attach(self, container, stdout=True, stderr=True,
method attach_socket (line 70) | def attach_socket(self, container, params=None, ws=False):
method commit (line 115) | def commit(self, container, repository=None, tag=None, message=None,
method containers (line 152) | def containers(self, quiet=False, all=False, trunc=False, latest=False,
method create_container (line 221) | def create_container(self, image, command=None, hostname=None, user=None,
method create_container_config (line 442) | def create_container_config(self, *args, **kwargs):
method create_container_from_config (line 445) | def create_container_from_config(self, config, name=None, platform=None):
method create_host_config (line 459) | def create_host_config(self, *args, **kwargs):
method create_networking_config (line 619) | def create_networking_config(self, *args, **kwargs):
method create_endpoint_config (line 645) | def create_endpoint_config(self, *args, **kwargs):
method diff (line 682) | def diff(self, container):
method export (line 702) | def export(self, container, chunk_size=DEFAULT_DATA_CHUNK_SIZE):
method get_archive (line 725) | def get_archive(self, container, path, chunk_size=DEFAULT_DATA_CHUNK_S...
method inspect_container (line 778) | def inspect_container(self, container):
method kill (line 798) | def kill(self, container, signal=None):
method logs (line 821) | def logs(self, container, stdout=True, stderr=True, stream=False,
method pause (line 904) | def pause(self, container):
method port (line 920) | def port(self, container, private_port):
method put_archive (line 970) | def put_archive(self, container, path, data):
method prune_containers (line 995) | def prune_containers(self, filters=None):
method remove_container (line 1017) | def remove_container(self, container, v=False, link=False, force=False):
method rename (line 1040) | def rename(self, container, name):
method resize (line 1058) | def resize(self, container, height, width):
method restart (line 1077) | def restart(self, container, timeout=10):
method start (line 1101) | def start(self, container, *args, **kwargs):
method stats (line 1139) | def stats(self, container, decode=None, stream=True, one_shot=None):
method stop (line 1187) | def stop(self, container, timeout=None):
method top (line 1215) | def top(self, container, ps_args=None):
method unpause (line 1237) | def unpause(self, container):
method update_container (line 1250) | def update_container(
method wait (line 1315) | def wait(self, container, timeout=None, condition=None):
FILE: docker/api/daemon.py
class DaemonApiMixin (line 7) | class DaemonApiMixin:
method df (line 9) | def df(self):
method events (line 24) | def events(self, since=None, until=None, filters=None, decode=None):
method info (line 83) | def info(self):
method login (line 97) | def login(self, username, password=None, email=None, registry=None,
method ping (line 154) | def ping(self):
method version (line 168) | def version(self, api_version=True):
FILE: docker/api/exec_api.py
class ExecApiMixin (line 5) | class ExecApiMixin:
method exec_create (line 7) | def exec_create(self, container, cmd, stdout=True, stderr=True,
method exec_inspect (line 80) | def exec_inspect(self, exec_id):
method exec_resize (line 99) | def exec_resize(self, exec_id, height=None, width=None):
method exec_start (line 118) | def exec_start(self, exec_id, detach=False, tty=False, stream=False,
FILE: docker/api/image.py
class ImageApiMixin (line 10) | class ImageApiMixin:
method get_image (line 13) | def get_image(self, image, chunk_size=DEFAULT_DATA_CHUNK_SIZE):
method history (line 42) | def history(self, image):
method images (line 59) | def images(self, name=None, quiet=False, all=False, filters=None):
method import_image (line 102) | def import_image(self, src=None, repository=None, tag=None, image=None,
method import_image_from_data (line 154) | def import_image_from_data(self, data, repository=None, tag=None,
method import_image_from_file (line 177) | def import_image_from_file(self, filename, repository=None, tag=None,
method import_image_from_stream (line 196) | def import_image_from_stream(self, stream, repository=None, tag=None,
method import_image_from_url (line 203) | def import_image_from_url(self, url, repository=None, tag=None,
method import_image_from_image (line 218) | def import_image_from_image(self, image, repository=None, tag=None,
method inspect_image (line 235) | def inspect_image(self, image):
method inspect_distribution (line 257) | def inspect_distribution(self, image, auth_config=None):
method load_image (line 291) | def load_image(self, data, quiet=None):
method prune_images (line 327) | def prune_images(self, filters=None):
method pull (line 351) | def pull(self, repository, tag=None, stream=False, auth_config=None,
method push (line 436) | def push(self, repository, tag=None, stream=False, auth_config=None,
method remove_image (line 503) | def remove_image(self, image, force=False, noprune=False):
method search (line 516) | def search(self, term, limit=None):
method tag (line 542) | def tag(self, image, repository, tag=None, force=False):
function is_file (line 575) | def is_file(src):
function _import_image_params (line 585) | def _import_image_params(repo, tag, image=None, src=None,
FILE: docker/api/network.py
class NetworkApiMixin (line 6) | class NetworkApiMixin:
method networks (line 7) | def networks(self, names=None, ids=None, filters=None):
method create_network (line 40) | def create_network(self, name, driver=None, options=None, ipam=None,
method prune_networks (line 155) | def prune_networks(self, filters=None):
method remove_network (line 177) | def remove_network(self, net_id):
method inspect_network (line 189) | def inspect_network(self, net_id, verbose=None, scope=None):
method connect_container_to_network (line 215) | def connect_container_to_network(self, container, net_id,
method disconnect_container_from_network (line 256) | def disconnect_container_from_network(self, container, net_id,
FILE: docker/api/plugin.py
class PluginApiMixin (line 4) | class PluginApiMixin:
method configure_plugin (line 7) | def configure_plugin(self, name, options):
method create_plugin (line 28) | def create_plugin(self, name, plugin_data_dir, gzip=False):
method disable_plugin (line 54) | def disable_plugin(self, name, force=False):
method enable_plugin (line 72) | def enable_plugin(self, name, timeout=0):
method inspect_plugin (line 91) | def inspect_plugin(self, name):
method pull_plugin (line 106) | def pull_plugin(self, remote, privileges, name=None):
method plugins (line 144) | def plugins(self):
method plugin_privileges (line 155) | def plugin_privileges(self, name):
method push_plugin (line 185) | def push_plugin(self, name):
method remove_plugin (line 209) | def remove_plugin(self, name, force=False):
method upgrade_plugin (line 229) | def upgrade_plugin(self, name, remote, privileges):
FILE: docker/api/secret.py
class SecretApiMixin (line 6) | class SecretApiMixin:
method create_secret (line 8) | def create_secret(self, name, data, labels=None, driver=None):
method inspect_secret (line 47) | def inspect_secret(self, id):
method remove_secret (line 65) | def remove_secret(self, id):
method secrets (line 84) | def secrets(self, filters=None):
FILE: docker/api/service.py
function _check_api_features (line 5) | def _check_api_features(version, task_template, update_config, endpoint_...
function _merge_task_template (line 99) | def _merge_task_template(current, override):
class ServiceApiMixin (line 114) | class ServiceApiMixin:
method create_service (line 116) | def create_service(
method inspect_service (line 193) | def inspect_service(self, service, insert_defaults=None):
method inspect_task (line 223) | def inspect_task(self, task):
method remove_service (line 242) | def remove_service(self, service):
method services (line 263) | def services(self, filters=None, status=None):
method service_logs (line 295) | def service_logs(self, service, details=False, follow=False, stdout=Fa...
method tasks (line 344) | def tasks(self, filters=None):
method update_service (line 369) | def update_service(self, service, version, task_template=None, name=None,
FILE: docker/api/swarm.py
class SwarmApiMixin (line 10) | class SwarmApiMixin:
method create_swarm_spec (line 12) | def create_swarm_spec(self, *args, **kwargs):
method get_unlock_key (line 74) | def get_unlock_key(self):
method init_swarm (line 84) | def init_swarm(self, advertise_addr=None, listen_addr='0.0.0.0:2377',
method inspect_swarm (line 183) | def inspect_swarm(self):
method inspect_node (line 199) | def inspect_node(self, node_id):
method join_swarm (line 217) | def join_swarm(self, remote_addrs, join_token, listen_addr='0.0.0.0:23...
method leave_swarm (line 268) | def leave_swarm(self, force=False):
method nodes (line 296) | def nodes(self, filters=None):
method remove_node (line 321) | def remove_node(self, node_id, force=False):
method unlock_swarm (line 347) | def unlock_swarm(self, key):
method update_node (line 383) | def update_node(self, node_id, version, node_spec=None):
method update_swarm (line 419) | def update_swarm(self, version, swarm_spec=None,
FILE: docker/api/volume.py
class VolumeApiMixin (line 4) | class VolumeApiMixin:
method volumes (line 5) | def volumes(self, filters=None):
method create_volume (line 38) | def create_volume(self, name=None, driver=None, driver_opts=None,
method inspect_volume (line 93) | def inspect_volume(self, name):
method prune_volumes (line 119) | def prune_volumes(self, filters=None):
method remove_volume (line 140) | def remove_volume(self, name, force=False):
FILE: docker/auth.py
function resolve_repository_name (line 15) | def resolve_repository_name(repo_name):
function resolve_index_name (line 30) | def resolve_index_name(index_name):
function get_config_header (line 37) | def get_config_header(client, registry):
function split_repo_name (line 59) | def split_repo_name(repo_name):
function get_credential_store (line 69) | def get_credential_store(authconfig, registry):
class AuthConfig (line 75) | class AuthConfig(dict):
method __init__ (line 76) | def __init__(self, dct, credstore_env=None):
method parse_auth (line 84) | def parse_auth(cls, entries, raise_on_error=False):
method load_config (line 144) | def load_config(cls, config_path, config_dict, credstore_env=None):
method auths (line 192) | def auths(self):
method creds_store (line 196) | def creds_store(self):
method cred_helpers (line 200) | def cred_helpers(self):
method is_empty (line 204) | def is_empty(self):
method resolve_authconfig (line 209) | def resolve_authconfig(self, registry=None):
method _resolve_authconfig_credstore (line 244) | def _resolve_authconfig_credstore(self, registry, credstore_name):
method _get_store_instance (line 272) | def _get_store_instance(self, name):
method get_credential_store (line 279) | def get_credential_store(self, registry):
method get_all_credentials (line 285) | def get_all_credentials(self):
method add_auth (line 305) | def add_auth(self, reg, data):
function resolve_authconfig (line 309) | def resolve_authconfig(authconfig, registry=None, credstore_env=None):
function convert_to_hostname (line 315) | def convert_to_hostname(url):
function decode_auth (line 319) | def decode_auth(auth):
function encode_header (line 327) | def encode_header(auth):
function parse_auth (line 332) | def parse_auth(entries, raise_on_error=False):
function load_config (line 348) | def load_config(config_path=None, config_dict=None, credstore_env=None):
function _load_legacy_config (line 352) | def _load_legacy_config(config_file):
FILE: docker/client.py
class DockerClient (line 16) | class DockerClient:
method __init__ (line 44) | def __init__(self, *args, **kwargs):
method from_env (line 48) | def from_env(cls, **kwargs):
method configs (line 104) | def configs(self):
method containers (line 112) | def containers(self):
method images (line 120) | def images(self):
method networks (line 128) | def networks(self):
method nodes (line 136) | def nodes(self):
method plugins (line 144) | def plugins(self):
method secrets (line 152) | def secrets(self):
method services (line 160) | def services(self):
method swarm (line 168) | def swarm(self):
method volumes (line 176) | def volumes(self):
method events (line 184) | def events(self, *args, **kwargs):
method df (line 188) | def df(self):
method info (line 192) | def info(self, *args, **kwargs):
method login (line 196) | def login(self, *args, **kwargs):
method ping (line 200) | def ping(self, *args, **kwargs):
method version (line 204) | def version(self, *args, **kwargs):
method close (line 208) | def close(self):
method __getattr__ (line 212) | def __getattr__(self, name):
FILE: docker/context/api.py
class ContextAPI (line 15) | class ContextAPI:
method create_context (line 23) | def create_context(
method get_context (line 73) | def get_context(cls, name=None):
method contexts (line 101) | def contexts(cls):
method get_current_context (line 128) | def get_current_context(cls):
method set_current_context (line 136) | def set_current_context(cls, name="default"):
method remove_context (line 147) | def remove_context(cls, name):
method inspect_context (line 180) | def inspect_context(cls, name="default"):
FILE: docker/context/config.py
function get_current_context_name (line 12) | def get_current_context_name():
function write_context_name_to_docker_config (line 24) | def write_context_name_to_docker_config(name=None):
function get_context_id (line 49) | def get_context_id(name):
function get_context_dir (line 53) | def get_context_dir():
function get_meta_dir (line 57) | def get_meta_dir(name=None):
function get_meta_file (line 64) | def get_meta_file(name):
function get_tls_dir (line 68) | def get_tls_dir(name=None, endpoint=""):
function get_context_host (line 75) | def get_context_host(path=None, tls=False):
FILE: docker/context/context.py
class Context (line 16) | class Context:
method __init__ (line 19) | def __init__(self, name, orchestrator=None, host=None, endpoints=None,
method set_endpoint (line 62) | def set_endpoint(
method inspect (line 75) | def inspect(self):
method load_context (line 79) | def load_context(cls, name):
method _load_meta (line 93) | def _load_meta(cls, name):
method _load_certs (line 120) | def _load_certs(self):
method save (line 146) | def save(self):
method remove (line 173) | def remove(self):
method __repr__ (line 179) | def __repr__(self):
method __str__ (line 182) | def __str__(self):
method __call__ (line 185) | def __call__(self):
method is_docker_host (line 191) | def is_docker_host(self):
method Name (line 195) | def Name(self):
method Host (line 199) | def Host(self):
method Orchestrator (line 209) | def Orchestrator(self):
method Metadata (line 213) | def Metadata(self):
method TLSConfig (line 224) | def TLSConfig(self):
method TLSMaterial (line 233) | def TLSMaterial(self):
method Storage (line 244) | def Storage(self):
FILE: docker/credentials/errors.py
class StoreError (line 1) | class StoreError(RuntimeError):
class CredentialsNotFound (line 5) | class CredentialsNotFound(StoreError):
class InitializationError (line 9) | class InitializationError(StoreError):
function process_store_error (line 13) | def process_store_error(cpe, program):
FILE: docker/credentials/store.py
class Store (line 11) | class Store:
method __init__ (line 12) | def __init__(self, program, environment=None):
method get (line 26) | def get(self, server):
method store (line 46) | def store(self, server, username, secret):
method erase (line 57) | def erase(self, server):
method list (line 65) | def list(self):
method _execute (line 71) | def _execute(self, subcmd, data_input):
FILE: docker/credentials/utils.py
function create_environment_dict (line 4) | def create_environment_dict(overrides):
FILE: docker/errors.py
class DockerException (line 13) | class DockerException(Exception):
function create_api_error_from_http_exception (line 22) | def create_api_error_from_http_exception(e):
class APIError (line 42) | class APIError(requests.exceptions.HTTPError, DockerException):
method __init__ (line 46) | def __init__(self, message, response=None, explanation=None):
method __str__ (line 53) | def __str__(self):
method status_code (line 74) | def status_code(self):
method is_error (line 78) | def is_error(self):
method is_client_error (line 81) | def is_client_error(self):
method is_server_error (line 86) | def is_server_error(self):
class NotFound (line 92) | class NotFound(APIError):
class ImageNotFound (line 96) | class ImageNotFound(NotFound):
class InvalidVersion (line 100) | class InvalidVersion(DockerException):
class InvalidRepository (line 104) | class InvalidRepository(DockerException):
class InvalidConfigFile (line 108) | class InvalidConfigFile(DockerException):
class InvalidArgument (line 112) | class InvalidArgument(DockerException):
class DeprecatedMethod (line 116) | class DeprecatedMethod(DockerException):
class TLSParameterError (line 120) | class TLSParameterError(DockerException):
method __init__ (line 121) | def __init__(self, msg):
method __str__ (line 124) | def __str__(self):
class NullResource (line 131) | class NullResource(DockerException, ValueError):
class ContainerError (line 135) | class ContainerError(DockerException):
method __init__ (line 139) | def __init__(self, container, exit_status, command, image, stderr):
class StreamParseError (line 153) | class StreamParseError(RuntimeError):
method __init__ (line 154) | def __init__(self, reason):
class BuildError (line 158) | class BuildError(DockerException):
method __init__ (line 159) | def __init__(self, reason, build_log):
class ImageLoadError (line 165) | class ImageLoadError(DockerException):
function create_unexpected_kwargs_error (line 169) | def create_unexpected_kwargs_error(name, kwargs):
class MissingContextParameter (line 180) | class MissingContextParameter(DockerException):
method __init__ (line 181) | def __init__(self, param):
method __str__ (line 184) | def __str__(self):
class ContextAlreadyExists (line 188) | class ContextAlreadyExists(DockerException):
method __init__ (line 189) | def __init__(self, name):
method __str__ (line 192) | def __str__(self):
class ContextException (line 196) | class ContextException(DockerException):
method __init__ (line 197) | def __init__(self, msg):
method __str__ (line 200) | def __str__(self):
class ContextNotFound (line 204) | class ContextNotFound(DockerException):
method __init__ (line 205) | def __init__(self, name):
method __str__ (line 208) | def __str__(self):
FILE: docker/models/configs.py
class Config (line 5) | class Config(Model):
method __repr__ (line 9) | def __repr__(self):
method name (line 13) | def name(self):
method remove (line 16) | def remove(self):
class ConfigCollection (line 27) | class ConfigCollection(Collection):
method create (line 31) | def create(self, **kwargs):
method get (line 37) | def get(self, config_id):
method list (line 55) | def list(self, **kwargs):
FILE: docker/models/containers.py
class Container (line 20) | class Container(Model):
method name (line 29) | def name(self):
method image (line 37) | def image(self):
method labels (line 47) | def labels(self):
method status (line 61) | def status(self):
method health (line 70) | def health(self):
method ports (line 79) | def ports(self):
method attach (line 85) | def attach(self, **kwargs):
method attach_socket (line 111) | def attach_socket(self, **kwargs):
method commit (line 127) | def commit(self, repository=None, tag=None, **kwargs):
method diff (line 153) | def diff(self):
method exec_run (line 167) | def exec_run(self, cmd, stdout=True, stderr=True, stdin=False, tty=False,
method export (line 226) | def export(self, chunk_size=DEFAULT_DATA_CHUNK_SIZE):
method get_archive (line 244) | def get_archive(self, path, chunk_size=DEFAULT_DATA_CHUNK_SIZE,
method kill (line 280) | def kill(self, signal=None):
method logs (line 294) | def logs(self, **kwargs):
method pause (line 325) | def pause(self):
method put_archive (line 335) | def put_archive(self, path, data):
method remove (line 353) | def remove(self, **kwargs):
method rename (line 370) | def rename(self, name):
method resize (line 383) | def resize(self, height, width):
method restart (line 397) | def restart(self, **kwargs):
method start (line 412) | def start(self, **kwargs):
method stats (line 423) | def stats(self, **kwargs):
method stop (line 441) | def stop(self, **kwargs):
method top (line 455) | def top(self, **kwargs):
method unpause (line 471) | def unpause(self):
method update (line 481) | def update(self, **kwargs):
method wait (line 508) | def wait(self, **kwargs):
class ContainerCollection (line 532) | class ContainerCollection(Collection):
method run (line 535) | def run(self, image, command=None, stdout=True, stderr=False,
method create (line 914) | def create(self, image, command=None, **kwargs):
method get (line 939) | def get(self, container_id):
method list (line 958) | def list(self, all=False, before=None, filters=None, limit=-1, since=N...
method prune (line 1026) | def prune(self, filters=None):
function _create_container_args (line 1123) | def _create_container_args(kwargs):
function _host_volume_from_bind (line 1185) | def _host_volume_from_bind(bind):
FILE: docker/models/images.py
class Image (line 13) | class Image(Model):
method __repr__ (line 17) | def __repr__(self):
method labels (line 22) | def labels(self):
method short_id (line 30) | def short_id(self):
method tags (line 40) | def tags(self):
method history (line 49) | def history(self):
method remove (line 62) | def remove(self, force=False, noprune=False):
method save (line 80) | def save(self, chunk_size=DEFAULT_DATA_CHUNK_SIZE, named=False):
method tag (line 122) | def tag(self, repository, tag=None, **kwargs):
class RegistryData (line 142) | class RegistryData(Model):
method __init__ (line 146) | def __init__(self, image_name, *args, **kwargs):
method id (line 151) | def id(self):
method short_id (line 158) | def short_id(self):
method pull (line 165) | def pull(self, platform=None):
method has_platform (line 179) | def has_platform(self, platform):
method reload (line 211) | def reload(self):
class ImageCollection (line 217) | class ImageCollection(Collection):
method build (line 220) | def build(self, **kwargs):
method get (line 317) | def get(self, name):
method get_registry_data (line 335) | def get_registry_data(self, name, auth_config=None):
method list (line 359) | def list(self, name=None, all=False, filters=None):
method load (line 383) | def load(self, data):
method pull (line 415) | def pull(self, repository, tag=None, all_tags=False, **kwargs):
method push (line 477) | def push(self, repository, tag=None, **kwargs):
method remove (line 481) | def remove(self, *args, **kwargs):
method search (line 485) | def search(self, *args, **kwargs):
method prune (line 489) | def prune(self, filters=None):
method prune_builds (line 493) | def prune_builds(self, *args, **kwargs):
function normalize_platform (line 498) | def normalize_platform(platform, engine_info):
FILE: docker/models/networks.py
class Network (line 7) | class Network(Model):
method name (line 12) | def name(self):
method containers (line 19) | def containers(self):
method connect (line 29) | def connect(self, container, *args, **kwargs):
method disconnect (line 62) | def disconnect(self, container, *args, **kwargs):
method remove (line 83) | def remove(self):
class NetworkCollection (line 94) | class NetworkCollection(Collection):
method create (line 100) | def create(self, name, *args, **kwargs):
method get (line 159) | def get(self, network_id, *args, **kwargs):
method list (line 185) | def list(self, *args, **kwargs):
method prune (line 216) | def prune(self, filters=None):
FILE: docker/models/nodes.py
class Node (line 4) | class Node(Model):
method version (line 9) | def version(self):
method update (line 17) | def update(self, node_spec):
method remove (line 44) | def remove(self, force=False):
class NodeCollection (line 64) | class NodeCollection(Collection):
method get (line 68) | def get(self, node_id):
method list (line 84) | def list(self, *args, **kwargs):
FILE: docker/models/plugins.py
class Plugin (line 5) | class Plugin(Model):
method __repr__ (line 9) | def __repr__(self):
method name (line 13) | def name(self):
method enabled (line 20) | def enabled(self):
method settings (line 27) | def settings(self):
method configure (line 33) | def configure(self, options):
method disable (line 47) | def disable(self, force=False):
method enable (line 62) | def enable(self, timeout=0):
method push (line 76) | def push(self):
method remove (line 89) | def remove(self, force=False):
method upgrade (line 103) | def upgrade(self, remote=None):
class PluginCollection (line 131) | class PluginCollection(Collection):
method create (line 134) | def create(self, name, plugin_data_dir, gzip=False):
method get (line 152) | def get(self, name):
method install (line 170) | def install(self, remote_name, local_name=None):
method list (line 194) | def list(self):
FILE: docker/models/resource.py
class Model (line 1) | class Model:
method __init__ (line 7) | def __init__(self, attrs=None, client=None, collection=None):
method __repr__ (line 19) | def __repr__(self):
method __eq__ (line 22) | def __eq__(self, other):
method __hash__ (line 25) | def __hash__(self):
method id (line 29) | def id(self):
method short_id (line 36) | def short_id(self):
method reload (line 42) | def reload(self):
class Collection (line 51) | class Collection:
method __init__ (line 60) | def __init__(self, client=None):
method __call__ (line 65) | def __call__(self, *args, **kwargs):
method list (line 72) | def list(self):
method get (line 75) | def get(self, key):
method create (line 78) | def create(self, attrs=None):
method prepare_model (line 81) | def prepare_model(self, attrs):
FILE: docker/models/secrets.py
class Secret (line 5) | class Secret(Model):
method __repr__ (line 9) | def __repr__(self):
method name (line 13) | def name(self):
method remove (line 16) | def remove(self):
class SecretCollection (line 27) | class SecretCollection(Collection):
method create (line 31) | def create(self, **kwargs):
method get (line 37) | def get(self, secret_id):
method list (line 55) | def list(self, **kwargs):
FILE: docker/models/services.py
class Service (line 9) | class Service(Model):
method name (line 14) | def name(self):
method version (line 19) | def version(self):
method remove (line 27) | def remove(self):
method tasks (line 37) | def tasks(self, filters=None):
method update (line 58) | def update(self, **kwargs):
method logs (line 87) | def logs(self, **kwargs):
method scale (line 116) | def scale(self, replicas):
method force_update (line 135) | def force_update(self):
class ServiceCollection (line 146) | class ServiceCollection(Collection):
method create (line 150) | def create(self, image, command=None, **kwargs):
method get (line 238) | def get(self, service_id, insert_defaults=None):
method list (line 263) | def list(self, **kwargs):
function _get_create_service_kwargs (line 342) | def _get_create_service_kwargs(func_name, kwargs):
FILE: docker/models/swarm.py
class Swarm (line 7) | class Swarm(Model):
method __init__ (line 14) | def __init__(self, *args, **kwargs):
method version (line 25) | def version(self):
method get_unlock_key (line 33) | def get_unlock_key(self):
method init (line 37) | def init(self, advertise_addr=None, listen_addr='0.0.0.0:2377',
method join (line 136) | def join(self, *args, **kwargs):
method leave (line 140) | def leave(self, *args, **kwargs):
method reload (line 144) | def reload(self):
method unlock (line 155) | def unlock(self, key):
method update (line 159) | def update(self, rotate_worker_token=False, rotate_manager_token=False,
FILE: docker/models/volumes.py
class Volume (line 5) | class Volume(Model):
method name (line 10) | def name(self):
method remove (line 14) | def remove(self, force=False):
class VolumeCollection (line 28) | class VolumeCollection(Collection):
method create (line 32) | def create(self, name=None, **kwargs):
method get (line 60) | def get(self, volume_id):
method list (line 78) | def list(self, **kwargs):
method prune (line 97) | def prune(self, filters=None):
FILE: docker/tls.py
class TLSConfig (line 6) | class TLSConfig:
method __init__ (line 21) | def __init__(self, client_cert=None, ca_cert=None, verify=None):
method configure_client (line 57) | def configure_client(self, client):
FILE: docker/transport/basehttpadapter.py
class BaseHTTPAdapter (line 4) | class BaseHTTPAdapter(requests.adapters.HTTPAdapter):
method close (line 5) | def close(self):
method get_connection_with_tls_context (line 12) | def get_connection_with_tls_context(self, request, verify, proxies=Non...
FILE: docker/transport/npipeconn.py
class NpipeHTTPConnection (line 14) | class NpipeHTTPConnection(urllib3.connection.HTTPConnection):
method __init__ (line 15) | def __init__(self, npipe_path, timeout=60):
method connect (line 22) | def connect(self):
class NpipeHTTPConnectionPool (line 29) | class NpipeHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool):
method __init__ (line 30) | def __init__(self, npipe_path, timeout=60, maxsize=10):
method _new_conn (line 37) | def _new_conn(self):
method _get_conn (line 45) | def _get_conn(self, timeout):
class NpipeHTTPAdapter (line 64) | class NpipeHTTPAdapter(BaseHTTPAdapter):
method __init__ (line 71) | def __init__(self, base_url, timeout=60,
method get_connection (line 82) | def get_connection(self, url, proxies=None):
method request_url (line 96) | def request_url(self, request, proxies):
FILE: docker/transport/npipesocket.py
function check_closed (line 18) | def check_closed(f):
class NpipeSocket (line 29) | class NpipeSocket:
method __init__ (line 36) | def __init__(self, handle=None):
method accept (line 41) | def accept(self):
method bind (line 44) | def bind(self, address):
method close (line 47) | def close(self):
method connect (line 52) | def connect(self, address, retry_count=0):
method connect_ex (line 84) | def connect_ex(self, address):
method detach (line 88) | def detach(self):
method dup (line 93) | def dup(self):
method getpeername (line 96) | def getpeername(self):
method getsockname (line 99) | def getsockname(self):
method getsockopt (line 102) | def getsockopt(self, level, optname, buflen=None):
method ioctl (line 105) | def ioctl(self, control, option):
method listen (line 108) | def listen(self, backlog):
method makefile (line 111) | def makefile(self, mode=None, bufsize=None):
method recv (line 120) | def recv(self, bufsize, flags=0):
method recvfrom (line 125) | def recvfrom(self, bufsize, flags=0):
method recvfrom_into (line 130) | def recvfrom_into(self, buf, nbytes=0, flags=0):
method recv_into (line 134) | def recv_into(self, buf, nbytes=0):
method send (line 157) | def send(self, string, flags=0):
method sendall (line 172) | def sendall(self, string, flags=0):
method sendto (line 176) | def sendto(self, string, address):
method setblocking (line 180) | def setblocking(self, flag):
method settimeout (line 185) | def settimeout(self, value):
method gettimeout (line 195) | def gettimeout(self):
method setsockopt (line 198) | def setsockopt(self, level, optname, value):
method shutdown (line 202) | def shutdown(self, how):
class NpipeFileIOBase (line 206) | class NpipeFileIOBase(io.RawIOBase):
method __init__ (line 207) | def __init__(self, npipe_socket):
method close (line 210) | def close(self):
method fileno (line 214) | def fileno(self):
method isatty (line 217) | def isatty(self):
method readable (line 220) | def readable(self):
method readinto (line 223) | def readinto(self, buf):
method seekable (line 226) | def seekable(self):
method writable (line 229) | def writable(self):
FILE: docker/transport/sshconn.py
class SSHSocket (line 20) | class SSHSocket(socket.socket):
method __init__ (line 21) | def __init__(self, host):
method connect (line 34) | def connect(self, **kwargs):
method _write (line 63) | def _write(self, data):
method sendall (line 71) | def sendall(self, data):
method send (line 74) | def send(self, data):
method recv (line 77) | def recv(self, n):
method makefile (line 83) | def makefile(self, mode):
method close (line 90) | def close(self):
class SSHConnection (line 98) | class SSHConnection(urllib3.connection.HTTPConnection):
method __init__ (line 99) | def __init__(self, ssh_transport=None, timeout=60, host=None):
method connect (line 107) | def connect(self):
class SSHConnectionPool (line 120) | class SSHConnectionPool(urllib3.connectionpool.HTTPConnectionPool):
method __init__ (line 123) | def __init__(self, ssh_client=None, timeout=60, maxsize=10, host=None):
method _new_conn (line 133) | def _new_conn(self):
method _get_conn (line 139) | def _get_conn(self, timeout):
class SSHHTTPAdapter (line 159) | class SSHHTTPAdapter(BaseHTTPAdapter):
method __init__ (line 165) | def __init__(self, base_url, timeout=60,
method _create_paramiko_client (line 185) | def _create_paramiko_client(self, base_url):
method _connect (line 216) | def _connect(self):
method get_connection (line 220) | def get_connection(self, url, proxies=None):
method close (line 247) | def close(self):
FILE: docker/transport/unixconn.py
class UnixHTTPConnection (line 13) | class UnixHTTPConnection(urllib3.connection.HTTPConnection):
method __init__ (line 15) | def __init__(self, base_url, unix_socket, timeout=60):
method connect (line 23) | def connect(self):
class UnixHTTPConnectionPool (line 30) | class UnixHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool):
method __init__ (line 31) | def __init__(self, base_url, socket_path, timeout=60, maxsize=10):
method _new_conn (line 39) | def _new_conn(self):
class UnixHTTPAdapter (line 45) | class UnixHTTPAdapter(BaseHTTPAdapter):
method __init__ (line 52) | def __init__(self, socket_url, timeout=60,
method get_connection (line 66) | def get_connection(self, url, proxies=None):
method request_url (line 80) | def request_url(self, request, proxies):
FILE: docker/types/base.py
class DictType (line 1) | class DictType(dict):
method __init__ (line 2) | def __init__(self, init):
FILE: docker/types/containers.py
class LogConfigTypesEnum (line 19) | class LogConfigTypesEnum:
class LogConfig (line 31) | class LogConfig(DictType):
method __init__ (line 66) | def __init__(self, **kwargs):
method type (line 79) | def type(self):
method type (line 83) | def type(self, value):
method config (line 87) | def config(self):
method set_config_value (line 90) | def set_config_value(self, key, value):
method unset_config (line 96) | def unset_config(self, key):
class Ulimit (line 102) | class Ulimit(DictType):
method __init__ (line 125) | def __init__(self, **kwargs):
method name (line 142) | def name(self):
method name (line 146) | def name(self, value):
method soft (line 150) | def soft(self):
method soft (line 154) | def soft(self, value):
method hard (line 158) | def hard(self):
method hard (line 162) | def hard(self, value):
class DeviceRequest (line 166) | class DeviceRequest(DictType):
method __init__ (line 187) | def __init__(self, **kwargs):
method driver (line 224) | def driver(self):
method driver (line 228) | def driver(self, value):
method count (line 232) | def count(self):
method count (line 236) | def count(self, value):
method device_ids (line 240) | def device_ids(self):
method device_ids (line 244) | def device_ids(self, value):
method capabilities (line 248) | def capabilities(self):
method capabilities (line 252) | def capabilities(self, value):
method options (line 256) | def options(self):
method options (line 260) | def options(self, value):
class HostConfig (line 264) | class HostConfig(dict):
method __init__ (line 265) | def __init__(self, version, binds=None, port_bindings=None,
function host_config_type_error (line 665) | def host_config_type_error(param, param_value, expected):
function host_config_version_error (line 672) | def host_config_version_error(param, version, less_than=True):
function host_config_value_error (line 678) | def host_config_value_error(param, param_value):
function host_config_incompatible_error (line 682) | def host_config_incompatible_error(param, param_value, incompatible_param):
class ContainerConfig (line 688) | class ContainerConfig(dict):
method __init__ (line 689) | def __init__(
FILE: docker/types/daemon.py
class CancellableStream (line 8) | class CancellableStream:
method __init__ (line 20) | def __init__(self, stream, response):
method __iter__ (line 24) | def __iter__(self):
method __next__ (line 27) | def __next__(self):
method close (line 37) | def close(self):
FILE: docker/types/healthcheck.py
class Healthcheck (line 4) | class Healthcheck(DictType):
method __init__ (line 30) | def __init__(self, **kwargs):
method test (line 49) | def test(self):
method test (line 53) | def test(self, value):
method interval (line 59) | def interval(self):
method interval (line 63) | def interval(self, value):
method timeout (line 67) | def timeout(self):
method timeout (line 71) | def timeout(self, value):
method retries (line 75) | def retries(self):
method retries (line 79) | def retries(self, value):
method start_period (line 83) | def start_period(self):
method start_period (line 87) | def start_period(self, value):
FILE: docker/types/networks.py
class EndpointConfig (line 5) | class EndpointConfig(dict):
method __init__ (line 6) | def __init__(self, version, aliases=None, links=None, ipv4_address=None,
class NetworkingConfig (line 54) | class NetworkingConfig(dict):
method __init__ (line 55) | def __init__(self, endpoints_config=None):
class IPAMConfig (line 60) | class IPAMConfig(dict):
method __init__ (line 79) | def __init__(self, driver='default', pool_configs=None, options=None):
class IPAMPool (line 91) | class IPAMPool(dict):
method __init__ (line 121) | def __init__(self, subnet=None, iprange=None, gateway=None,
FILE: docker/types/services.py
class TaskTemplate (line 13) | class TaskTemplate(dict):
method __init__ (line 37) | def __init__(self, container_spec, resources=None, restart_policy=None,
method container_spec (line 60) | def container_spec(self):
method resources (line 64) | def resources(self):
method restart_policy (line 68) | def restart_policy(self):
method placement (line 72) | def placement(self):
class ContainerSpec (line 76) | class ContainerSpec(dict):
method __init__ (line 126) | def __init__(self, image, command=None, args=None, hostname=None, env=...
class Mount (line 221) | class Mount(dict):
method __init__ (line 250) | def __init__(self, target, source, type='volume', read_only=False,
method parse_mount_string (line 312) | def parse_mount_string(cls, string):
class Resources (line 336) | class Resources(dict):
method __init__ (line 353) | def __init__(self, cpu_limit=None, mem_limit=None, cpu_reservation=None,
function _convert_generic_resources_dict (line 375) | def _convert_generic_resources_dict(generic_resources):
class UpdateConfig (line 401) | class UpdateConfig(dict):
method __init__ (line 424) | def __init__(self, parallelism=0, delay=None, failure_action='continue',
class RollbackConfig (line 457) | class RollbackConfig(UpdateConfig):
class RestartConditionTypesEnum (line 482) | class RestartConditionTypesEnum:
class RestartPolicy (line 491) | class RestartPolicy(dict):
method __init__ (line 509) | def __init__(self, condition=RestartConditionTypesEnum.NONE, delay=0,
class DriverConfig (line 522) | class DriverConfig(dict):
method __init__ (line 536) | def __init__(self, name, options=None):
class EndpointSpec (line 542) | class EndpointSpec(dict):
method __init__ (line 558) | def __init__(self, mode=None, ports=None):
function convert_service_ports (line 565) | def convert_service_ports(ports):
class ServiceMode (line 598) | class ServiceMode(dict):
method __init__ (line 611) | def __init__(self, mode, replicas=None, concurrency=None):
method _convert_mode (line 646) | def _convert_mode(original_mode):
method replicas (line 656) | def replicas(self):
class SecretReference (line 666) | class SecretReference(dict):
method __init__ (line 682) | def __init__(self, secret_id, secret_name, filename=None, uid=None,
class ConfigReference (line 694) | class ConfigReference(dict):
method __init__ (line 710) | def __init__(self, config_id, config_name, filename=None, uid=None,
class Placement (line 722) | class Placement(dict):
method __init__ (line 738) | def __init__(self, constraints=None, preferences=None, platforms=None,
class PlacementPreference (line 758) | class PlacementPreference(dict):
method __init__ (line 771) | def __init__(self, strategy, descriptor):
class DNSConfig (line 780) | class DNSConfig(dict):
method __init__ (line 793) | def __init__(self, nameservers=None, search=None, options=None):
class Privileges (line 799) | class Privileges(dict):
method __init__ (line 824) | def __init__(self, credentialspec_file=None, credentialspec_registry=N...
class NetworkAttachmentConfig (line 854) | class NetworkAttachmentConfig(dict):
method __init__ (line 867) | def __init__(self, target, aliases=None, options=None):
FILE: docker/types/swarm.py
class SwarmSpec (line 5) | class SwarmSpec(dict):
method __init__ (line 11) | def __init__(self, version, task_history_retention_limit=None,
class SwarmExternalCA (line 97) | class SwarmExternalCA(dict):
method __init__ (line 115) | def __init__(self, url, protocol=None, options=None, ca_cert=None):
FILE: docker/utils/build.py
function match_tag (line 18) | def match_tag(tag: str) -> bool:
function tar (line 22) | def tar(path, exclude=None, dockerfile=None, fileobj=None, gzip=False):
function exclude_paths (line 41) | def exclude_paths(root, patterns, dockerfile=None):
function build_file_list (line 58) | def build_file_list(root):
function create_archive (line 70) | def create_archive(root, files=None, fileobj=None, gzip=False,
function mkbuildcontext (line 123) | def mkbuildcontext(dockerfile):
function split_path (line 142) | def split_path(p):
function normalize_slashes (line 146) | def normalize_slashes(p):
function walk (line 152) | def walk(root, patterns, default=True):
class PatternMatcher (line 159) | class PatternMatcher:
method __init__ (line 160) | def __init__(self, patterns):
method matches (line 166) | def matches(self, filepath):
method walk (line 185) | def walk(self, root):
class Pattern (line 222) | class Pattern:
method __init__ (line 223) | def __init__(self, pattern_str):
method normalize (line 233) | def normalize(cls, p):
method match (line 259) | def match(self, filepath):
FILE: docker/utils/config.py
function find_config_file (line 13) | def find_config_file(config_path=None):
function config_path_from_environment (line 33) | def config_path_from_environment():
function home_dir (line 40) | def home_dir():
function load_general_config (line 51) | def load_general_config(config_path=None):
FILE: docker/utils/decorators.py
function check_resource (line 7) | def check_resource(resource_name):
function minimum_version (line 24) | def minimum_version(version):
function update_headers (line 37) | def update_headers(f):
FILE: docker/utils/fnmatch.py
function _purge (line 21) | def _purge():
function fnmatch (line 26) | def fnmatch(name, pat):
function fnmatchcase (line 47) | def fnmatchcase(name, pat):
function translate (line 63) | def translate(pat):
FILE: docker/utils/json_stream.py
function stream_as_text (line 9) | def stream_as_text(stream):
function json_splitter (line 22) | def json_splitter(buffer):
function json_stream (line 35) | def json_stream(stream):
function line_splitter (line 43) | def line_splitter(buffer, separator='\n'):
function split_buffer (line 50) | def split_buffer(stream, splitter=None, decoder=lambda a: a):
FILE: docker/utils/ports.py
function add_port_mapping (line 15) | def add_port_mapping(port_bindings, internal_port, external):
function add_port (line 22) | def add_port(port_bindings, internal_port_range, external_range):
function build_port_bindings (line 32) | def build_port_bindings(ports):
function _raise_invalid_port (line 40) | def _raise_invalid_port(port):
function port_range (line 46) | def port_range(start, end, proto, randomly_available_port=False):
function split_port (line 56) | def split_port(port):
FILE: docker/utils/proxy.py
class ProxyConfig (line 4) | class ProxyConfig(dict):
method http (line 9) | def http(self):
method https (line 13) | def https(self):
method ftp (line 17) | def ftp(self):
method no_proxy (line 21) | def no_proxy(self):
method from_dict (line 25) | def from_dict(config):
method get_environment (line 40) | def get_environment(self):
method inject_proxy_environment (line 56) | def inject_proxy_environment(self, environment):
method __str__ (line 71) | def __str__(self):
FILE: docker/utils/socket.py
class SocketError (line 17) | class SocketError(Exception):
function read (line 26) | def read(socket, n=4096):
function read_exactly (line 62) | def read_exactly(socket, n):
function next_frame_header (line 76) | def next_frame_header(socket):
function frames_iter (line 92) | def frames_iter(socket, tty):
function frames_iter_no_tty (line 106) | def frames_iter_no_tty(socket):
function frames_iter_tty (line 127) | def frames_iter_tty(socket):
function consume_socket_output (line 140) | def consume_socket_output(frames, demux=False):
function demux_adaptor (line 177) | def demux_adaptor(stream_id, data):
FILE: docker/utils/utils.py
function create_ipam_pool (line 28) | def create_ipam_pool(*args, **kwargs):
function create_ipam_config (line 35) | def create_ipam_config(*args, **kwargs):
function decode_json_header (line 42) | def decode_json_header(header):
function compare_version (line 49) | def compare_version(v1, v2):
function version_lt (line 77) | def version_lt(v1, v2):
function version_gte (line 81) | def version_gte(v1, v2):
function _convert_port_binding (line 85) | def _convert_port_binding(binding):
function convert_port_bindings (line 113) | def convert_port_bindings(port_bindings):
function convert_volume_binds (line 126) | def convert_volume_binds(binds):
function convert_tmpfs_mounts (line 180) | def convert_tmpfs_mounts(tmpfs):
function convert_service_networks (line 209) | def convert_service_networks(networks):
function parse_repository_tag (line 223) | def parse_repository_tag(repo_name):
function parse_host (line 233) | def parse_host(addr, is_win32=False, tls=False):
function parse_devices (line 324) | def parse_devices(devices):
function kwargs_from_env (line 353) | def kwargs_from_env(environment=None):
function convert_filters (line 391) | def convert_filters(filters):
function datetime_to_timestamp (line 405) | def datetime_to_timestamp(dt):
function parse_bytes (line 411) | def parse_bytes(s):
function normalize_links (line 451) | def normalize_links(links):
function parse_env_file (line 458) | def parse_env_file(env_file):
function split_command (line 486) | def split_command(command):
function format_environment (line 490) | def format_environment(environment):
function format_extra_hosts (line 501) | def format_extra_hosts(extra_hosts, task=False):
function create_host_config (line 513) | def create_host_config(self, *args, **kwargs):
FILE: scripts/versions.py
class Version (line 17) | class Version(namedtuple('_Version', 'major minor patch stage edition')):
method parse (line 20) | def parse(cls, version):
method major_minor (line 34) | def major_minor(self):
method order (line 38) | def order(self):
method __str__ (line 54) | def __str__(self):
function main (line 60) | def main():
FILE: tests/helpers.py
function make_tree (line 17) | def make_tree(dirs, files):
function simple_tar (line 30) | def simple_tar(path):
function untar_file (line 42) | def untar_file(tardata, filename):
function skip_if_desktop (line 50) | def skip_if_desktop():
function requires_api_version (line 63) | def requires_api_version(version):
function requires_experimental (line 74) | def requires_experimental(until=None):
function wait_on_condition (line 93) | def wait_on_condition(condition, delay=0.1, timeout=40):
function random_name (line 101) | def random_name():
function force_leave_swarm (line 105) | def force_leave_swarm(client):
function swarm_listen_addr (line 120) | def swarm_listen_addr():
function assert_cat_socket_detached_with_keys (line 124) | def assert_cat_socket_detached_with_keys(sock, inputs):
function ctrl_with (line 156) | def ctrl_with(char):
FILE: tests/integration/api_build_test.py
class BuildTest (line 15) | class BuildTest(BaseAPIIntegrationTest):
method test_build_with_proxy (line 16) | def test_build_with_proxy(self):
method test_build_with_proxy_and_buildargs (line 35) | def test_build_with_proxy_and_buildargs(self):
method test_build_streaming (line 58) | def test_build_streaming(self):
method test_build_from_stringio (line 72) | def test_build_from_stringio(self):
method test_build_with_dockerignore (line 88) | def test_build_with_dockerignore(self):
method test_build_with_buildargs (line 152) | def test_build_with_buildargs(self):
method test_build_shmsize (line 170) | def test_build_shmsize(self):
method test_build_isolation (line 190) | def test_build_isolation(self):
method test_build_labels (line 205) | def test_build_labels(self):
method test_build_with_cache_from (line 223) | def test_build_with_cache_from(self):
method test_build_container_with_target (line 259) | def test_build_container_with_target(self):
method test_build_with_network_mode (line 281) | def test_build_with_network_mode(self):
method test_build_with_extra_hosts (line 323) | def test_build_with_extra_hosts(self):
method test_build_squash (line 354) | def test_build_squash(self):
method test_build_stderr_data (line 378) | def test_build_stderr_data(self):
method test_build_gzip_encoding (line 395) | def test_build_gzip_encoding(self):
method test_build_with_dockerfile_empty_lines (line 416) | def test_build_with_dockerfile_empty_lines(self):
method test_build_gzip_custom_encoding (line 438) | def test_build_gzip_custom_encoding(self):
method test_build_invalid_platform (line 444) | def test_build_invalid_platform(self):
method test_build_out_of_context_dockerfile (line 457) | def test_build_out_of_context_dockerfile(self):
method test_build_in_context_dockerfile (line 492) | def test_build_in_context_dockerfile(self):
method test_build_in_context_nested_dockerfile (line 523) | def test_build_in_context_nested_dockerfile(self):
method test_build_in_context_abs_dockerfile (line 556) | def test_build_in_context_abs_dockerfile(self):
method test_prune_builds (line 594) | def test_prune_builds(self):
FILE: tests/integration/api_client_test.py
class InformationTest (line 11) | class InformationTest(BaseAPIIntegrationTest):
method test_version (line 12) | def test_version(self):
method test_info (line 17) | def test_info(self):
class AutoDetectVersionTest (line 24) | class AutoDetectVersionTest(unittest.TestCase):
method test_client_init (line 25) | def test_client_init(self):
class ConnectionTimeoutTest (line 35) | class ConnectionTimeoutTest(unittest.TestCase):
method setUp (line 36) | def setUp(self):
method test_timeout (line 44) | def test_timeout(self):
class UnixconnTest (line 57) | class UnixconnTest(unittest.TestCase):
method test_resource_warnings (line 62) | def test_resource_warnings(self):
FILE: tests/integration/api_config_test.py
class ConfigAPITest (line 10) | class ConfigAPITest(BaseAPIIntegrationTest):
method setup_class (line 12) | def setup_class(cls):
method teardown_class (line 18) | def teardown_class(cls):
method test_create_config (line 22) | def test_create_config(self):
method test_create_config_unicode_data (line 31) | def test_create_config_unicode_data(self):
method test_inspect_config (line 40) | def test_inspect_config(self):
method test_remove_config (line 51) | def test_remove_config(self):
method test_list_configs (line 62) | def test_list_configs(self):
method test_create_config_with_templating (line 74) | def test_create_config_with_templating(self):
FILE: tests/integration/api_container_test.py
class ListContainersTest (line 25) | class ListContainersTest(BaseAPIIntegrationTest):
method test_list_containers (line 26) | def test_list_containers(self):
class CreateContainerTest (line 45) | class CreateContainerTest(BaseAPIIntegrationTest):
method test_create (line 47) | def test_create(self):
method test_create_with_host_pid_mode (line 52) | def test_create_with_host_pid_mode(self):
method test_create_with_links (line 67) | def test_create_with_links(self):
method test_create_with_restart_policy (line 114) | def test_create_with_restart_policy(self):
method test_create_container_with_volumes_from (line 131) | def test_create_container_with_volumes_from(self):
method create_container_readonly_fs (line 161) | def create_container_readonly_fs(self):
method create_container_with_name (line 174) | def create_container_with_name(self):
method create_container_privileged (line 182) | def create_container_privileged(self):
method test_create_with_mac_address (line 207) | def test_create_with_mac_address(self):
method test_create_with_cgroupns (line 221) | def test_create_with_cgroupns(self):
method test_group_id_ints (line 234) | def test_group_id_ints(self):
method test_group_id_strings (line 248) | def test_group_id_strings(self):
method test_valid_log_driver_and_log_opt (line 264) | def test_valid_log_driver_and_log_opt(self):
method test_invalid_log_driver_raises_exception (line 283) | def test_invalid_log_driver_raises_exception(self):
method test_valid_no_log_driver_specified (line 304) | def test_valid_no_log_driver_specified(self):
method test_valid_no_config_specified (line 323) | def test_valid_no_config_specified(self):
method test_create_with_memory_constraints_with_str (line 342) | def test_create_with_memory_constraints_with_str(self):
method test_create_with_memory_constraints_with_int (line 360) | def test_create_with_memory_constraints_with_int(self):
method test_create_with_environment_variable_no_value (line 374) | def test_create_with_environment_variable_no_value(self):
method test_create_with_tmpfs (line 387) | def test_create_with_tmpfs(self):
method test_create_with_isolation (line 403) | def test_create_with_isolation(self):
method test_create_with_auto_remove (line 414) | def test_create_with_auto_remove(self):
method test_create_with_stop_timeout (line 426) | def test_create_with_stop_timeout(self):
method test_create_with_storage_opt (line 436) | def test_create_with_storage_opt(self):
method test_create_with_init (line 450) | def test_create_with_init(self):
method test_create_with_cpu_rt_options (line 464) | def test_create_with_cpu_rt_options(self):
method test_create_with_device_cgroup_rules (line 476) | def test_create_with_device_cgroup_rules(self):
method test_create_with_uts_mode (line 487) | def test_create_with_uts_mode(self):
class VolumeBindTest (line 501) | class VolumeBindTest(BaseAPIIntegrationTest):
method setUp (line 502) | def setUp(self):
method test_create_with_binds_rw (line 517) | def test_create_with_binds_rw(self):
method test_create_with_binds_ro (line 529) | def test_create_with_binds_ro(self):
method test_create_with_binds_rw_rshared (line 548) | def test_create_with_binds_rw_rshared(self):
method test_create_with_mounts (line 569) | def test_create_with_mounts(self):
method test_create_with_mounts_ro (line 585) | def test_create_with_mounts_ro(self):
method test_create_with_volume_mount (line 602) | def test_create_with_volume_mount(self):
method test_create_with_subpath_volume_mount (line 624) | def test_create_with_subpath_volume_mount(self):
method check_container_data (line 673) | def check_container_data(self, inspect_data, rw, propagation='rprivate'):
method run_with_volume (line 685) | def run_with_volume(self, ro, *args, **kwargs):
method run_with_volume_propagation (line 701) | def run_with_volume_propagation(self, ro, propagation, *args, **kwargs):
class ArchiveTest (line 719) | class ArchiveTest(BaseAPIIntegrationTest):
method test_get_file_archive_from_container (line 720) | def test_get_file_archive_from_container(self):
method test_get_file_stat_from_container (line 738) | def test_get_file_stat_from_container(self):
method test_copy_file_to_container (line 753) | def test_copy_file_to_container(self):
method test_copy_directory_to_container (line 771) | def test_copy_directory_to_container(self):
class RenameContainerTest (line 791) | class RenameContainerTest(BaseAPIIntegrationTest):
method test_rename_container (line 792) | def test_rename_container(self):
class StartContainerTest (line 807) | class StartContainerTest(BaseAPIIntegrationTest):
method test_start_container (line 808) | def test_start_container(self):
method test_start_container_with_dict_instead_of_id (line 824) | def test_start_container_with_dict_instead_of_id(self):
method test_run_shlex_commands (line 840) | def test_run_shlex_commands(self):
class WaitTest (line 861) | class WaitTest(BaseAPIIntegrationTest):
method test_wait (line 862) | def test_wait(self):
method test_wait_with_dict_instead_of_id (line 875) | def test_wait_with_dict_instead_of_id(self):
method test_wait_with_condition (line 889) | def test_wait_with_condition(self):
class LogsTest (line 906) | class LogsTest(BaseAPIIntegrationTest):
method test_logs (line 907) | def test_logs(self):
method test_logs_tail_option (line 920) | def test_logs_tail_option(self):
method test_logs_streaming_and_follow (line 934) | def test_logs_streaming_and_follow(self):
method test_logs_streaming_and_follow_and_cancel (line 954) | def test_logs_streaming_and_follow_and_cancel(self):
method test_logs_with_dict_instead_of_id (line 972) | def test_logs_with_dict_instead_of_id(self):
method test_logs_with_tail_0 (line 985) | def test_logs_with_tail_0(self):
method test_logs_with_until (line 999) | def test_logs_with_until(self):
class DiffTest (line 1015) | class DiffTest(BaseAPIIntegrationTest):
method test_diff (line 1016) | def test_diff(self):
method test_diff_with_dict_instead_of_id (line 1029) | def test_diff_with_dict_instead_of_id(self):
class StopTest (line 1043) | class StopTest(BaseAPIIntegrationTest):
method test_stop (line 1044) | def test_stop(self):
method test_stop_with_dict_instead_of_id (line 1056) | def test_stop_with_dict_instead_of_id(self):
class KillTest (line 1070) | class KillTest(BaseAPIIntegrationTest):
method test_kill (line 1071) | def test_kill(self):
method test_kill_with_dict_instead_of_id (line 1085) | def test_kill_with_dict_instead_of_id(self):
method test_kill_with_signal (line 1099) | def test_kill_with_signal(self):
method test_kill_with_signal_name (line 1116) | def test_kill_with_signal_name(self):
method test_kill_with_signal_integer (line 1131) | def test_kill_with_signal_integer(self):
class PortTest (line 1147) | class PortTest(BaseAPIIntegrationTest):
method test_port (line 1148) | def test_port(self):
class ContainerTopTest (line 1185) | class ContainerTopTest(BaseAPIIntegrationTest):
method test_top (line 1188) | def test_top(self):
method test_top_with_psargs (line 1208) | def test_top_with_psargs(self):
class RestartContainerTest (line 1221) | class RestartContainerTest(BaseAPIIntegrationTest):
method test_restart (line 1222) | def test_restart(self):
method test_restart_with_low_timeout (line 1241) | def test_restart_with_low_timeout(self):
method test_restart_with_dict_instead_of_id (line 1250) | def test_restart_with_dict_instead_of_id(self):
class RemoveContainerTest (line 1271) | class RemoveContainerTest(BaseAPIIntegrationTest):
method test_remove (line 1272) | def test_remove(self):
method test_remove_with_dict_instead_of_id (line 1282) | def test_remove_with_dict_instead_of_id(self):
class AttachContainerTest (line 1293) | class AttachContainerTest(BaseAPIIntegrationTest):
method test_run_container_streaming (line 1294) | def test_run_container_streaming(self):
method test_run_container_reading_socket_http (line 1303) | def test_run_container_reading_socket_http(self):
method test_run_container_reading_socket_ws (line 1325) | def test_run_container_reading_socket_ws(self):
method test_attach_no_stream (line 1343) | def test_attach_no_stream(self):
method test_attach_stream_and_cancel (line 1359) | def test_attach_stream_and_cancel(self):
method test_detach_with_default (line 1377) | def test_detach_with_default(self):
method test_detach_with_config_file (line 1394) | def test_detach_with_config_file(self):
method test_detach_with_arg (line 1411) | def test_detach_with_arg(self):
class PauseTest (line 1429) | class PauseTest(BaseAPIIntegrationTest):
method test_pause_unpause (line 1430) | def test_pause_unpause(self):
class PruneTest (line 1458) | class PruneTest(BaseAPIIntegrationTest):
method test_prune_containers (line 1460) | def test_prune_containers(self):
class GetContainerStatsTest (line 1474) | class GetContainerStatsTest(BaseAPIIntegrationTest):
method test_get_container_stats_no_stream (line 1475) | def test_get_container_stats_no_stream(self):
class ContainerUpdateTest (line 1503) | class ContainerUpdateTest(BaseAPIIntegrationTest):
method test_update_container (line 1505) | def test_update_container(self):
method test_restart_policy_update (line 1520) | def test_restart_policy_update(self):
class ContainerCPUTest (line 1550) | class ContainerCPUTest(BaseAPIIntegrationTest):
method test_container_cpu_shares (line 1551) | def test_container_cpu_shares(self):
method test_container_cpuset (line 1563) | def test_container_cpuset(self):
method test_create_with_runtime (line 1576) | def test_create_with_runtime(self):
class LinkTest (line 1585) | class LinkTest(BaseAPIIntegrationTest):
method test_remove_link (line 1586) | def test_remove_link(self):
FILE: tests/integration/api_exec_test.py
class ExecTest (line 12) | class ExecTest(BaseAPIIntegrationTest):
method test_execute_command_with_proxy_env (line 13) | def test_execute_command_with_proxy_env(self):
method test_execute_command (line 51) | def test_execute_command(self):
method test_exec_command_string (line 64) | def test_exec_command_string(self):
method test_exec_command_as_user (line 77) | def test_exec_command_as_user(self):
method test_exec_command_as_root (line 90) | def test_exec_command_as_root(self):
method test_exec_command_streaming (line 103) | def test_exec_command_streaming(self):
method test_exec_start_socket (line 118) | def test_exec_start_socket(self):
method test_exec_start_detached (line 140) | def test_exec_start_detached(self):
method test_exec_inspect (line 155) | def test_exec_inspect(self):
method test_exec_command_with_env (line 170) | def test_exec_command_with_env(self):
method test_exec_command_with_workdir (line 184) | def test_exec_command_with_workdir(self):
method test_detach_with_default (line 195) | def test_detach_with_default(self):
method test_detach_with_config_file (line 213) | def test_detach_with_config_file(self):
class ExecDemuxTest (line 231) | class ExecDemuxTest(BaseAPIIntegrationTest):
method setUp (line 242) | def setUp(self):
method test_exec_command_no_stream_no_demux (line 250) | def test_exec_command_no_stream_no_demux(self):
method test_exec_command_stream_no_demux (line 257) | def test_exec_command_stream_no_demux(self):
method test_exec_command_no_stream_demux (line 265) | def test_exec_command_no_stream_demux(self):
method test_exec_command_stream_demux (line 271) | def test_exec_command_stream_demux(self):
method test_exec_command_tty_no_stream_no_demux (line 279) | def test_exec_command_tty_no_stream_no_demux(self):
method test_exec_command_tty_stream_no_demux (line 285) | def test_exec_command_tty_stream_no_demux(self):
method test_exec_command_tty_no_stream_demux (line 297) | def test_exec_command_tty_no_stream_demux(self):
method test_exec_command_tty_stream_demux (line 303) | def test_exec_command_tty_stream_demux(self):
FILE: tests/integration/api_healthcheck_test.py
function wait_on_health_status (line 7) | def wait_on_health_status(client, container, status):
class HealthcheckTest (line 14) | class HealthcheckTest(BaseAPIIntegrationTest):
method test_healthcheck_shell_command (line 17) | def test_healthcheck_shell_command(self):
method test_healthcheck_passes (line 28) | def test_healthcheck_passes(self):
method test_healthcheck_fails (line 41) | def test_healthcheck_fails(self):
method test_healthcheck_start_period (line 54) | def test_healthcheck_start_period(self):
FILE: tests/integration/api_image_test.py
class ListImagesTest (line 19) | class ListImagesTest(BaseAPIIntegrationTest):
method test_images (line 20) | def test_images(self):
method test_images_quiet (line 32) | def test_images_quiet(self):
class PullImageTest (line 37) | class PullImageTest(BaseAPIIntegrationTest):
method test_pull (line 38) | def test_pull(self):
method test_pull_streaming (line 50) | def test_pull_streaming(self):
method test_pull_invalid_platform (line 66) | def test_pull_invalid_platform(self):
class CommitTest (line 76) | class CommitTest(BaseAPIIntegrationTest):
method test_commit (line 77) | def test_commit(self):
method test_commit_with_changes (line 91) | def test_commit_with_changes(self):
class RemoveImageTest (line 104) | class RemoveImageTest(BaseAPIIntegrationTest):
method test_remove (line 105) | def test_remove(self):
class ImportImageTest (line 121) | class ImportImageTest(BaseAPIIntegrationTest):
method write_dummy_tar_content (line 126) | def write_dummy_tar_content(self, n_bytes, tar_fd):
method dummy_tar_stream (line 142) | def dummy_tar_stream(self, n_bytes):
method dummy_tar_file (line 150) | def dummy_tar_file(self, n_bytes):
method test_import_from_bytes (line 157) | def test_import_from_bytes(self):
method test_import_from_file (line 177) | def test_import_from_file(self):
method test_import_from_stream (line 193) | def test_import_from_stream(self):
method test_import_image_from_data_with_changes (line 208) | def test_import_image_from_data_with_changes(self):
method test_import_image_with_changes (line 230) | def test_import_image_with_changes(self):
method test_get_load_image (line 252) | def test_get_load_image(self):
method temporary_http_file_server (line 262) | def temporary_http_file_server(self, stream):
method test_import_from_url (line 282) | def test_import_from_url(self):
class PruneImagesTest (line 303) | class PruneImagesTest(BaseAPIIntegrationTest):
method test_prune_images (line 304) | def test_prune_images(self):
class SaveLoadImagesTest (line 331) | class SaveLoadImagesTest(BaseAPIIntegrationTest):
method test_get_image_load_image (line 333) | def test_get_image_load_image(self):
class InspectDistributionTest (line 354) | class InspectDistributionTest(BaseAPIIntegrationTest):
method test_inspect_distribution (line 355) | def test_inspect_distribution(self):
FILE: tests/integration/api_network_test.py
class TestNetworks (line 10) | class TestNetworks(BaseAPIIntegrationTest):
method tearDown (line 11) | def tearDown(self):
method create_network (line 15) | def create_network(self, *args, **kwargs):
method test_list_networks (line 21) | def test_list_networks(self):
method test_inspect_network (line 35) | def test_inspect_network(self):
method test_create_network_with_ipam_config (line 45) | def test_create_network_with_ipam_config(self):
method test_create_network_with_host_driver_fails (line 82) | def test_create_network_with_host_driver_fails(self):
method test_remove_network (line 86) | def test_remove_network(self):
method test_connect_and_disconnect_container (line 93) | def test_connect_and_disconnect_container(self):
method test_connect_and_force_disconnect_container (line 120) | def test_connect_and_force_disconnect_container(self):
method test_connect_with_aliases (line 145) | def test_connect_with_aliases(self):
method test_connect_on_container_create (line 161) | def test_connect_on_container_create(self):
method test_create_with_aliases (line 181) | def test_create_with_aliases(self):
method test_create_with_ipv4_address (line 207) | def test_create_with_ipv4_address(self):
method test_create_with_ipv6_address (line 233) | def test_create_with_ipv6_address(self):
method test_create_with_linklocal_ips (line 260) | def test_create_with_linklocal_ips(self):
method test_create_with_driveropt (line 281) | def test_create_with_driveropt(self):
method test_create_with_links (line 302) | def test_create_with_links(self):
method test_create_check_duplicate (line 328) | def test_create_check_duplicate(self):
method test_connect_with_links (line 334) | def test_connect_with_links(self):
method test_connect_with_ipv4_address (line 360) | def test_connect_with_ipv4_address(self):
method test_connect_with_ipv6_address (line 386) | def test_connect_with_ipv6_address(self):
method test_connect_with_mac_address (line 413) | def test_connect_with_mac_address(self):
method test_create_internal_networks (line 429) | def test_create_internal_networks(self):
method test_create_network_with_labels (line 435) | def test_create_network_with_labels(self):
method test_create_network_with_labels_wrong_type (line 448) | def test_create_network_with_labels_wrong_type(self):
method test_create_network_ipv6_enabled (line 453) | def test_create_network_ipv6_enabled(self):
method test_create_network_attachable (line 469) | def test_create_network_attachable(self):
method test_create_network_ingress (line 476) | def test_create_network_ingress(self):
method test_prune_networks (line 484) | def test_prune_networks(self):
method test_create_inspect_network_with_scope (line 490) | def test_create_inspect_network_with_scope(self):
method test_create_remove_network_with_space_in_name (line 508) | def test_create_remove_network_with_space_in_name(self):
FILE: tests/integration/api_plugin_test.py
class PluginTest (line 14) | class PluginTest(BaseAPIIntegrationTest):
method teardown_class (line 16) | def teardown_class(cls):
method teardown_method (line 23) | def teardown_method(self, method):
method ensure_plugin_installed (line 38) | def ensure_plugin_installed(self, plugin_name):
method test_enable_plugin (line 47) | def test_enable_plugin(self):
method test_disable_plugin (line 56) | def test_disable_plugin(self):
method test_inspect_plugin (line 68) | def test_inspect_plugin(self):
method test_plugin_privileges (line 75) | def test_plugin_privileges(self):
method test_list_plugins (line 83) | def test_list_plugins(self):
method test_configure_plugin (line 90) | def test_configure_plugin(self):
method test_remove_plugin (line 104) | def test_remove_plugin(self):
method test_force_remove_plugin (line 109) | def test_force_remove_plugin(self):
method test_install_plugin (line 115) | def test_install_plugin(self):
method test_upgrade_plugin (line 128) | def test_upgrade_plugin(self):
method test_create_plugin (line 137) | def test_create_plugin(self):
FILE: tests/integration/api_secret_test.py
class SecretAPITest (line 10) | class SecretAPITest(BaseAPIIntegrationTest):
method setup_class (line 12) | def setup_class(cls):
method teardown_class (line 18) | def teardown_class(cls):
method test_create_secret (line 22) | def test_create_secret(self):
method test_create_secret_unicode_data (line 31) | def test_create_secret_unicode_data(self):
method test_inspect_secret (line 40) | def test_inspect_secret(self):
method test_remove_secret (line 51) | def test_remove_secret(self):
method test_list_secrets (line 62) | def test_list_secrets(self):
FILE: tests/integration/api_service_test.py
class ServiceTest (line 12) | class ServiceTest(BaseAPIIntegrationTest):
method setup_class (line 14) | def setup_class(cls):
method teardown_class (line 20) | def teardown_class(cls):
method tearDown (line 24) | def tearDown(self):
method get_service_name (line 32) | def get_service_name(self):
method get_service_container (line 35) | def get_service_container(self, service_name, attempts=20, interval=0.5,
method create_simple_service (line 52) | def create_simple_service(self, name=None, labels=None):
method test_list_services (line 67) | def test_list_services(self):
method test_list_services_filter_by_label (line 79) | def test_list_services_filter_by_label(self):
method test_list_services_with_status (line 88) | def test_list_services_with_status(self):
method test_inspect_service_by_id (line 101) | def test_inspect_service_by_id(self):
method test_inspect_service_by_name (line 107) | def test_inspect_service_by_name(self):
method test_inspect_service_insert_defaults (line 114) | def test_inspect_service_insert_defaults(self):
method test_remove_service_by_id (line 124) | def test_remove_service_by_id(self):
method test_remove_service_by_name (line 130) | def test_remove_service_by_name(self):
method test_create_service_simple (line 136) | def test_create_service_simple(self):
method test_service_logs (line 144) | def test_service_logs(self):
method test_create_service_custom_log_driver (line 166) | def test_create_service_custom_log_driver(self):
method test_create_service_with_volume_mount (line 183) | def test_create_service_with_volume_mount(self):
method test_create_service_with_resources_constraints (line 205) | def test_create_service_with_resources_constraints(self):
method _create_service_with_generic_resources (line 225) | def _create_service_with_generic_resources(self, generic_resources):
method test_create_service_with_generic_resources (line 239) | def test_create_service_with_generic_resources(self):
method test_create_service_with_invalid_generic_resources (line 271) | def test_create_service_with_invalid_generic_resources(self):
method test_create_service_with_update_config (line 276) | def test_create_service_with_update_config(self):
method test_create_service_with_failure_action_rollback (line 294) | def test_create_service_with_failure_action_rollback(self):
method test_create_service_with_update_config_monitor (line 308) | def test_create_service_with_update_config_monitor(self):
method test_create_service_with_rollback_config (line 325) | def test_create_service_with_rollback_config(self):
method test_create_service_with_restart_policy (line 345) | def test_create_service_with_restart_policy(self):
method test_create_service_with_custom_networks (line 360) | def test_create_service_with_custom_networks(self):
method test_create_service_with_network_attachment_config (line 385) | def test_create_service_with_network_attachment_config(self):
method test_create_service_with_placement (line 414) | def test_create_service_with_placement(self):
method test_create_service_with_placement_object (line 427) | def test_create_service_with_placement_object(self):
method test_create_service_with_placement_platform (line 443) | def test_create_service_with_placement_platform(self):
method test_create_service_with_placement_preferences (line 456) | def test_create_service_with_placement_preferences(self):
method test_create_service_with_placement_preferences_tuple (line 471) | def test_create_service_with_placement_preferences_tuple(self):
method test_create_service_with_placement_maxreplicas (line 486) | def test_create_service_with_placement_maxreplicas(self):
method test_create_service_with_endpoint_spec (line 498) | def test_create_service_with_endpoint_spec(self):
method test_create_service_with_endpoint_spec_host_publish_mode (line 528) | def test_create_service_with_endpoint_spec_host_publish_mode(self):
method test_create_service_with_env (line 547) | def test_create_service_with_env(self):
method test_create_service_with_update_order (line 564) | def test_create_service_with_update_order(self):
method test_create_service_with_tty (line 582) | def test_create_service_with_tty(self):
method test_create_service_with_tty_dict (line 599) | def test_create_service_with_tty_dict(self):
method test_create_service_global_mode (line 615) | def test_create_service_global_mode(self):
method test_create_service_replicated_mode (line 628) | def test_create_service_replicated_mode(self):
method test_create_service_global_job_mode (line 644) | def test_create_service_global_job_mode(self):
method test_create_service_replicated_job_mode (line 658) | def test_create_service_replicated_job_mode(self):
method test_update_service_force_update (line 677) | def test_update_service_force_update(self):
method test_create_service_with_secret (line 698) | def test_create_service_with_secret(self):
method test_create_service_with_unicode_secret (line 723) | def test_create_service_with_unicode_secret(self):
method test_create_service_with_config (line 750) | def test_create_service_with_config(self):
method test_create_service_with_unicode_config (line 775) | def test_create_service_with_unicode_config(self):
method test_create_service_with_hosts (line 802) | def test_create_service_with_hosts(self):
method test_create_service_with_hostname (line 820) | def test_create_service_with_hostname(self):
method test_create_service_with_groups (line 835) | def test_create_service_with_groups(self):
method test_create_service_with_dns_config (line 850) | def test_create_service_with_dns_config(self):
method test_create_service_with_healthcheck (line 869) | def test_create_service_with_healthcheck(self):
method test_create_service_with_readonly (line 891) | def test_create_service_with_readonly(self):
method test_create_service_with_stop_signal (line 905) | def test_create_service_with_stop_signal(self):
method test_create_service_with_privileges (line 922) | def test_create_service_with_privileges(self):
method test_create_service_with_init (line 940) | def test_create_service_with_init(self):
method test_update_service_with_defaults_name (line 954) | def test_update_service_with_defaults_name(self):
method test_update_service_with_defaults_labels (line 977) | def test_update_service_with_defaults_labels(self):
method test_update_service_with_defaults_mode (line 1004) | def test_update_service_with_defaults_mode(self):
method test_update_service_with_defaults_container_labels (line 1033) | def test_update_service_with_defaults_container_labels(self):
method test_update_service_with_defaults_update_config (line 1080) | def test_update_service_with_defaults_update_config(self):
method test_update_service_with_defaults_networks (line 1111) | def test_update_service_with_defaults_networks(self):
method test_update_service_with_defaults_endpoint_spec (line 1163) | def test_update_service_with_defaults_endpoint_spec(self):
method test_update_service_remove_healthcheck (line 1221) | def test_update_service_remove_healthcheck(self):
method test_update_service_remove_labels (line 1261) | def test_update_service_remove_labels(self):
method test_update_service_remove_container_labels (line 1284) | def test_update_service_remove_container_labels(self):
method test_update_service_with_network_change (line 1319) | def test_update_service_with_network_change(self):
method _update_service (line 1400) | def _update_service(self, svc_id, *args, **kwargs):
method test_create_service_cap_add (line 1420) | def test_create_service_cap_add(self):
method test_create_service_cap_drop (line 1435) | def test_create_service_cap_drop(self):
method test_create_service_with_sysctl (line 1450) | def test_create_service_with_sysctl(self):
FILE: tests/integration/api_swarm_test.py
class SwarmTest (line 11) | class SwarmTest(BaseAPIIntegrationTest):
method setUp (line 12) | def setUp(self):
method tearDown (line 17) | def tearDown(self):
method test_init_swarm_simple (line 27) | def test_init_swarm_simple(self):
method test_init_swarm_force_new_cluster (line 31) | def test_init_swarm_force_new_cluster(self):
method test_init_swarm_custom_addr_pool_defaults (line 41) | def test_init_swarm_custom_addr_pool_defaults(self):
method test_init_swarm_custom_addr_pool_only_pool (line 48) | def test_init_swarm_custom_addr_pool_only_pool(self):
method test_init_swarm_custom_addr_pool_only_subnet_size (line 55) | def test_init_swarm_custom_addr_pool_only_subnet_size(self):
method test_init_swarm_custom_addr_pool_both_args (line 62) | def test_init_swarm_custom_addr_pool_both_args(self):
method test_init_already_in_cluster (line 70) | def test_init_already_in_cluster(self):
method test_init_swarm_custom_raft_spec (line 76) | def test_init_swarm_custom_raft_spec(self):
method test_init_swarm_with_ca_config (line 86) | def test_init_swarm_with_ca_config(self):
method test_init_swarm_with_autolock_managers (line 101) | def test_init_swarm_with_autolock_managers(self):
method test_init_swarm_with_log_driver (line 118) | def test_init_swarm_with_log_driver(self):
method test_leave_swarm (line 128) | def test_leave_swarm(self):
method test_update_swarm (line 140) | def test_update_swarm(self):
method test_list_nodes (line 171) | def test_list_nodes(self):
method test_inspect_node (line 190) | def test_inspect_node(self):
method test_update_node (line 202) | def test_update_node(self):
method test_remove_main_node (line 225) | def test_remove_main_node(self):
method test_rotate_manager_unlock_key (line 242) | def test_rotate_manager_unlock_key(self):
method test_init_swarm_data_path_addr (line 256) | def test_init_swarm_data_path_addr(self):
method test_init_swarm_data_path_port (line 260) | def test_init_swarm_data_path_port(self):
FILE: tests/integration/api_volume_test.py
class TestVolumes (line 9) | class TestVolumes(BaseAPIIntegrationTest):
method test_create_volume (line 10) | def test_create_volume(self):
method test_create_volume_invalid_driver (line 19) | def test_create_volume_invalid_driver(self):
method test_list_volumes (line 31) | def test_list_volumes(self):
method test_inspect_volume (line 40) | def test_inspect_volume(self):
method test_inspect_nonexistent_volume (line 47) | def test_inspect_nonexistent_volume(self):
method test_remove_volume (line 52) | def test_remove_volume(self):
method test_force_remove_volume (line 59) | def test_force_remove_volume(self):
method test_prune_volumes (line 66) | def test_prune_volumes(self):
method test_remove_nonexistent_volume (line 72) | def test_remove_nonexistent_volume(self):
FILE: tests/integration/base.py
class BaseIntegrationTest (line 14) | class BaseIntegrationTest(unittest.TestCase):
method setUp (line 20) | def setUp(self):
method tearDown (line 30) | def tearDown(self):
class BaseAPIIntegrationTest (line 72) | class BaseAPIIntegrationTest(BaseIntegrationTest):
method setUp (line 78) | def setUp(self):
method tearDown (line 82) | def tearDown(self):
method get_client_instance (line 87) | def get_client_instance():
method _init_swarm (line 93) | def _init_swarm(client, **kwargs):
method run_container (line 98) | def run_container(self, *args, **kwargs):
method create_and_start (line 111) | def create_and_start(self, image=TEST_IMG, command='top', **kwargs):
method execute (line 118) | def execute(self, container, cmd, exit_code=0, **kwargs):
method init_swarm (line 126) | def init_swarm(self, **kwargs):
FILE: tests/integration/client_test.py
class ClientTest (line 11) | class ClientTest(unittest.TestCase):
method test_info (line 14) | def test_info(self):
method test_ping (line 19) | def test_ping(self):
method test_version (line 22) | def test_version(self):
method test_df (line 26) | def test_df(self):
class CancellableEventsTest (line 34) | class CancellableEventsTest(unittest.TestCase):
method test_cancel_events (line 37) | def test_cancel_events(self):
FILE: tests/integration/conftest.py
function setup_test_session (line 13) | def setup_test_session():
FILE: tests/integration/context_api_test.py
class ContextLifecycleTest (line 13) | class ContextLifecycleTest(BaseAPIIntegrationTest):
method test_lifecycle (line 14) | def test_lifecycle(self):
method test_context_remove (line 49) | def test_context_remove(self):
method test_load_context_without_orchestrator (line 57) | def test_load_context_without_orchestrator(self):
FILE: tests/integration/credentials/store_test.py
class TestStore (line 17) | class TestStore:
method teardown_method (line 18) | def teardown_method(self):
method setup_method (line 25) | def setup_method(self):
method get_random_servername (line 37) | def get_random_servername(self):
method test_store_and_get (line 42) | def test_store_and_get(self):
method test_get_nonexistent (line 52) | def test_get_nonexistent(self):
method test_store_and_erase (line 57) | def test_store_and_erase(self):
method test_unicode_strings (line 64) | def test_unicode_strings(self):
method test_list (line 74) | def test_list(self):
method test_execute_with_env_override (line 84) | def test_execute_with_env_override(self):
method test_unavailable_store (line 91) | def test_unavailable_store(self):
FILE: tests/integration/credentials/utils_test.py
function test_create_environment_dict (line 8) | def test_create_environment_dict():
FILE: tests/integration/errors_test.py
class ErrorsTest (line 8) | class ErrorsTest(BaseAPIIntegrationTest):
method test_api_error_parses_json (line 9) | def test_api_error_parses_json(self):
FILE: tests/integration/models_containers_test.py
class ContainerCollectionTest (line 13) | class ContainerCollectionTest(BaseIntegrationTest):
method test_run (line 15) | def test_run(self):
method test_run_detach (line 21) | def test_run_detach(self):
method test_run_with_error (line 28) | def test_run_with_error(self):
method test_run_with_image_that_does_not_exist (line 37) | def test_run_with_image_that_does_not_exist(self):
method test_run_with_volume (line 45) | def test_run_with_volume(self):
method test_run_with_named_volume (line 66) | def test_run_with_named_volume(self):
method test_run_with_network (line 88) | def test_run_with_network(self):
method test_run_with_networking_config (line 106) | def test_run_with_networking_config(self):
method test_run_with_networking_config_with_undeclared_network (line 140) | def test_run_with_networking_config_with_undeclared_network(self):
method test_run_with_networking_config_only_undeclared_network (line 168) | def test_run_with_networking_config_only_undeclared_network(self):
method test_run_with_none_driver (line 199) | def test_run_with_none_driver(self):
method test_run_with_json_file_driver (line 208) | def test_run_with_json_file_driver(self):
method test_run_with_auto_remove (line 218) | def test_run_with_auto_remove(self):
method test_run_with_auto_remove_error (line 228) | def test_run_with_auto_remove_error(self):
method test_run_with_streamed_logs (line 240) | def test_run_with_streamed_logs(self):
method test_run_with_streamed_logs_and_cancel (line 252) | def test_run_with_streamed_logs_and_cancel(self):
method test_run_with_proxy_config (line 266) | def test_run_with_proxy_config(self):
method test_get (line 277) | def test_get(self):
method test_list (line 284) | def test_list(self):
method test_list_sparse (line 302) | def test_list_sparse(self):
class ContainerTest (line 323) | class ContainerTest(BaseIntegrationTest):
method test_commit (line 325) | def test_commit(self):
method test_diff (line 338) | def test_diff(self):
method test_exec_run_success (line 345) | def test_exec_run_success(self):
method test_exec_run_error_code_from_exec (line 355) | def test_exec_run_error_code_from_exec(self):
method test_exec_run_failed (line 364) | def test_exec_run_failed(self):
method test_kill (line 376) | def test_kill(self):
method test_logs (line 387) | def test_logs(self):
method test_pause (line 395) | def test_pause(self):
method test_remove (line 406) | def test_remove(self):
method test_rename (line 416) | def test_rename(self):
method test_restart (line 426) | def test_restart(self):
method test_start (line 436) | def test_start(self):
method test_stats (line 445) | def test_stats(self):
method test_ports_target_none (line 454) | def test_ports_target_none(self):
method test_ports_target_tuple (line 474) | def test_ports_target_tuple(self):
method test_ports_target_list (line 494) | def test_ports_target_list(self):
method test_stop (line 514) | def test_stop(self):
method test_top (line 523) | def test_top(self):
method test_update (line 531) | def test_update(self):
method test_wait (line 541) | def test_wait(self):
method test_create_with_volume_driver (line 552) | def test_create_with_volume_driver(self):
FILE: tests/integration/models_images_test.py
class ImageCollectionTest (line 12) | class ImageCollectionTest(BaseIntegrationTest):
method test_build (line 14) | def test_build(self):
method test_build_with_error (line 24) | def test_build_with_error(self):
method test_build_with_multiple_success (line 36) | def test_build_with_multiple_success(self):
method test_build_with_success_build_output (line 47) | def test_build_with_success_build_output(self):
method test_list (line 58) | def test_list(self):
method test_list_with_repository (line 63) | def test_list_with_repository(self):
method test_pull (line 69) | def test_pull(self):
method test_pull_with_tag (line 74) | def test_pull_with_tag(self):
method test_pull_with_sha (line 79) | def test_pull_with_sha(self):
method test_pull_multiple (line 88) | def test_pull_multiple(self):
method test_load_error (line 94) | def test_load_error(self):
method test_save_and_load (line 99) | def test_save_and_load(self):
method test_save_and_load_repo_name (line 113) | def test_save_and_load_repo_name(self):
method test_save_name_error (line 133) | def test_save_name_error(self):
class ImageTest (line 140) | class ImageTest(BaseIntegrationTest):
method test_tag_and_remove (line 142) | def test_tag_and_remove(self):
function get_ids (line 163) | def get_ids(images):
FILE: tests/integration/models_networks_test.py
class NetworkCollectionTest (line 7) | class NetworkCollectionTest(BaseIntegrationTest):
method test_create (line 9) | def test_create(self):
method test_get (line 17) | def test_get(self):
method test_list_remove (line 25) | def test_list_remove(self):
class NetworkTest (line 51) | class NetworkTest(BaseIntegrationTest):
method test_connect_disconnect (line 53) | def test_connect_disconnect(self):
FILE: tests/integration/models_nodes_test.py
class NodesTest (line 9) | class NodesTest(unittest.TestCase):
method setUp (line 10) | def setUp(self):
method tearDown (line 13) | def tearDown(self):
method test_list_get_update (line 16) | def test_list_get_update(self):
FILE: tests/integration/models_resources_test.py
class ModelTest (line 6) | class ModelTest(BaseIntegrationTest):
method test_reload (line 8) | def test_reload(self):
FILE: tests/integration/models_services_test.py
class ServiceTest (line 13) | class ServiceTest(unittest.TestCase):
method setUpClass (line 15) | def setUpClass(cls):
method tearDownClass (line 21) | def tearDownClass(cls):
method test_create (line 24) | def test_create(self):
method test_create_with_network (line 47) | def test_create_with_network(self):
method test_get (line 66) | def test_get(self):
method test_list_remove (line 77) | def test_list_remove(self):
method test_tasks (line 88) | def test_tasks(self):
method test_update (line 112) | def test_update(self):
method test_update_retains_service_labels (line 131) | def test_update_retains_service_labels(self):
method test_update_retains_container_labels (line 151) | def test_update_retains_container_labels(self):
method test_update_remove_service_labels (line 171) | def test_update_remove_service_labels(self):
method test_update_retains_networks (line 192) | def test_update_retains_networks(self):
method test_scale_service (line 217) | def test_scale_service(self):
method test_scale_method_service (line 241) | def test_scale_method_service(self):
method test_scale_method_global_service (line 263) | def test_scale_method_global_service(self):
method test_force_update_service (line 285) | def test_force_update_service(self):
method test_force_update_service_using_bool (line 307) | def test_force_update_service_using_bool(self):
method test_force_update_service_using_shorthand_method (line 329) | def test_force_update_service_using_shorthand_method(self):
method test_create_cap_add (line 344) | def test_create_cap_add(self):
method test_create_cap_drop (line 363) | def test_create_cap_drop(self):
FILE: tests/integration/models_swarm_test.py
class SwarmTest (line 11) | class SwarmTest(unittest.TestCase):
method setUp (line 12) | def setUp(self):
method tearDown (line 15) | def tearDown(self):
method test_init_update_leave (line 18) | def test_init_update_leave(self):
method test_join_on_already_joined_swarm (line 36) | def test_join_on_already_joined_swarm(self):
FILE: tests/integration/models_volumes_test.py
class VolumesTest (line 6) | class VolumesTest(BaseIntegrationTest):
method test_create_get (line 7) | def test_create_get(self):
method test_list_remove (line 22) | def test_list_remove(self):
FILE: tests/integration/regression_test.py
class TestRegressions (line 11) | class TestRegressions(BaseAPIIntegrationTest):
method test_443_handle_nonchunked_response_in_stream (line 13) | def test_443_handle_nonchunked_response_in_stream(self):
method test_542_truncate_ids_client_side (line 21) | def test_542_truncate_ids_client_side(self):
method test_647_support_doubleslash_in_image_names (line 28) | def test_647_support_doubleslash_in_image_names(self):
method test_649_handle_timeout_value_none (line 32) | def test_649_handle_timeout_value_none(self):
method test_715_handle_user_param_as_int_value (line 38) | def test_715_handle_user_param_as_int_value(self):
method test_792_explicit_port_protocol (line 46) | def test_792_explicit_port_protocol(self):
FILE: tests/ssh/api_build_test.py
class BuildTest (line 15) | class BuildTest(BaseAPIIntegrationTest):
method test_build_with_proxy (line 16) | def test_build_with_proxy(self):
method test_build_with_proxy_and_buildargs (line 35) | def test_build_with_proxy_and_buildargs(self):
method test_build_streaming (line 58) | def test_build_streaming(self):
method test_build_from_stringio (line 72) | def test_build_from_stringio(self):
method test_build_with_dockerignore (line 88) | def test_build_with_dockerignore(self):
method test_build_with_buildargs (line 143) | def test_build_with_buildargs(self):
method test_build_shmsize (line 161) | def test_build_shmsize(self):
method test_build_isolation (line 181) | def test_build_isolation(self):
method test_build_labels (line 196) | def test_build_labels(self):
method test_build_with_cache_from (line 214) | def test_build_with_cache_from(self):
method test_build_container_with_target (line 250) | def test_build_container_with_target(self):
method test_build_with_network_mode (line 272) | def test_build_with_network_mode(self):
method test_build_with_extra_hosts (line 314) | def test_build_with_extra_hosts(self):
method test_build_squash (line 345) | def test_build_squash(self):
method test_build_stderr_data (line 369) | def test_build_stderr_data(self):
method test_build_gzip_encoding (line 386) | def test_build_gzip_encoding(self):
method test_build_with_dockerfile_empty_lines (line 407) | def test_build_with_dockerfile_empty_lines(self):
method test_build_gzip_custom_encoding (line 429) | def test_build_gzip_custom_encoding(self):
method test_build_invalid_platform (line 435) | def test_build_invalid_platform(self):
method test_build_out_of_context_dockerfile (line 448) | def test_build_out_of_context_dockerfile(self):
method test_build_in_context_dockerfile (line 483) | def test_build_in_context_dockerfile(self):
method test_build_in_context_nested_dockerfile (line 514) | def test_build_in_context_nested_dockerfile(self):
method test_build_in_context_abs_dockerfile (line 547) | def test_build_in_context_abs_dockerfile(self):
method test_prune_builds (line 585) | def test_prune_builds(self):
FILE: tests/ssh/base.py
class BaseIntegrationTest (line 16) | class BaseIntegrationTest(unittest.TestCase):
method setUp (line 22) | def setUp(self):
method tearDown (line 32) | def tearDown(self):
class BaseAPIIntegrationTest (line 76) | class BaseAPIIntegrationTest(BaseIntegrationTest):
method setUpClass (line 82) | def setUpClass(cls):
method tearDown (line 86) | def tearDown(self):
method get_client_instance (line 91) | def get_client_instance():
method _init_swarm (line 100) | def _init_swarm(client, **kwargs):
method run_container (line 105) | def run_container(self, *args, **kwargs):
method create_and_start (line 118) | def create_and_start(self, image=TEST_IMG, command='top', **kwargs):
method execute (line 125) | def execute(self, container, cmd, exit_code=0, **kwargs):
method init_swarm (line 133) | def init_swarm(self, **kwargs):
FILE: tests/ssh/connect_test.py
class SSHConnectionTest (line 12) | class SSHConnectionTest(unittest.TestCase):
method test_ssh_unknown_host (line 15) | def test_ssh_unknown_host(self):
FILE: tests/unit/api_build_test.py
class BuildTest (line 15) | class BuildTest(BaseAPIClientTest):
method test_build_container (line 16) | def test_build_container(self):
method test_build_container_pull (line 31) | def test_build_container_pull(self):
method test_build_container_custom_context (line 46) | def test_build_container_custom_context(self):
method test_build_container_custom_context_gzip (line 62) | def test_build_container_custom_context_gzip(self):
method test_build_remote_with_registry_auth (line 79) | def test_build_remote_with_registry_auth(self):
method test_build_container_with_named_dockerfile (line 118) | def test_build_container_with_named_dockerfile(self):
method test_build_with_invalid_tag (line 121) | def test_build_with_invalid_tag(self):
method test_build_container_with_container_limits (line 125) | def test_build_container_with_container_limits(self):
method test_build_container_invalid_container_limits (line 136) | def test_build_container_invalid_container_limits(self):
method test_set_auth_headers_with_empty_dict_and_auth_configs (line 140) | def test_set_auth_headers_with_empty_dict_and_auth_configs(self):
method test_set_auth_headers_with_dict_and_auth_configs (line 161) | def test_set_auth_headers_with_dict_and_auth_configs(self):
method test_set_auth_headers_with_dict_and_no_auth_configs (line 183) | def test_set_auth_headers_with_dict_and_no_auth_configs(self):
method test_process_dockerfile_win_longpath_prefix (line 193) | def test_process_dockerfile_win_longpath_prefix(self):
method test_process_dockerfile (line 225) | def test_process_dockerfile(self):
FILE: tests/unit/api_container_test.py
function fake_inspect_container_tty (line 23) | def fake_inspect_container_tty(self, container):
class StartContainerTest (line 27) | class StartContainerTest(BaseAPIClientTest):
method test_start_container (line 28) | def test_start_container(self):
method test_start_container_none (line 37) | def test_start_container_none(self):
method test_start_container_regression_573 (line 48) | def test_start_container_regression_573(self):
method test_start_container_with_lxc_conf (line 51) | def test_start_container_with_lxc_conf(self):
method test_start_container_with_lxc_conf_compat (line 58) | def test_start_container_with_lxc_conf_compat(self):
method test_start_container_with_binds_ro (line 65) | def test_start_container_with_binds_ro(self):
method test_start_container_with_binds_rw (line 76) | def test_start_container_with_binds_rw(self):
method test_start_container_with_port_binds (line 84) | def test_start_container_with_port_binds(self):
method test_start_container_with_links (line 97) | def test_start_container_with_links(self):
method test_start_container_with_multiple_links (line 103) | def test_start_container_with_multiple_links(self):
method test_start_container_with_links_as_list_of_tuples (line 113) | def test_start_container_with_links_as_list_of_tuples(self):
method test_start_container_privileged (line 118) | def test_start_container_privileged(self):
method test_start_container_with_dict_instead_of_id (line 122) | def test_start_container_with_dict_instead_of_id(self):
class CreateContainerTest (line 132) | class CreateContainerTest(BaseAPIClientTest):
method test_create_container (line 133) | def test_create_container(self):
method test_create_container_with_binds (line 147) | def test_create_container_with_binds(self):
method test_create_container_with_volume_string (line 166) | def test_create_container_with_volume_string(self):
method test_create_container_with_ports (line 185) | def test_create_container_with_ports(self):
method test_create_container_with_entrypoint (line 206) | def test_create_container_with_entrypoint(self):
method test_create_container_with_host_config_cpu_shares (line 223) | def test_create_container_with_host_config_cpu_shares(self):
method test_create_container_with_host_config_cpuset (line 247) | def test_create_container_with_host_config_cpuset(self):
method test_create_container_with_host_config_cpuset_mems (line 271) | def test_create_container_with_host_config_cpuset_mems(self):
method test_create_container_with_cgroup_parent (line 295) | def test_create_container_with_cgroup_parent(self):
method test_create_container_with_working_dir (line 309) | def test_create_container_with_working_dir(self):
method test_create_container_with_stdin_open (line 326) | def test_create_container_with_stdin_open(self):
method test_create_named_container (line 340) | def test_create_named_container(self):
method test_create_container_with_platform (line 356) | def test_create_container_with_platform(self):
method test_create_container_with_mem_limit_as_int (line 372) | def test_create_container_with_mem_limit_as_int(self):
method test_create_container_with_mem_limit_as_string (line 383) | def test_create_container_with_mem_limit_as_string(self):
method test_create_container_with_mem_limit_as_string_with_k_unit (line 394) | def test_create_container_with_mem_limit_as_string_with_k_unit(self):
method test_create_container_with_mem_limit_as_string_with_m_unit (line 405) | def test_create_container_with_mem_limit_as_string_with_m_unit(self):
method test_create_container_with_mem_limit_as_string_with_g_unit (line 416) | def test_create_container_with_mem_limit_as_string_with_g_unit(self):
method test_create_container_with_mem_limit_as_string_with_wrong_value (line 427) | def test_create_container_with_mem_limit_as_string_with_wrong_value(se...
method test_create_container_with_lxc_conf (line 434) | def test_create_container_with_lxc_conf(self):
method test_create_container_with_lxc_conf_compat (line 453) | def test_create_container_with_lxc_conf_compat(self):
method test_create_container_with_binds_ro (line 471) | def test_create_container_with_binds_ro(self):
method test_create_container_with_binds_rw (line 493) | def test_create_container_with_binds_rw(self):
method test_create_container_with_binds_mode (line 515) | def test_create_container_with_binds_mode(self):
method test_create_container_with_binds_mode_and_ro_error (line 537) | def test_create_container_with_binds_mode_and_ro_error(self):
method test_create_container_with_binds_list (line 551) | def test_create_container_with_binds_list(self):
method test_create_container_with_port_binds (line 573) | def test_create_container_with_port_binds(self):
method test_create_container_with_mac_address (line 616) | def test_create_container_with_mac_address(self):
method test_create_container_with_links (line 630) | def test_create_container_with_links(self):
method test_create_container_with_multiple_links (line 649) | def test_create_container_with_multiple_links(self):
method test_create_container_with_links_as_list_of_tuples (line 672) | def test_create_container_with_links_as_list_of_tuples(self):
method test_create_container_privileged (line 691) | def test_create_container_privileged(self):
method test_create_container_with_restart_policy (line 706) | def test_create_container_with_restart_policy(self):
method test_create_container_with_added_capabilities (line 729) | def test_create_container_with_added_capabilities(self):
method test_create_container_with_dropped_capabilities (line 744) | def test_create_container_with_dropped_capabilities(self):
method test_create_container_with_devices (line 759) | def test_create_container_with_devices(self):
method test_create_container_with_device_requests (line 787) | def test_create_container_with_device_requests(self):
method test_create_container_with_labels_dict (line 848) | def test_create_container_with_labels_dict(self):
method test_create_container_with_labels_list (line 865) | def test_create_container_with_labels_list(self):
method test_create_container_with_named_volume (line 886) | def test_create_container_with_named_volume(self):
method test_create_container_with_stop_signal (line 910) | def test_create_container_with_stop_signal(self):
method test_create_container_with_aliases (line 928) | def test_create_container_with_aliases(self):
method test_create_container_with_tmpfs_list (line 960) | def test_create_container_with_tmpfs_list(self):
method test_create_container_with_tmpfs_dict (line 984) | def test_create_container_with_tmpfs_dict(self):
method test_create_container_with_sysctl (line 1008) | def test_create_container_with_sysctl(self):
method test_create_container_with_unicode_envvars (line 1030) | def test_create_container_with_unicode_envvars(self):
method test_create_container_with_host_config_cpus (line 1049) | def test_create_container_with_host_config_cpus(self):
method test_create_container_with_cgroupns (line 1078) | def test_create_container_with_cgroupns(self):
class ContainerTest (line 1097) | class ContainerTest(BaseAPIClientTest):
method test_list_containers (line 1098) | def test_list_containers(self):
method test_resize_container (line 1115) | def test_resize_container(self):
method test_rename_container (line 1130) | def test_rename_container(self):
method test_wait (line 1144) | def test_wait(self):
method test_wait_with_dict_instead_of_id (line 1154) | def test_wait_with_dict_instead_of_id(self):
method test_logs (line 1164) | def test_logs(self):
method test_logs_with_dict_instead_of_id (line 1180) | def test_logs_with_dict_instead_of_id(self):
method test_log_streaming (line 1196) | def test_log_streaming(self):
method test_log_following (line 1211) | def test_log_following(self):
method test_log_following_backwards (line 1226) | def test_log_following_backwards(self):
method test_log_streaming_and_following (line 1240) | def test_log_streaming_and_following(self):
method test_log_tail (line 1255) | def test_log_tail(self):
method test_log_since (line 1271) | def test_log_since(self):
method test_log_since_with_float (line 1287) | def test_log_since_with_float(self):
method test_log_since_with_datetime (line 1303) | def test_log_since_with_datetime(self):
method test_log_since_with_invalid_value_raises_error (line 1320) | def test_log_since_with_invalid_value_raises_error(self):
method test_log_tty (line 1327) | def test_log_tty(self):
method test_diff (line 1346) | def test_diff(self):
method test_diff_with_dict_instead_of_id (line 1356) | def test_diff_with_dict_instead_of_id(self):
method test_port (line 1366) | def test_port(self):
method test_stop_container (line 1375) | def test_stop_container(self):
method test_stop_container_with_dict_instead_of_id (line 1387) | def test_stop_container_with_dict_instead_of_id(self):
method test_pause_container (line 1400) | def test_pause_container(self):
method test_unpause_container (line 1410) | def test_unpause_container(self):
method test_kill_container (line 1420) | def test_kill_container(self):
method test_kill_container_with_dict_instead_of_id (line 1430) | def test_kill_container_with_dict_instead_of_id(self):
method test_kill_container_with_signal (line 1440) | def test_kill_container_with_signal(self):
method test_restart_container (line 1450) | def test_restart_container(self):
method test_restart_container_with_dict_instead_of_id (line 1461) | def test_restart_container_with_dict_instead_of_id(self):
method test_remove_container (line 1472) | def test_remove_container(self):
method test_remove_container_with_dict_instead_of_id (line 1482) | def test_remove_container_with_dict_instead_of_id(self):
method test_export (line 1492) | def test_export(self):
method test_export_with_dict_instead_of_id (line 1503) | def test_export_with_dict_instead_of_id(self):
method test_inspect_container (line 1514) | def test_inspect_container(self):
method test_inspect_container_undefined_id (line 1523) | def test_inspect_container_undefined_id(self):
method test_container_stats (line 1530) | def test_container_stats(self):
method test_container_stats_without_streaming (line 1541) | def test_container_stats_without_streaming(self):
method test_container_stats_with_one_shot (line 1551) | def test_container_stats_with_one_shot(self):
method test_container_top (line 1562) | def test_container_top(self):
method test_container_top_with_psargs (line 1572) | def test_container_top_with_psargs(self):
method test_container_update (line 1583) | def test_container_update(self):
FILE: tests/unit/api_exec_test.py
class ExecTest (line 12) | class ExecTest(BaseAPIClientTest):
method test_exec_create (line 13) | def test_exec_create(self):
method test_exec_start (line 34) | def test_exec_start(self):
method test_exec_start_detached (line 51) | def test_exec_start_detached(self):
method test_exec_inspect (line 66) | def test_exec_inspect(self):
method test_exec_resize (line 72) | def test_exec_resize(self):
FILE: tests/unit/api_image_test.py
class ImageTest (line 18) | class ImageTest(BaseAPIClientTest):
method test_image_viz (line 19) | def test_image_viz(self):
method test_images (line 24) | def test_images(self):
method test_images_name (line 34) | def test_images_name(self):
method test_images_quiet (line 45) | def test_images_quiet(self):
method test_image_ids (line 55) | def test_image_ids(self):
method test_images_filters (line 65) | def test_images_filters(self):
method test_pull (line 76) | def test_pull(self):
method test_pull_stream (line 86) | def test_pull_stream(self):
method test_commit (line 96) | def test_commit(self):
method test_remove_image (line 116) | def test_remove_image(self):
method test_image_history (line 126) | def test_image_history(self):
method test_import_image (line 135) | def test_import_image(self):
method test_import_image_from_bytes (line 154) | def test_import_image_from_bytes(self):
method test_import_image_from_image (line 178) | def test_import_image_from_image(self):
method test_inspect_image (line 197) | def test_inspect_image(self):
method test_inspect_image_undefined_id (line 206) | def test_inspect_image_undefined_id(self):
method test_push_image (line 213) | def test_push_image(self):
method test_push_image_with_tag (line 230) | def test_push_image_with_tag(self):
method test_push_image_with_auth (line 249) | def test_push_image_with_auth(self):
method test_push_image_stream (line 274) | def test_push_image_stream(self):
method test_tag_image (line 291) | def test_tag_image(self):
method test_tag_image_tag (line 305) | def test_tag_image_tag(self):
method test_tag_image_force (line 323) | def test_tag_image_force(self):
method test_get_image (line 338) | def test_get_image(self):
method test_load_image (line 348) | def test_load_image(self):
method test_load_image_quiet (line 360) | def test_load_image_quiet(self):
FILE: tests/unit/api_network_test.py
class NetworkTest (line 9) | class NetworkTest(BaseAPIClientTest):
method test_list_networks (line 10) | def test_list_networks(self):
method test_create_network (line 45) | def test_create_network(self):
method test_remove_network (line 93) | def test_remove_network(self):
method test_inspect_network (line 103) | def test_inspect_network(self):
method test_connect_container_to_network (line 123) | def test_connect_container_to_network(self):
method test_disconnect_container_from_network (line 151) | def test_disconnect_container_from_network(self):
FILE: tests/unit/api_test.py
function response (line 30) | def response(status_code=200, content='', headers=None, reason=None, ela...
function fake_resolve_authconfig (line 45) | def fake_resolve_authconfig(authconfig, registry=None, *args, **kwargs):
function fake_inspect_container (line 49) | def fake_inspect_container(self, container, tty=False):
function fake_resp (line 53) | def fake_resp(method, url, *args, **kwargs):
function fake_get (line 68) | def fake_get(self, url, *args, **kwargs):
function fake_post (line 72) | def fake_post(self, url, *args, **kwargs):
function fake_put (line 76) | def fake_put(self, url, *args, **kwargs):
function fake_delete (line 80) | def fake_delete(self, url, *args, **kwargs):
function fake_read_from_socket (line 84) | def fake_read_from_socket(self, response, stream, tty=False, demux=False):
class BaseAPIClientTest (line 92) | class BaseAPIClientTest(unittest.TestCase):
method setUp (line 93) | def setUp(self):
method tearDown (line 105) | def tearDown(self):
method base_create_payload (line 109) | def base_create_payload(self, img='busybox', cmd=None):
class DockerApiTest (line 120) | class DockerApiTest(BaseAPIClientTest):
method test_ctor (line 121) | def test_ctor(self):
method test_url_valid_resource (line 129) | def test_url_valid_resource(self):
method test_url_invalid_resource (line 144) | def test_url_invalid_resource(self):
method test_url_no_resource (line 148) | def test_url_no_resource(self):
method test_url_unversioned_api (line 152) | def test_url_unversioned_api(self):
method test_version (line 158) | def test_version(self):
method test_version_no_api_version (line 167) | def test_version_no_api_version(self):
method test_retrieve_server_version (line 176) | def test_retrieve_server_version(self):
method test_auto_retrieve_server_version (line 182) | def test_auto_retrieve_server_version(self):
method test_info (line 186) | def test_info(self):
method test_search (line 195) | def test_search(self):
method test_login (line 205) | def test_login(self):
method test_events (line 221) | def test_events(self):
method test_events_with_since_until (line 232) | def test_events_with_since_until(self):
method test_events_with_filters (line 252) | def test_events_with_filters(self):
method _socket_path_for_client_session (line 271) | def _socket_path_for_client_session(self, client):
method test_url_compatibility_unix (line 275) | def test_url_compatibility_unix(self):
method test_url_compatibility_unix_triple_slash (line 282) | def test_url_compatibility_unix_triple_slash(self):
method test_url_compatibility_http_unix_triple_slash (line 289) | def test_url_compatibility_http_unix_triple_slash(self):
method test_url_compatibility_http (line 296) | def test_url_compatibility_http(self):
method test_url_compatibility_tcp (line 303) | def test_url_compatibility_tcp(self):
method test_remove_link (line 310) | def test_remove_link(self):
method test_create_host_config_secopt (line 320) | def test_create_host_config_secopt(self):
method test_stream_helper_decoding (line 328) | def test_stream_helper_decoding(self):
class UnixSocketStreamTest (line 365) | class UnixSocketStreamTest(unittest.TestCase):
method setUp (line 366) | def setUp(self):
method stop (line 382) | def stop(self):
method _setup_socket (line 385) | def _setup_socket(self):
method run_server (line 393) | def run_server(self):
method early_response_sending_handler (line 411) | def early_response_sending_handler(self, connection):
method test_early_stream_response (line 435) | def test_early_stream_response(self):
class TCPSocketStreamTest (line 468) | class TCPSocketStreamTest(unittest.TestCase):
method setup_class (line 481) | def setup_class(cls):
method teardown_class (line 490) | def teardown_class(cls):
method get_handler_class (line 496) | def get_handler_class(cls):
method request (line 534) | def request(self, stream=None, tty=None, demux=None):
method test_read_from_socket_tty (line 548) | def test_read_from_socket_tty(self):
method test_read_from_socket_tty_demux (line 554) | def test_read_from_socket_tty_demux(self):
method test_read_from_socket_no_tty (line 560) | def test_read_from_socket_no_tty(self):
method test_read_from_socket_no_tty_demux (line 567) | def test_read_from_socket_no_tty_demux(self):
method test_read_from_socket_no_stream_tty (line 574) | def test_read_from_socket_no_stream_tty(self):
method test_read_from_socket_no_stream_tty_demux (line 578) | def test_read_from_socket_no_stream_tty_demux(self):
method test_read_from_socket_no_stream_no_tty (line 582) | def test_read_from_socket_no_stream_no_tty(self):
method test_read_from_socket_no_stream_no_tty_demux (line 586) | def test_read_from_socket_no_stream_no_tty_demux(self):
class UserAgentTest (line 591) | class UserAgentTest(unittest.TestCase):
method setUp (line 592) | def setUp(self):
method tearDown (line 600) | def tearDown(self):
method test_default_user_agent (line 603) | def test_default_user_agent(self):
method test_custom_user_agent (line 612) | def test_custom_user_agent(self):
class DisableSocketTest (line 623) | class DisableSocketTest(unittest.TestCase):
class DummySocket (line 624) | class DummySocket:
method __init__ (line 625) | def __init__(self, timeout=60):
method settimeout (line 628) | def settimeout(self, timeout):
method gettimeout (line 631) | def gettimeout(self):
method setUp (line 634) | def setUp(self):
method test_disable_socket_timeout (line 637) | def test_disable_socket_timeout(self):
method test_disable_socket_timeout2 (line 645) | def test_disable_socket_timeout2(self):
method test_disable_socket_timout_non_blocking (line 656) | def test_disable_socket_timout_non_blocking(self):
FILE: tests/unit/api_volume_test.py
class VolumeTest (line 9) | class VolumeTest(BaseAPIClientTest):
method test_list_volumes (line 10) | def test_list_volumes(self):
method test_list_volumes_and_filters (line 19) | def test_list_volumes_and_filters(self):
method test_create_volume (line 30) | def test_create_volume(self):
method test_create_volume_with_labels (line 44) | def test_create_volume_with_labels(self):
method test_create_volume_with_invalid_labels (line 54) | def test_create_volume_with_invalid_labels(self):
method test_create_volume_with_driver (line 59) | def test_create_volume_with_driver(self):
method test_create_volume_invalid_opts_type (line 71) | def test_create_volume_invalid_opts_type(self):
method test_create_volume_with_no_specified_name (line 88) | def test_create_volume_with_no_specified_name(self):
method test_inspect_volume (line 97) | def test_inspect_volume(self):
method test_remove_volume (line 109) | def test_remove_volume(self):
FILE: tests/unit/auth_test.py
class RegressionTest (line 16) | class RegressionTest(unittest.TestCase):
method test_803_urlsafe_encode (line 17) | def test_803_urlsafe_encode(self):
class ResolveRepositoryNameTest (line 27) | class ResolveRepositoryNameTest(unittest.TestCase):
method test_resolve_repository_name_hub_library_image (line 28) | def test_resolve_repository_name_hub_library_image(self):
method test_resolve_repository_name_dotted_hub_library_image (line 33) | def test_resolve_repository_name_dotted_hub_library_image(self):
method test_resolve_repository_name_hub_image (line 38) | def test_resolve_repository_name_hub_image(self):
method test_explicit_hub_index_library_image (line 43) | def test_explicit_hub_index_library_image(self):
method test_explicit_legacy_hub_index_library_image (line 48) | def test_explicit_legacy_hub_index_library_image(self):
method test_resolve_repository_name_private_registry (line 53) | def test_resolve_repository_name_private_registry(self):
method test_resolve_repository_name_private_registry_with_port (line 58) | def test_resolve_repository_name_private_registry_with_port(self):
method test_resolve_repository_name_private_registry_with_username (line 63) | def test_resolve_repository_name_private_registry_with_username(self):
method test_resolve_repository_name_no_dots_but_port (line 68) | def test_resolve_repository_name_no_dots_but_port(self):
method test_resolve_repository_name_no_dots_but_port_and_username (line 73) | def test_resolve_repository_name_no_dots_but_port_and_username(self):
method test_resolve_repository_name_localhost (line 78) | def test_resolve_repository_name_localhost(self):
method test_resolve_repository_name_localhost_with_username (line 83) | def test_resolve_repository_name_localhost_with_username(self):
method test_invalid_index_name (line 88) | def test_invalid_index_name(self):
function encode_auth (line 93) | def encode_auth(auth_info):
class ResolveAuthTest (line 99) | class ResolveAuthTest(unittest.TestCase):
method test_resolve_authconfig_hostname_only (line 112) | def test_resolve_authconfig_hostname_only(self):
method test_resolve_authconfig_no_protocol (line 117) | def test_resolve_authconfig_no_protocol(self):
method test_resolve_authconfig_no_path (line 122) | def test_resolve_authconfig_no_path(self):
method test_resolve_authconfig_no_path_trailing_slash (line 127) | def test_resolve_authconfig_no_path_trailing_slash(self):
method test_resolve_authconfig_no_path_wrong_secure_proto (line 132) | def test_resolve_authconfig_no_path_wrong_secure_proto(self):
method test_resolve_authconfig_no_path_wrong_insecure_proto (line 137) | def test_resolve_authconfig_no_path_wrong_insecure_proto(self):
method test_resolve_authconfig_path_wrong_proto (line 142) | def test_resolve_authconfig_path_wrong_proto(self):
method test_resolve_authconfig_default_registry (line 147) | def test_resolve_authconfig_default_registry(self):
method test_resolve_authconfig_default_explicit_none (line 152) | def test_resolve_authconfig_default_explicit_none(self):
method test_resolve_authconfig_fully_explicit (line 157) | def test_resolve_authconfig_fully_explicit(self):
method test_resolve_authconfig_legacy_config (line 162) | def test_resolve_authconfig_legacy_config(self):
method test_resolve_authconfig_no_match (line 167) | def test_resolve_authconfig_no_match(self):
method test_resolve_registry_and_auth_library_image (line 172) | def test_resolve_registry_and_auth_library_image(self):
method test_resolve_registry_and_auth_hub_image (line 178) | def test_resolve_registry_and_auth_hub_image(self):
method test_resolve_registry_and_auth_explicit_hub (line 184) | def test_resolve_registry_and_auth_explicit_hub(self):
method test_resolve_registry_and_auth_explicit_legacy_hub (line 190) | def test_resolve_registry_and_auth_explicit_legacy_hub(self):
method test_resolve_registry_and_auth_private_registry (line 196) | def test_resolve_registry_and_auth_private_registry(self):
method test_resolve_registry_and_auth_unauthenticated_registry (line 202) | def test_resolve_registry_and_auth_unauthenticated_registry(self):
method test_resolve_auth_with_empty_credstore_and_auth_dict (line 208) | def test_resolve_auth_with_empty_credstore_and_auth_dict(self):
class LoadConfigTest (line 224) | class LoadConfigTest(unittest.TestCase):
method test_load_config_no_file (line 225) | def test_load_config_no_file(self):
method test_load_legacy_config (line 231) | def test_load_legacy_config(self):
method test_load_json_config (line 249) | def test_load_json_config(self):
method test_load_modern_json_config (line 268) | def test_load_modern_json_config(self):
method test_load_config_with_random_name (line 290) | def test_load_config_with_random_name(self):
method test_load_config_custom_config_env (line 319) | def test_load_config_custom_config_env(self):
method test_load_config_custom_config_env_with_auths (line 346) | def test_load_config_custom_config_env_with_auths(self):
method test_load_config_custom_config_env_utf8 (line 374) | def test_load_config_custom_config_env_utf8(self):
method test_load_config_unknown_keys (line 403) | def test_load_config_unknown_keys(self):
method test_load_config_invalid_auth_dict (line 416) | def test_load_config_invalid_auth_dict(self):
method test_load_config_identity_token (line 431) | def test_load_config_identity_token(self):
class CredstoreTest (line 456) | class CredstoreTest(unittest.TestCase):
method setUp (line 457) | def setUp(self):
method test_get_credential_store (line 468) | def test_get_credential_store(self):
method test_get_credential_store_no_default (line 481) | def test_get_credential_store_no_default(self):
method test_get_credential_store_default_index (line 491) | def test_get_credential_store_default_index(self):
method test_get_credential_store_with_plain_dict (line 503) | def test_get_credential_store_with_plain_dict(self):
method test_get_all_credentials_credstore_only (line 522) | def test_get_all_credentials_credstore_only(self):
method test_get_all_credentials_with_empty_credhelper (line 546) | def test_get_all_credentials_with_empty_credhelper(self):
method test_get_all_credentials_with_credhelpers_only (line 575) | def test_get_all_credentials_with_credhelpers_only(self):
method test_get_all_credentials_with_auths_entries (line 607) | def test_get_all_credentials_with_auths_entries(self):
method test_get_all_credentials_with_empty_auths_entry (line 642) | def test_get_all_credentials_with_empty_auths_entry(self):
method test_get_all_credentials_credstore_overrides_auth_entry (line 668) | def test_get_all_credentials_credstore_overrides_auth_entry(self):
method test_get_all_credentials_helpers_override_default (line 698) | def test_get_all_credentials_helpers_override_default(self):
method test_get_all_credentials_3_sources (line 728) | def test_get_all_credentials_3_sources(self):
class InMemoryStore (line 775) | class InMemoryStore(credentials.Store):
method __init__ (line 776) | def __init__(self, *args, **kwargs):
method get (line 779) | def get(self, server):
method store (line 785) | def store(self, server, username, secret):
method list (line 792) | def list(self):
method erase (line 797) | def erase(self, server):
FILE: tests/unit/client_test.py
class ClientTest (line 23) | class ClientTest(unittest.TestCase):
method test_events (line 26) | def test_events(self, mock_func):
method test_info (line 34) | def test_info(self, mock_func):
method test_ping (line 41) | def test_ping(self, mock_func):
method test_version (line 48) | def test_version(self, mock_func):
method test_call_api_client_method (line 54) | def test_call_api_client_method(self):
method test_call_containers (line 68) | def test_call_containers(self):
method test_default_pool_size_unix (line 84) | def test_default_pool_size_unix(self, mock_obj):
method test_default_pool_size_win (line 103) | def test_default_pool_size_win(self, mock_obj):
method test_pool_size_unix (line 119) | def test_pool_size_unix(self, mock_obj):
method test_pool_size_win (line 139) | def test_pool_size_win(self, mock_obj):
class FromEnvTest (line 153) | class FromEnvTest(unittest.TestCase):
method setUp (line 155) | def setUp(self):
method tearDown (line 158) | def tearDown(self):
method test_from_env (line 162) | def test_from_env(self):
method test_from_env_with_version (line 172) | def test_from_env_with_version(self):
method test_from_env_without_version_uses_default (line 180) | def test_from_env_without_version_uses_default(self):
method test_from_env_without_timeout_uses_default (line 185) | def test_from_env_without_timeout_uses_default(self):
method test_default_pool_size_from_env_unix (line 195) | def test_default_pool_size_from_env_unix(self, mock_obj):
method test_default_pool_size_from_env_win (line 212) | def test_default_pool_size_from_env_win(self, mock_obj):
method test_pool_size_from_env_unix (line 227) | def test_pool_size_from_env_unix(self, mock_obj):
method test_pool_size_from_env_win (line 247) | def test_pool_size_from_env_win(self, mock_obj):
FILE: tests/unit/context_test.py
class BaseContextTest (line 10) | class BaseContextTest(unittest.TestCase):
method test_url_compatibility_on_linux (line 14) | def test_url_compatibility_on_linux(self):
method test_url_compatibility_on_windows (line 21) | def test_url_compatibility_on_windows(self):
method test_fail_on_default_context_create (line 25) | def test_fail_on_default_context_create(self):
method test_default_in_context_list (line 29) | def test_default_in_context_list(self):
method test_get_current_context (line 37) | def test_get_current_context(self):
method test_https_host (line 40) | def test_https_host(self):
method test_context_inspect_without_params (line 44) | def test_context_inspect_without_params(self):
FILE: tests/unit/dockertypes_test.py
function create_host_config (line 22) | def create_host_config(*args, **kwargs):
class HostConfigTest (line 26) | class HostConfigTest(unittest.TestCase):
method test_create_host_config_no_options_newer_api_version (line 27) | def test_create_host_config_no_options_newer_api_version(self):
method test_create_host_config_invalid_cpu_cfs_types (line 31) | def test_create_host_config_invalid_cpu_cfs_types(self):
method test_create_host_config_with_cpu_quota (line 44) | def test_create_host_config_with_cpu_quota(self):
method test_create_host_config_with_cpu_period (line 48) | def test_create_host_config_with_cpu_period(self):
method test_create_host_config_with_blkio_constraints (line 52) | def test_create_host_config_with_blkio_constraints(self):
method test_create_host_config_with_shm_size (line 69) | def test_create_host_config_with_shm_size(self):
method test_create_host_config_with_shm_size_in_mb (line 73) | def test_create_host_config_with_shm_size_in_mb(self):
method test_create_host_config_with_oom_kill_disable (line 77) | def test_create_host_config_with_oom_kill_disable(self):
method test_create_host_config_with_userns_mode (line 81) | def test_create_host_config_with_userns_mode(self):
method test_create_host_config_with_uts (line 89) | def test_create_host_config_with_uts(self):
method test_create_host_config_with_oom_score_adj (line 95) | def test_create_host_config_with_oom_score_adj(self):
method test_create_host_config_with_dns_opt (line 103) | def test_create_host_config_with_dns_opt(self):
method test_create_host_config_with_mem_reservation (line 112) | def test_create_host_config_with_mem_reservation(self):
method test_create_host_config_with_kernel_memory (line 116) | def test_create_host_config_with_kernel_memory(self):
method test_create_host_config_with_pids_limit (line 120) | def test_create_host_config_with_pids_limit(self):
method test_create_host_config_with_isolation (line 129) | def test_create_host_config_with_isolation(self):
method test_create_host_config_pid_mode (line 140) | def test_create_host_config_pid_mode(self):
method test_create_host_config_invalid_mem_swappiness (line 149) | def test_create_host_config_invalid_mem_swappiness(self):
method test_create_host_config_with_volume_driver (line 153) | def test_create_host_config_with_volume_driver(self):
method test_create_host_config_invalid_cpu_count_types (line 157) | def test_create_host_config_invalid_cpu_count_types(self):
method test_create_host_config_with_cpu_count (line 161) | def test_create_host_config_with_cpu_count(self):
method test_create_host_config_invalid_cpu_percent_types (line 167) | def test_create_host_config_invalid_cpu_percent_types(self):
method test_create_host_config_with_cpu_percent (line 171) | def test_create_host_config_with_cpu_percent(self):
method test_create_host_config_invalid_nano_cpus_types (line 177) | def test_create_host_config_invalid_nano_cpus_types(self):
method test_create_host_config_with_nano_cpus (line 181) | def test_create_host_config_with_nano_cpus(self):
method test_create_host_config_with_cpu_rt_period_types (line 187) | def test_create_host_config_with_cpu_rt_period_types(self):
method test_create_host_config_with_cpu_rt_period (line 191) | def test_create_host_config_with_cpu_rt_period(self):
method test_ctrate_host_config_with_cpu_rt_runtime_types (line 197) | def test_ctrate_host_config_with_cpu_rt_runtime_types(self):
method test_create_host_config_with_cpu_rt_runtime (line 201) | def test_create_host_config_with_cpu_rt_runtime(self):
class ContainerSpecTest (line 208) | class ContainerSpecTest(unittest.TestCase):
method test_parse_mounts (line 209) | def test_parse_mounts(self):
class UlimitTest (line 224) | class UlimitTest(unittest.TestCase):
method test_create_host_config_dict_ulimit (line 225) | def test_create_host_config_dict_ulimit(self):
method test_create_host_config_dict_ulimit_capitals (line 238) | def test_create_host_config_dict_ulimit_capitals(self):
method test_create_host_config_obj_ulimit (line 252) | def test_create_host_config_obj_ulimit(self):
method test_ulimit_invalid_type (line 263) | def test_ulimit_invalid_type(self):
class LogConfigTest (line 272) | class LogConfigTest(unittest.TestCase):
method test_create_host_config_dict_logconfig (line 273) | def test_create_host_config_dict_logconfig(self):
method test_create_host_config_obj_logconfig (line 282) | def test_create_host_config_obj_logconfig(self):
method test_logconfig_invalid_config_type (line 291) | def test_logconfig_invalid_config_type(self):
class EndpointConfigTest (line 296) | class EndpointConfigTest(unittest.TestCase):
method test_create_endpoint_config_with_aliases (line 297) | def test_create_endpoint_config_with_aliases(self):
class IPAMConfigTest (line 305) | class IPAMConfigTest(unittest.TestCase):
method test_create_ipam_config (line 306) | def test_create_ipam_config(self):
class ServiceModeTest (line 322) | class ServiceModeTest(unittest.TestCase):
method test_replicated_simple (line 323) | def test_replicated_simple(self):
method test_global_simple (line 329) | def test_global_simple(self):
method test_replicated_job_simple (line 335) | def test_replicated_job_simple(self):
method test_global_job_simple (line 341) | def test_global_job_simple(self):
method test_global_replicas_error (line 347) | def test_global_replicas_error(self):
method test_global_job_replicas_simple (line 351) | def test_global_job_replicas_simple(self):
method test_replicated_replicas (line 355) | def test_replicated_replicas(self):
method test_replicated_replicas_0 (line 361) | def test_replicated_replicas_0(self):
method test_invalid_mode (line 367) | def test_invalid_mode(self):
class MountTest (line 372) | class MountTest(unittest.TestCase):
method test_parse_mount_string_ro (line 373) | def test_parse_mount_string_ro(self):
method test_parse_mount_string_rw (line 379) | def test_parse_mount_string_rw(self):
method test_parse_mount_string_short_form (line 385) | def test_parse_mount_string_short_form(self):
method test_parse_mount_string_no_source (line 391) | def test_parse_mount_string_no_source(self):
method test_parse_mount_string_invalid (line 397) | def test_parse_mount_string_invalid(self):
method test_parse_mount_named_volume (line 401) | def test_parse_mount_named_volume(self):
method test_parse_mount_bind (line 407) | def test_parse_mount_bind(self):
method test_parse_mount_bind_windows (line 414) | def test_parse_mount_bind_windows(self):
class ServicePortsTest (line 422) | class ServicePortsTest(unittest.TestCase):
method test_convert_service_ports_simple (line 423) | def test_convert_service_ports_simple(self):
method test_convert_service_ports_with_protocol (line 431) | def test_convert_service_ports_with_protocol(self):
method test_convert_service_ports_with_protocol_and_mode (line 440) | def test_convert_service_ports_with_protocol_and_mode(self):
method test_convert_service_ports_invalid (line 450) | def test_convert_service_ports_invalid(self):
method test_convert_service_ports_no_protocol_and_mode (line 456) | def test_convert_service_ports_no_protocol_and_mode(self):
method test_convert_service_ports_multiple (line 466) | def test_convert_service_ports_multiple(self):
FILE: tests/unit/errors_test.py
class APIErrorTest (line 17) | class APIErrorTest(unittest.TestCase):
method test_api_error_is_caught_by_dockerexception (line 18) | def test_api_error_is_caught_by_dockerexception(self):
method test_status_code_200 (line 24) | def test_status_code_200(self):
method test_status_code_400 (line 31) | def test_status_code_400(self):
method test_status_code_500 (line 38) | def test_status_code_500(self):
method test_is_server_error_200 (line 45) | def test_is_server_error_200(self):
method test_is_server_error_300 (line 52) | def test_is_server_error_300(self):
method test_is_server_error_400 (line 59) | def test_is_server_error_400(self):
method test_is_server_error_500 (line 66) | def test_is_server_error_500(self):
method test_is_client_error_500 (line 73) | def test_is_client_error_500(self):
method test_is_client_error_400 (line 80) | def test_is_client_error_400(self):
method test_is_error_300 (line 87) | def test_is_error_300(self):
method test_is_error_400 (line 94) | def test_is_error_400(self):
method test_is_error_500 (line 101) | def test_is_error_500(self):
method test_create_error_from_exception (line 108) | def test_create_error_from_exception(self):
class ContainerErrorTest (line 122) | class ContainerErrorTest(unittest.TestCase):
method test_container_without_stderr (line 123) | def test_container_without_stderr(self):
method test_container_with_stderr (line 137) | def test_container_with_stderr(self):
class CreateUnexpectedKwargsErrorTest (line 152) | class CreateUnexpectedKwargsErrorTest(unittest.TestCase):
method test_create_unexpected_kwargs_error_single (line 153) | def test_create_unexpected_kwargs_error_single(self):
method test_create_unexpected_kwargs_error_multiple (line 157) | def test_create_unexpected_kwargs_error_multiple(self):
FILE: tests/unit/fake_api.py
function get_fake_version (line 29) | def get_fake_version():
function get_fake_info (line 62) | def get_fake_info():
function post_fake_auth (line 70) | def post_fake_auth():
function get_fake_ping (line 77) | def get_fake_ping():
function get_fake_search (line 81) | def get_fake_search():
function get_fake_images (line 87) | def get_fake_images():
function get_fake_image_history (line 98) | def get_fake_image_history():
function get_fake_containers (line 116) | def get_fake_containers():
function post_fake_start_container (line 128) | def post_fake_start_container():
function post_fake_resize_container (line 134) | def post_fake_resize_container():
function post_fake_create_container (line 140) | def post_fake_create_container():
function get_fake_inspect_container (line 146) | def get_fake_inspect_container(tty=False):
function get_fake_inspect_image (line 173) | def get_fake_inspect_image():
function get_fake_insert_image (line 207) | def get_fake_insert_image():
function get_fake_wait (line 213) | def get_fake_wait():
function get_fake_logs (line 219) | def get_fake_logs():
function get_fake_diff (line 228) | def get_fake_diff():
function get_fake_events (line 234) | def get_fake_events():
function get_fake_export (line 241) | def get_fake_export():
function post_fake_exec_create (line 247) | def post_fake_exec_create():
function post_fake_exec_start (line 253) | def post_fake_exec_start():
function post_fake_exec_resize (line 261) | def post_fake_exec_resize():
function get_fake_exec_inspect (line 266) | def get_fake_exec_inspect():
function post_fake_stop_container (line 285) | def post_fake_stop_container():
function post_fake_kill_container (line 291) | def post_fake_kill_container():
function post_fake_pause_container (line 297) | def post_fake_pause_container():
function post_fake_unpause_container (line 303) | def post_fake_unpause_container():
function post_fake_restart_container (line 309) | def post_fake_restart_container():
function post_fake_rename_container (line 315) | def post_fake_rename_container():
function delete_fake_remove_container (line 320) | def delete_fake_remove_container():
function post_fake_image_create (line 326) | def post_fake_image_create():
function delete_fake_remove_image (line 332) | def delete_fake_remove_image():
function get_fake_get_image (line 338) | def get_fake_get_image():
function post_fake_load_image (line 344) | def post_fake_load_image():
function post_fake_commit (line 350) | def post_fake_commit():
function post_fake_push (line 356) | def post_fake_push():
function post_fake_build_container (line 362) | def post_fake_build_container():
function post_fake_tag_image (line 368) | def post_fake_tag_image():
function get_fake_stats (line 374) | def get_fake_stats():
function get_fake_top (line 380) | def get_fake_top():
function get_fake_volume_list (line 407) | def get_fake_volume_list():
function get_fake_volume (line 427) | def get_fake_volume():
function fake_remove_volume (line 441) | def fake_remove_volume():
function post_fake_update_container (line 445) | def post_fake_update_container():
function post_fake_update_node (line 449) | def post_fake_update_node():
function post_fake_join_swarm (line 453) | def post_fake_join_swarm():
function get_fake_network_list (line 457) | def get_fake_network_list():
function get_fake_network (line 492) | def get_fake_network():
function post_fake_network (line 496) | def post_fake_network():
function delete_fake_network (line 500) | def delete_fake_network():
function post_fake_network_connect (line 504) | def post_fake_network_connect():
function post_fake_network_disconnect (line 508) | def post_fake_network_disconnect():
function post_fake_secret (line 512) | def post_fake_secret():
function post_fake_config (line 517) | def post_fake_config():
FILE: tests/unit/fake_api_client.py
class CopyReturnMagicMock (line 10) | class CopyReturnMagicMock(mock.MagicMock):
method _mock_call (line 14) | def _mock_call(self, *args, **kwargs):
function make_fake_api_client (line 21) | def make_fake_api_client(overrides=None):
function make_fake_client (line 62) | def make_fake_client(overrides=None):
FILE: tests/unit/models_configs_test.py
class CreateConfigsTest (line 7) | class CreateConfigsTest(unittest.TestCase):
method test_create_config (line 8) | def test_create_config(self):
FILE: tests/unit/models_containers_test.py
class ContainerCollectionTest (line 15) | class ContainerCollectionTest(unittest.TestCase):
method test_run (line 16) | def test_run(self):
method test_create_container_args (line 36) | def test_create_container_args(self):
method test_run_detach (line 231) | def test_run_detach(self):
method test_run_pull (line 247) | def test_run_pull(self):
method test_run_with_error (line 263) | def test_run_with_error(self):
method test_run_with_image_object (line 273) | def test_run_with_image_object(self):
method test_run_remove (line 286) | def test_run_remove(self):
method test_run_platform (line 341) | def test_run_platform(self):
method test_run_networking_config_without_network (line 368) | def test_run_networking_config_without_network(self):
method test_run_networking_config_with_network_mode (line 378) | def test_run_networking_config_with_network_mode(self):
method test_run_networking_config (line 389) | def test_run_networking_config(self):
method test_run_networking_config_with_undeclared_network (line 415) | def test_run_networking_config_with_undeclared_network(self):
method test_run_networking_config_only_undeclared_network (line 446) | def test_run_networking_config_only_undeclared_network(self):
method test_create (line 470) | def test_create(self):
method test_create_with_image_object (line 487) | def test_create_with_image_object(self):
method test_create_networking_config_without_network (line 497) | def test_create_networking_config_without_network(self):
method test_create_networking_config_with_network_mode (line 512) | def test_create_networking_config_with_network_mode(self):
method test_create_networking_config (line 528) | def test_create_networking_config(self):
method test_create_networking_config_with_undeclared_network (line 553) | def test_create_networking_config_with_undeclared_network(self):
method test_create_networking_config_only_undeclared_network (line 583) | def test_create_networking_config_only_undeclared_network(self):
method test_get (line 606) | def test_get(self):
method test_list (line 613) | def test_list(self):
method test_list_ignore_removed (line 628) | def test_list_ignore_removed(self):
class ContainerTest (line 642) | class ContainerTest(unittest.TestCase):
method test_short_id (line 643) | def test_short_id(self):
method test_name (line 648) | def test_name(self):
method test_status (line 653) | def test_status(self):
method test_attach (line 658) | def test_attach(self):
method test_commit (line 664) | def test_commit(self):
method test_diff (line 674) | def test_diff(self):
method test_exec_run (line 680) | def test_exec_run(self):
method test_exec_run_failure (line 694) | def test_exec_run_failure(self):
method test_export (line 708) | def test_export(self):
method test_get_archive (line 716) | def test_get_archive(self):
method test_image (line 724) | def test_image(self):
method test_kill (line 729) | def test_kill(self):
method test_labels (line 735) | def test_labels(self):
method test_logs (line 740) | def test_logs(self):
method test_pause (line 746) | def test_pause(self):
method test_put_archive (line 752) | def test_put_archive(self):
method test_remove (line 759) | def test_remove(self):
method test_rename (line 765) | def test_rename(self):
method test_resize (line 771) | def test_resize(self):
method test_restart (line 777) | def test_restart(self):
method test_start (line 783) | def test_start(self):
method test_stats (line 789) | def test_stats(self):
method test_stop (line 795) | def test_stop(self):
method test_top (line 801) | def test_top(self):
method test_unpause (line 807) | def test_unpause(self):
method test_update (line 813) | def test_update(self):
method test_wait (line 820) | def test_wait(self):
FILE: tests/unit/models_images_test.py
class ImageCollectionTest (line 11) | class ImageCollectionTest(unittest.TestCase):
method test_build (line 12) | def test_build(self):
method test_get (line 20) | def test_get(self):
method test_labels (line 27) | def test_labels(self):
method test_list (line 32) | def test_list(self):
method test_load (line 40) | def test_load(self):
method test_pull (line 45) | def test_pull(self):
method test_pull_tag_precedence (line 55) | def test_pull_tag_precedence(self):
method test_pull_multiple (line 71) | def test_pull_multiple(self):
method test_pull_with_stream_param (line 86) | def test_pull_with_stream_param(self):
method test_push (line 96) | def test_push(self):
method test_remove (line 105) | def test_remove(self):
method test_search (line 110) | def test_search(self):
method test_search_limit (line 115) | def test_search_limit(self):
class ImageTest (line 121) | class ImageTest(unittest.TestCase):
method test_short_id (line 122) | def test_short_id(self):
method test_tags (line 131) | def test_tags(self):
method test_history (line 147) | def test_history(self):
method test_remove (line 153) | def test_remove(self):
method test_save (line 163) | def test_save(self):
method test_tag (line 171) | def test_tag(self):
FILE: tests/unit/models_networks_test.py
class NetworkCollectionTest (line 7) | class NetworkCollectionTest(unittest.TestCase):
method test_create (line 9) | def test_create(self):
method test_get (line 19) | def test_get(self):
method test_list (line 25) | def test_list(self):
class NetworkTest (line 40) | class NetworkTest(unittest.TestCase):
method test_connect (line 42) | def test_connect(self):
method test_disconnect (line 51) | def test_disconnect(self):
method test_remove (line 60) | def test_remove(self):
FILE: tests/unit/models_resources_test.py
class ModelTest (line 7) | class ModelTest(unittest.TestCase):
method test_reload (line 8) | def test_reload(self):
method test_hash (line 16) | def test_hash(self):
FILE: tests/unit/models_secrets_test.py
class CreateServiceTest (line 7) | class CreateServiceTest(unittest.TestCase):
method test_secrets_repr (line 8) | def test_secrets_repr(self):
FILE: tests/unit/models_services_test.py
class CreateServiceKwargsTest (line 6) | class CreateServiceKwargsTest(unittest.TestCase):
method test_get_create_service_kwargs (line 7) | def test_get_create_service_kwargs(self):
FILE: tests/unit/sshadapter_test.py
class SSHAdapterTest (line 7) | class SSHAdapterTest(unittest.TestCase):
method test_ssh_hostname_prefix_trim (line 9) | def test_ssh_hostname_prefix_trim():
method test_ssh_parse_url (line 15) | def test_ssh_parse_url():
method test_ssh_parse_hostname_only (line 22) | def test_ssh_parse_hostname_only():
method test_ssh_parse_user_and_hostname (line 29) | def test_ssh_parse_user_and_hostname():
method test_ssh_parse_hostname_and_port (line 36) | def test_ssh_parse_hostname_and_port():
FILE: tests/unit/swarm_test.py
class SwarmTest (line 8) | class SwarmTest(BaseAPIClientTest):
method test_node_update (line 10) | def test_node_update(self):
method test_join_swarm (line 29) | def test_join_swarm(self):
method test_join_swarm_no_listen_address_takes_default (line 53) | def test_join_swarm_no_listen_address_takes_default(self):
FILE: tests/unit/types_containers_test.py
function test_uid_0_is_not_elided (line 4) | def test_uid_0_is_not_elided():
FILE: tests/unit/utils_build_test.py
function convert_paths (line 17) | def convert_paths(collection):
function convert_path (line 21) | def convert_path(path):
class ExcludePathsTest (line 25) | class ExcludePathsTest(unittest.TestCase):
method setUp (line 65) | def setUp(self):
method tearDown (line 68) | def tearDown(self):
method exclude (line 71) | def exclude(self, patterns, dockerfile=None):
method test_no_excludes (line 74) | def test_no_excludes(self):
method test_no_dupes (line 77) | def test_no_dupes(self):
method test_wildcard_exclude (line 81) | def test_wildcard_exclude(self):
method test_exclude_dockerfile_dockerignore (line 84) | def test_exclude_dockerfile_dockerignore(self):
method test_exclude_custom_dockerfile (line 94) | def test_exclude_custom_dockerfile(self):
method test_exclude_dockerfile_child (line 112) | def test_exclude_dockerfile_child(self):
method test_single_filename (line 117) | def test_single_filename(self):
method test_single_filename_leading_dot_slash (line 122) | def test_single_filename_leading_dot_slash(self):
method test_single_filename_trailing_slash (line 129) | def test_single_filename_trailing_slash(self):
method test_wildcard_filename_start (line 134) | def test_wildcard_filename_start(self):
method test_wildcard_with_exception (line 139) | def test_wildcard_with_exception(self):
method test_wildcard_with_wildcard_exception (line 144) | def test_wildcard_with_wildcard_exception(self):
method test_wildcard_filename_end (line 151) | def test_wildcard_filename_end(self):
method test_question_mark (line 156) | def test_question_mark(self):
method test_single_subdir_single_filename (line 161) | def test_single_subdir_single_filename(self):
method test_single_subdir_single_filename_leading_slash (line 166) | def test_single_subdir_single_filename_leading_slash(self):
method test_exclude_include_absolute_path (line 171) | def test_exclude_include_absolute_path(self):
method test_single_subdir_with_path_traversal (line 178) | def test_single_subdir_with_path_traversal(self):
method test_single_subdir_wildcard_filename (line 183) | def test_single_subdir_wildcard_filename(self):
method test_wildcard_subdir_single_filename (line 188) | def test_wildcard_subdir_single_filename(self):
method test_wildcard_subdir_wildcard_filename (line 193) | def test_wildcard_subdir_wildcard_filename(self):
method test_directory (line 198) | def test_directory(self):
method test_directory_with_trailing_slash (line 206) | def test_directory_with_trailing_slash(self):
method test_directory_with_single_exception (line 214) | def test_directory_with_single_exception(self):
method test_directory_with_subdir_exception (line 222) | def test_directory_with_subdir_exception(self):
method test_directory_with_subdir_exception_win32_pathsep (line 232) | def test_directory_with_subdir_exception_win32_pathsep(self):
method test_directory_with_wildcard_exception (line 239) | def test_directory_with_wildcard_exception(self):
method test_subdirectory (line 246) | def test_subdirectory(self):
method test_subdirectory_win32_pathsep (line 254) | def test_subdirectory_win32_pathsep(self):
method test_double_wildcard (line 259) | def test_double_wildcard(self):
method test_single_and_double_wildcard (line 270) | def test_single_and_double_wildcard(self):
method test_trailing_double_wildcard (line 279) | def test_trailing_double_wildcard(self):
method test_double_wildcard_with_exception (line 296) | def test_double_wildcard_with_exception(self):
method test_include_wildcard (line 304) | def test_include_wildcard(self):
method test_last_line_precedence (line 313) | def test_last_line_precedence(self):
method test_parent_directory (line 326) | def test_parent_directory(self):
class TarTest (line 343) | class TarTest(unittest.TestCase):
method test_tar_with_excludes (line 344) | def test_tar_with_excludes(self):
method test_tar_with_empty_directory (line 390) | def test_tar_with_empty_directory(self):
method test_tar_with_inaccessible_file (line 403) | def test_tar_with_inaccessible_file(self):
method test_tar_with_file_symlinks (line 418) | def test_tar_with_file_symlinks(self):
method test_tar_with_directory_symlinks (line 430) | def test_tar_with_directory_symlinks(self):
method test_tar_with_broken_symlinks (line 441) | def test_tar_with_broken_symlinks(self):
method test_tar_socket_file (line 453) | def test_tar_socket_file(self):
method tar_test_negative_mtime_bug (line 465) | def tar_test_negative_mtime_bug(self):
method test_tar_directory_link (line 478) | def test_tar_directory_link(self):
function test_match_tag (line 537) | def test_match_tag(tag: str, expected: bool):
FILE: tests/unit/utils_config_test.py
class FindConfigFileTest (line 13) | class FindConfigFileTest(unittest.TestCase):
method tmpdir (line 16) | def tmpdir(self, tmpdir):
method test_find_config_fallback (line 19) | def test_find_config_fallback(self):
method test_find_config_from_explicit_path (line 25) | def test_find_config_from_explicit_path(self):
method test_find_config_from_environment (line 31) | def test_find_config_from_environment(self):
method test_find_config_from_home_posix (line 39) | def test_find_config_from_home_posix(self):
method test_find_config_from_home_legacy_name (line 47) | def test_find_config_from_home_legacy_name(self):
method test_find_config_from_home_windows (line 55) | def test_find_config_from_home_windows(self):
class LoadConfigTest (line 63) | class LoadConfigTest(unittest.TestCase):
method test_load_config_no_file (line 64) | def test_load_config_no_file(self):
method test_load_config_custom_headers (line 72) | def test_load_config_custom_headers(self):
method test_load_config_detach_keys (line 94) | def test_load_config_detach_keys(self):
method test_load_config_from_env (line 107) | def test_load_config_from_env(self):
FILE: tests/unit/utils_json_stream_test.py
class TestJsonSplitter (line 4) | class TestJsonSplitter:
method test_json_splitter_no_object (line 6) | def test_json_splitter_no_object(self):
method test_json_splitter_with_object (line 10) | def test_json_splitter_with_object(self):
method test_json_splitter_leading_whitespace (line 14) | def test_json_splitter_leading_whitespace(self):
class TestStreamAsText (line 19) | class TestStreamAsText:
method test_stream_with_non_utf_unicode_character (line 21) | def test_stream_with_non_utf_unicode_character(self):
method test_stream_with_utf_character (line 26) | def test_stream_with_utf_character(self):
class TestJsonStream (line 32) | class TestJsonStream:
method test_with_falsy_entries (line 34) | def test_with_falsy_entries(self):
method test_with_leading_whitespace (line 47) | def test_with_leading_whitespace(self):
FILE: tests/unit/utils_proxy_test.py
class ProxyConfigTest (line 22) | class ProxyConfigTest(unittest.TestCase):
method test_from_dict (line 24) | def test_from_dict(self):
method test_new (line 36) | def test_new(self):
method test_truthiness (line 49) | def test_truthiness(self):
method test_environment (line 56) | def test_environment(self):
method test_inject_proxy_environment (line 61) | def test_inject_proxy_environment(self):
FILE: tests/unit/utils_test.py
class DecoratorsTest (line 39) | class DecoratorsTest(unittest.TestCase):
method test_update_headers (line 40) | def test_update_headers(self):
class KwargsFromEnvTest (line 70) | class KwargsFromEnvTest(unittest.TestCase):
method setUp (line 71) | def setUp(self):
method tearDown (line 74) | def tearDown(self):
method test_kwargs_from_env_empty (line 78) | def test_kwargs_from_env_empty(self):
method test_kwargs_from_env_tls (line 87) | def test_kwargs_from_env_tls(self):
method test_kwargs_from_env_tls_verify_false (line 108) | def test_kwargs_from_env_tls_verify_false(self):
method test_kwargs_from_env_tls_verify_false_no_cert (line 128) | def test_kwargs_from_env_tls_verify_false_no_cert(self):
method test_kwargs_from_env_no_cert_path (line 140) | def test_kwargs_from_env_no_cert_path(self):
method test_kwargs_from_env_alternate_env (line 158) | def test_kwargs_from_env_alternate_env(self):
class ConverVolumeBindsTest (line 173) | class ConverVolumeBindsTest(unittest.TestCase):
method test_convert_volume_binds_empty (line 174) | def test_convert_volume_binds_empty(self):
method test_convert_volume_binds_list (line 178) | def test_convert_volume_binds_list(self):
method test_convert_volume_binds_complete (line 182) | def test_convert_volume_binds_complete(self):
method test_convert_volume_binds_compact (line 191) | def test_convert_volume_binds_compact(self):
method test_convert_volume_binds_no_mode (line 197) | def test_convert_volume_binds_no_mode(self):
method test_convert_volume_binds_unicode_bytes_input (line 205) | def test_convert_volume_binds_unicode_bytes_input(self):
method test_convert_volume_binds_unicode_unicode_input (line 216) | def test_convert_volume_binds_unicode_unicode_input(self):
class ParseEnvFileTest (line 228) | class ParseEnvFileTest(unittest.TestCase):
method generate_tempfile (line 229) | def generate_tempfile(self, file_content=None):
method test_parse_env_file_proper (line 240) | def test_parse_env_file_proper(self):
method test_parse_env_file_with_equals_character (line 247) | def test_parse_env_file_with_equals_character(self):
method test_parse_env_file_commented_line (line 254) | def test_parse_env_file_commented_line(self):
method test_parse_env_file_newline (line 261) | def test_parse_env_file_newline(self):
method test_parse_env_file_invalid_line (line 268) | def test_parse_env_file_invalid_line(self):
class ParseHostTest (line 276) | class ParseHostTest(unittest.TestCase):
method test_parse_host (line 277) | def test_parse_host(self):
method test_parse_host_empty_value (line 329) | def test_parse_host_empty_value(self):
method test_parse_host_tls (line 337) | def test_parse_host_tls(self):
method test_parse_host_tls_tcp_proto (line 342) | def test_parse_host_tls_tcp_proto(self):
method test_parse_host_trailing_slash (line 347) | def test_parse_host_trailing_slash(self):
class ParseRepositoryTagTest (line 353) | class ParseRepositoryTagTest(unittest.TestCase):
method test_index_image_no_tag (line 356) | def test_index_image_no_tag(self):
method test_index_image_tag (line 359) | def test_index_image_tag(self):
method test_index_user_image_no_tag (line 362) | def test_index_user_image_no_tag(self):
method test_index_user_image_tag (line 365) | def test_index_user_image_tag(self):
method test_private_reg_image_no_tag (line 368) | def test_private_reg_image_no_tag(self):
method test_private_reg_image_tag (line 371) | def test_private_reg_image_tag(self):
method test_index_image_sha (line 376) | def test_index_image_sha(self):
method test_private_reg_image_sha (line 381) | def test_private_reg_image_sha(self):
class ParseDeviceTest (line 387) | class ParseDeviceTest(unittest.TestCase):
method test_dict (line 388) | def test_dict(self):
method test_partial_string_definition (line 400) | def test_partial_string_definition(self):
method test_permissionless_string_definition (line 408) | def test_permissionless_string_definition(self):
method test_full_string_definition (line 416) | def test_full_string_definition(self):
method test_hybrid_list (line 424) | def test_hybrid_list(self):
class ParseBytesTest (line 446) | class ParseBytesTest(unittest.TestCase):
method test_parse_bytes_valid (line 447) | def test_parse_bytes_valid(self):
method test_parse_bytes_invalid (line 452) | def test_parse_bytes_invalid(self):
method test_parse_bytes_float (line 460) | def test_parse_bytes_float(self):
class UtilsTest (line 464) | class UtilsTest(unittest.TestCase):
method test_convert_filters (line 467) | def test_convert_filters(self):
method test_decode_json_header (line 478) | def test_decode_json_header(self):
class SplitCommandTest (line 486) | class SplitCommandTest(unittest.TestCase):
method test_split_command_with_unicode (line 487) | def test_split_command_with_unicode(self):
class PortsTest (line 491) | class PortsTest(unittest.TestCase):
method test_split_port_with_host_ip (line 492) | def test_split_port_with_host_ip(self):
method test_split_port_with_protocol (line 497) | def test_split_port_with_protocol(self):
method test_split_port_with_host_ip_no_port (line 505) | def test_split_port_with_host_ip_no_port(self):
method test_split_port_range_with_host_ip_no_port (line 510) | def test_split_port_range_with_host_ip_no_port(self):
method test_split_port_with_host_port (line 515) | def test_split_port_with_host_port(self):
method test_split_port_range_with_host_port (line 520) | def test_split_port_range_with_host_port(self):
method test_split_port_random_port_range_with_host_port (line 525) | def test_split_port_random_port_range_with_host_port(self):
method test_split_port_no_host_port (line 530) | def test_split_port_no_host_port(self):
method test_split_port_range_no_host_port (line 535) | def test_split_port_range_no_host_port(self):
method test_split_port_range_with_protocol (line 540) | def test_split_port_range_with_protocol(self):
method test_split_port_with_ipv6_address (line 546) | def test_split_port_with_ipv6_address(self):
method test_split_port_with_ipv6_square_brackets_address (line 552) | def test_split_port_with_ipv6_square_brackets_address(self):
method test_split_port_invalid (line 558) | def test_split_port_invalid(self):
method test_split_port_invalid_protocol (line 562) | def test_split_port_invalid_protocol(self):
method test_non_matching_length_port_ranges (line 566) | def test_non_matching_length_port_ranges(self):
method test_port_and_range_invalid (line 570) | def test_port_and_range_invalid(self):
method test_port_only_with_colon (line 574) | def test_port_only_with_colon(self):
method test_host_only_with_colon (line 578) | def test_host_only_with_colon(self):
method test_with_no_container_port (line 582) | def test_with_no_container_port(self):
method test_split_port_empty_string (line 586) | def test_split_port_empty_string(self):
method test_split_port_non_string (line 590) | def test_split_port_non_string(self):
method test_build_port_bindings_with_one_port (line 593) | def test_build_port_bindings_with_one_port(self):
method test_build_port_bindings_with_matching_internal_ports (line 597) | def test_build_port_bindings_with_matching_internal_ports(self):
method test_build_port_bindings_with_nonmatching_internal_ports (line 604) | def test_build_port_bindings_with_nonmatching_internal_ports(self):
method test_build_port_bindings_with_port_range (line 610) | def test_build_port_bindings_with_port_range(self):
method test_build_port_bindings_with_matching_internal_port_ranges (line 615) | def test_build_port_bindings_with_matching_internal_port_ranges(self):
method test_build_port_bindings_with_nonmatching_internal_port_ranges (line 625) | def test_build_port_bindings_with_nonmatching_internal_port_ranges(self):
class FormatEnvironmentTest (line 632) | class FormatEnvironmentTest(unittest.TestCase):
method test_format_env_binary_unicode_value (line 633) | def test_format_env_binary_unicode_value(self):
method test_format_env_no_value (line 639) | def test_format_env_no_value(self):
function test_compare_versions (line 647) | def test_compare_versions():
Condensed preview — 192 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,295K chars).
[
{
"path": ".coveragerc",
"chars": 118,
"preview": "[run]\nbranch = True\nsource = docker\n\n[report]\nexclude_lines =\n if __name__ == .__main__.:\n\n[html]\ndirectory = html\n"
},
{
"path": ".dockerignore",
"chars": 121,
"preview": ".git/\n\nbuild\ndist\n*.egg-info\n*.egg/\n*.pyc\n*.swp\n\n.tox\n.coverage\nhtml/*\n__pycache__\n\n# Compiled Documentation\ndocs/_build"
},
{
"path": ".editorconfig",
"chars": 208,
"preview": "root = true\n\n[*]\nindent_style = space\nindent_size = 4\ninsert_final_newline = true\ntrim_trailing_whitespace = true\nmax_li"
},
{
"path": ".github/workflows/ci.yml",
"chars": 2038,
"preview": "name: Python package\n\non: [push, pull_request]\n\nenv:\n DOCKER_BUILDKIT: '1'\n FORCE_COLOR: 1\n\njobs:\n lint:\n ru"
},
{
"path": ".github/workflows/release.yml",
"chars": 1301,
"preview": "name: Release\n\non:\n workflow_dispatch:\n inputs:\n tag:\n description: \"Release Tag WITHOUT `v` Prefix (e.g"
},
{
"path": ".gitignore",
"chars": 164,
"preview": "build\ndist\n*.egg-info\n*.egg/\n*.pyc\n*.swp\n\n.tox\n.coverage\nhtml/*\n\n# Compiled Documentation\n_build/\nREADME.rst\n\n# setuptoo"
},
{
"path": ".readthedocs.yml",
"chars": 212,
"preview": "version: 2\n\nsphinx:\n configuration: docs/conf.py\n\nbuild:\n os: ubuntu-22.04\n tools:\n python: '3.12'\n\npython:\n inst"
},
{
"path": "CONTRIBUTING.md",
"chars": 4734,
"preview": "# Contributing guidelines\n\nSee the [Docker contributing guidelines](https://github.com/docker/docker/blob/master/CONTRIB"
},
{
"path": "Dockerfile",
"chars": 276,
"preview": "# syntax=docker/dockerfile:1\n\nARG PYTHON_VERSION=3.12\nFROM python:${PYTHON_VERSION}\n\nWORKDIR /src\nCOPY . .\n\nARG VERSION="
},
{
"path": "Dockerfile-docs",
"chars": 400,
"preview": "# syntax=docker/dockerfile:1\n\nARG PYTHON_VERSION=3.12\n\nFROM python:${PYTHON_VERSION}\n\nARG uid=1000\nARG gid=1000\n\nRUN add"
},
{
"path": "LICENSE",
"chars": 10758,
"preview": "\n Apache License\n Version 2.0, January 2004\n "
},
{
"path": "MAINTAINERS",
"chars": 1835,
"preview": "# Docker SDK for Python maintainers file\n#\n# This file describes who runs the docker/docker-py project and how.\n# This i"
},
{
"path": "Makefile",
"chars": 4969,
"preview": "TEST_API_VERSION ?= 1.45\nTEST_ENGINE_VERSION ?= 26.1\n\nifeq ($(OS),Windows_NT)\n PLATFORM := Windows\nelse\n PLATFORM "
},
{
"path": "README.md",
"chars": 1844,
"preview": "# Docker SDK for Python\n\n[](https"
},
{
"path": "docker/__init__.py",
"chars": 193,
"preview": "from .api import APIClient\nfrom .client import DockerClient, from_env\nfrom .context import Context, ContextAPI\nfrom .tls"
},
{
"path": "docker/api/__init__.py",
"chars": 30,
"preview": "from .client import APIClient\n"
},
{
"path": "docker/api/build.py",
"chars": 16063,
"preview": "import json\nimport logging\nimport os\nimport random\n\nfrom .. import auth, constants, errors, utils\n\nlog = logging.getLogg"
},
{
"path": "docker/api/client.py",
"chars": 19429,
"preview": "import json\nimport struct\nimport urllib\nfrom functools import partial\n\nimport requests\nimport requests.adapters\nimport r"
},
{
"path": "docker/api/config.py",
"chars": 2706,
"preview": "import base64\n\nfrom .. import utils\n\n\nclass ConfigApiMixin:\n @utils.minimum_version('1.30')\n def create_config(sel"
},
{
"path": "docker/api/container.py",
"chars": 52842,
"preview": "from datetime import datetime\n\nfrom .. import errors, utils\nfrom ..constants import DEFAULT_DATA_CHUNK_SIZE\nfrom ..types"
},
{
"path": "docker/api/daemon.py",
"chars": 6008,
"preview": "import os\nfrom datetime import datetime\n\nfrom .. import auth, types, utils\n\n\nclass DaemonApiMixin:\n @utils.minimum_ve"
},
{
"path": "docker/api/exec_api.py",
"chars": 6210,
"preview": "from .. import errors, utils\nfrom ..types import CancellableStream\n\n\nclass ExecApiMixin:\n @utils.check_resource('cont"
},
{
"path": "docker/api/image.py",
"chars": 20256,
"preview": "import logging\nimport os\n\nfrom .. import auth, errors, utils\nfrom ..constants import DEFAULT_DATA_CHUNK_SIZE\n\nlog = logg"
},
{
"path": "docker/api/network.py",
"chars": 10672,
"preview": "from .. import utils\nfrom ..errors import InvalidVersion\nfrom ..utils import check_resource, minimum_version, version_lt"
},
{
"path": "docker/api/plugin.py",
"chars": 8982,
"preview": "from .. import auth, utils\n\n\nclass PluginApiMixin:\n @utils.minimum_version('1.25')\n @utils.check_resource('name')\n"
},
{
"path": "docker/api/secret.py",
"chars": 2869,
"preview": "import base64\n\nfrom .. import errors, utils\n\n\nclass SecretApiMixin:\n @utils.minimum_version('1.25')\n def create_se"
},
{
"path": "docker/api/service.py",
"chars": 19215,
"preview": "from .. import auth, errors, utils\nfrom ..types import ServiceMode\n\n\ndef _check_api_features(version, task_template, upd"
},
{
"path": "docker/api/swarm.py",
"chars": 18089,
"preview": "import http.client as http_client\nimport logging\n\nfrom .. import errors, types, utils\nfrom ..constants import DEFAULT_SW"
},
{
"path": "docker/api/volume.py",
"chars": 5119,
"preview": "from .. import errors, utils\n\n\nclass VolumeApiMixin:\n def volumes(self, filters=None):\n \"\"\"\n List volum"
},
{
"path": "docker/auth.py",
"chars": 12977,
"preview": "import base64\nimport json\nimport logging\n\nfrom . import credentials, errors\nfrom .utils import config\n\nINDEX_NAME = 'doc"
},
{
"path": "docker/client.py",
"chars": 7704,
"preview": "from .api.client import APIClient\nfrom .constants import DEFAULT_MAX_POOL_SIZE, DEFAULT_TIMEOUT_SECONDS\nfrom .models.con"
},
{
"path": "docker/constants.py",
"chars": 1195,
"preview": "import sys\n\nfrom .version import __version__\n\nDEFAULT_DOCKER_API_VERSION = '1.45'\nMINIMUM_DOCKER_API_VERSION = '1.24'\nDE"
},
{
"path": "docker/context/__init__.py",
"chars": 57,
"preview": "from .api import ContextAPI\nfrom .context import Context\n"
},
{
"path": "docker/context/api.py",
"chars": 6326,
"preview": "import json\nimport os\n\nfrom docker import errors\n\nfrom .config import (\n METAFILE,\n get_current_context_name,\n "
},
{
"path": "docker/context/config.py",
"chars": 2151,
"preview": "import hashlib\nimport json\nimport os\n\nfrom docker import utils\nfrom docker.constants import DEFAULT_UNIX_SOCKET, IS_WIND"
},
{
"path": "docker/context/context.py",
"chars": 7828,
"preview": "import json\nimport os\nfrom shutil import copyfile, rmtree\n\nfrom docker.errors import ContextException\nfrom docker.tls im"
},
{
"path": "docker/credentials/__init__.py",
"chars": 197,
"preview": "from .constants import (\n DEFAULT_LINUX_STORE,\n DEFAULT_OSX_STORE,\n DEFAULT_WIN32_STORE,\n PROGRAM_PREFIX,\n)\n"
},
{
"path": "docker/credentials/constants.py",
"chars": 142,
"preview": "PROGRAM_PREFIX = 'docker-credential-'\nDEFAULT_LINUX_STORE = 'secretservice'\nDEFAULT_OSX_STORE = 'osxkeychain'\nDEFAULT_WI"
},
{
"path": "docker/credentials/errors.py",
"chars": 440,
"preview": "class StoreError(RuntimeError):\n pass\n\n\nclass CredentialsNotFound(StoreError):\n pass\n\n\nclass InitializationError(S"
},
{
"path": "docker/credentials/store.py",
"chars": 3262,
"preview": "import errno\nimport json\nimport shutil\nimport subprocess\nimport warnings\n\nfrom . import constants, errors\nfrom .utils im"
},
{
"path": "docker/credentials/utils.py",
"chars": 224,
"preview": "import os\n\n\ndef create_environment_dict(overrides):\n \"\"\"\n Create and return a copy of os.environ with the specifie"
},
{
"path": "docker/errors.py",
"chars": 5340,
"preview": "import requests\n\n_image_not_found_explanation_fragments = frozenset(\n fragment.lower() for fragment in [\n 'no "
},
{
"path": "docker/models/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "docker/models/configs.py",
"chars": 1845,
"preview": "from ..api import APIClient\nfrom .resource import Collection, Model\n\n\nclass Config(Model):\n \"\"\"A config.\"\"\"\n id_at"
},
{
"path": "docker/models/containers.py",
"chars": 46782,
"preview": "import copy\nimport ntpath\nfrom collections import namedtuple\n\nfrom ..api import APIClient\nfrom ..constants import DEFAUL"
},
{
"path": "docker/models/images.py",
"chars": 18023,
"preview": "import itertools\nimport re\nimport warnings\n\nfrom ..api import APIClient\nfrom ..constants import DEFAULT_DATA_CHUNK_SIZE\n"
},
{
"path": "docker/models/networks.py",
"chars": 7962,
"preview": "from ..api import APIClient\nfrom ..utils import version_gte\nfrom .containers import Container\nfrom .resource import Coll"
},
{
"path": "docker/models/nodes.py",
"chars": 2928,
"preview": "from .resource import Collection, Model\n\n\nclass Node(Model):\n \"\"\"A node in a swarm.\"\"\"\n id_attribute = 'ID'\n\n @"
},
{
"path": "docker/models/plugins.py",
"chars": 5971,
"preview": "from .. import errors\nfrom .resource import Collection, Model\n\n\nclass Plugin(Model):\n \"\"\"\n A plugin on the server."
},
{
"path": "docker/models/resource.py",
"chars": 2580,
"preview": "class Model:\n \"\"\"\n A base class for representing a single object on the server.\n \"\"\"\n id_attribute = 'Id'\n\n "
},
{
"path": "docker/models/secrets.py",
"chars": 1845,
"preview": "from ..api import APIClient\nfrom .resource import Collection, Model\n\n\nclass Secret(Model):\n \"\"\"A secret.\"\"\"\n id_at"
},
{
"path": "docker/models/services.py",
"chars": 13924,
"preview": "import copy\n\nfrom docker.errors import InvalidArgument, create_unexpected_kwargs_error\nfrom docker.types import Containe"
},
{
"path": "docker/models/swarm.py",
"chars": 8290,
"preview": "from docker.api import APIClient\nfrom docker.errors import APIError\n\nfrom .resource import Model\n\n\nclass Swarm(Model):\n "
},
{
"path": "docker/models/volumes.py",
"chars": 2848,
"preview": "from ..api import APIClient\nfrom .resource import Collection, Model\n\n\nclass Volume(Model):\n \"\"\"A volume.\"\"\"\n id_at"
},
{
"path": "docker/tls.py",
"chars": 2320,
"preview": "import os\n\nfrom . import errors\n\n\nclass TLSConfig:\n \"\"\"\n TLS configuration.\n\n Args:\n client_cert (tuple "
},
{
"path": "docker/transport/__init__.py",
"chars": 233,
"preview": "from .unixconn import UnixHTTPAdapter\n\ntry:\n from .npipeconn import NpipeHTTPAdapter\n from .npipesocket import Npi"
},
{
"path": "docker/transport/basehttpadapter.py",
"chars": 457,
"preview": "import requests.adapters\n\n\nclass BaseHTTPAdapter(requests.adapters.HTTPAdapter):\n def close(self):\n super().cl"
},
{
"path": "docker/transport/npipeconn.py",
"chars": 3525,
"preview": "import queue\n\nimport requests.adapters\nimport urllib3\nimport urllib3.connection\n\nfrom .. import constants\nfrom .basehttp"
},
{
"path": "docker/transport/npipesocket.py",
"chars": 6585,
"preview": "import functools\nimport io\nimport time\n\nimport pywintypes\nimport win32api\nimport win32event\nimport win32file\nimport win3"
},
{
"path": "docker/transport/sshconn.py",
"chars": 7923,
"preview": "import logging\nimport os\nimport queue\nimport signal\nimport socket\nimport subprocess\nimport urllib.parse\n\nimport paramiko"
},
{
"path": "docker/transport/unixconn.py",
"chars": 2915,
"preview": "import socket\n\nimport requests.adapters\nimport urllib3\nimport urllib3.connection\n\nfrom .. import constants\nfrom .basehtt"
},
{
"path": "docker/types/__init__.py",
"chars": 625,
"preview": "from .containers import ContainerConfig, DeviceRequest, HostConfig, LogConfig, Ulimit\nfrom .daemon import CancellableStr"
},
{
"path": "docker/types/base.py",
"chars": 110,
"preview": "class DictType(dict):\n def __init__(self, init):\n for k, v in init.items():\n self[k] = v\n"
},
{
"path": "docker/types/containers.py",
"chars": 27412,
"preview": "from .. import errors\nfrom ..utils.utils import (\n convert_port_bindings,\n convert_tmpfs_mounts,\n convert_volum"
},
{
"path": "docker/types/daemon.py",
"chars": 1943,
"preview": "import socket\n\nimport urllib3\n\nfrom ..errors import DockerException\n\n\nclass CancellableStream:\n \"\"\"\n Stream wrappe"
},
{
"path": "docker/types/healthcheck.py",
"chars": 2776,
"preview": "from .base import DictType\n\n\nclass Healthcheck(DictType):\n \"\"\"\n Defines a healthcheck configuration for a cont"
},
{
"path": "docker/types/networks.py",
"chars": 4240,
"preview": "from .. import errors\nfrom ..utils import normalize_links, version_lt\n\n\nclass EndpointConfig(dict):\n def __init__(sel"
},
{
"path": "docker/types/services.py",
"chars": 33328,
"preview": "from .. import errors\nfrom ..constants import IS_WINDOWS_PLATFORM\nfrom ..utils import (\n check_resource,\n convert_"
},
{
"path": "docker/types/swarm.py",
"chars": 4653,
"preview": "from ..errors import InvalidVersion\nfrom ..utils import version_lt\n\n\nclass SwarmSpec(dict):\n \"\"\"\n Describe a S"
},
{
"path": "docker/utils/__init__.py",
"chars": 664,
"preview": "\nfrom .build import create_archive, exclude_paths, match_tag, mkbuildcontext, tar\nfrom .decorators import check_resource"
},
{
"path": "docker/utils/build.py",
"chars": 8266,
"preview": "import io\nimport os\nimport re\nimport tarfile\nimport tempfile\n\nfrom ..constants import IS_WINDOWS_PLATFORM\nfrom .fnmatch "
},
{
"path": "docker/utils/config.py",
"chars": 1724,
"preview": "import json\nimport logging\nimport os\n\nfrom ..constants import IS_WINDOWS_PLATFORM\n\nDOCKER_CONFIG_FILENAME = os.path.join"
},
{
"path": "docker/utils/decorators.py",
"chars": 1492,
"preview": "import functools\n\nfrom .. import errors\nfrom . import utils\n\n\ndef check_resource(resource_name):\n def decorator(f):\n "
},
{
"path": "docker/utils/fnmatch.py",
"chars": 3295,
"preview": "\"\"\"Filename matching with shell patterns.\n\nfnmatch(FILENAME, PATTERN) matches according to the local convention.\nfnmatch"
},
{
"path": "docker/utils/json_stream.py",
"chars": 2184,
"preview": "import json\nimport json.decoder\n\nfrom ..errors import StreamParseError\n\njson_decoder = json.JSONDecoder()\n\n\ndef stream_a"
},
{
"path": "docker/utils/ports.py",
"chars": 2799,
"preview": "import re\n\nPORT_SPEC = re.compile(\n \"^\" # Match full string\n \"(\" # External part\n r\"(\\[?(?P<host>[a-fA-F\\d.:]"
},
{
"path": "docker/utils/proxy.py",
"chars": 2246,
"preview": "from .utils import format_environment\n\n\nclass ProxyConfig(dict):\n '''\n Hold the client's proxy configuration\n '"
},
{
"path": "docker/utils/socket.py",
"chars": 5073,
"preview": "import errno\nimport os\nimport select\nimport socket as pysocket\nimport struct\n\ntry:\n from ..transport import NpipeSock"
},
{
"path": "docker/utils/utils.py",
"chars": 14124,
"preview": "import base64\nimport collections\nimport json\nimport os\nimport os.path\nimport shlex\nimport string\nfrom datetime import da"
},
{
"path": "docker/version.py",
"chars": 240,
"preview": "try:\n from ._version import __version__\nexcept ImportError:\n from importlib.metadata import PackageNotFoundError, "
},
{
"path": "docs/_static/custom.css",
"chars": 206,
"preview": "dl.hide-signature > dt {\n display: none;\n}\n\ndl.field-list > dt {\n /* prevent code blocks from forcing wrapping on th"
},
{
"path": "docs/_templates/page.html",
"chars": 84,
"preview": "{% extends \"!page.html\" %}\n{% set css_files = css_files + [\"_static/custom.css\"] %}\n"
},
{
"path": "docs/api.rst",
"chars": 3073,
"preview": "Low-level API\n=============\n\nThe main object-orientated API is built on top of :py:class:`APIClient`. Each method on :py"
},
{
"path": "docs/change-log.md",
"chars": 78722,
"preview": "Changelog\n==========\n\n7.1.0\n-----\n### Upgrade Notes\n- Bumped minimum engine API version to 1.24\n- Bumped default engine "
},
{
"path": "docs/client.rst",
"chars": 920,
"preview": "Client\n======\n.. py:module:: docker.client\n\n\nCreating a client\n-----------------\n\nTo communicate with the Docker daemon,"
},
{
"path": "docs/conf.py",
"chars": 10280,
"preview": "#\n# docker-sdk-python documentation build configuration file, created by\n# sphinx-quickstart on Wed Sep 14 15:48:58 2016"
},
{
"path": "docs/configs.rst",
"chars": 505,
"preview": "Configs\n=======\n\n.. py:module:: docker.models.configs\n\nManage configs on the server.\n\nMethods available on ``client.conf"
},
{
"path": "docs/containers.rst",
"chars": 1313,
"preview": "Containers\n==========\n\n.. py:module:: docker.models.containers\n\nRun and manage containers on the server.\n\nMethods availa"
},
{
"path": "docs/images.rst",
"chars": 1089,
"preview": "Images\n======\n\n.. py:module:: docker.models.images\n\nManage images on the server.\n\nMethods available on ``client.images``"
},
{
"path": "docs/index.rst",
"chars": 2210,
"preview": "Docker SDK for Python\n=====================\n\nA Python library for the Docker Engine API. It lets you do anything the ``d"
},
{
"path": "docs/networks.rst",
"chars": 792,
"preview": "Networks\n========\n\n.. py:module:: docker.models.networks\n\nCreate and manage networks on the server. For more information"
},
{
"path": "docs/nodes.rst",
"chars": 615,
"preview": "Nodes\n=====\n\n.. py:module:: docker.models.nodes\n\nGet and list nodes in a swarm. Before you can use these methods, you fi"
},
{
"path": "docs/plugins.rst",
"chars": 723,
"preview": "Plugins\n=======\n\n.. py:module:: docker.models.plugins\n\nManage plugins on the server.\n\nMethods available on ``client.plug"
},
{
"path": "docs/secrets.rst",
"chars": 505,
"preview": "Secrets\n=======\n\n.. py:module:: docker.models.secrets\n\nManage secrets on the server.\n\nMethods available on ``client.secr"
},
{
"path": "docs/services.rst",
"chars": 919,
"preview": "Services\n========\n\n.. py:module:: docker.models.services\n\nManage services on a swarm. For more information about service"
},
{
"path": "docs/swarm.rst",
"chars": 754,
"preview": "Swarm\n=====\n\n.. py:module:: docker.models.swarm\n\nManage `Docker Engine's swarm mode <https://docs.docker.com/engine/swar"
},
{
"path": "docs/tls.rst",
"chars": 1168,
"preview": "Using TLS\n=========\n\n.. py:module:: docker.tls\n\nBoth the main :py:class:`~docker.client.DockerClient` and low-level\n:py:"
},
{
"path": "docs/user_guides/index.rst",
"chars": 110,
"preview": "User guides and tutorials\n=========================\n\n.. toctree::\n :maxdepth: 2\n\n multiplex\n swarm_services"
},
{
"path": "docs/user_guides/multiplex.rst",
"chars": 1919,
"preview": "Handling multiplexed streams\n============================\n\n.. note::\n The following instruction assume you're inter"
},
{
"path": "docs/user_guides/swarm_services.md",
"chars": 2087,
"preview": "# Swarm services\n\n> Warning:\n> This is a stale document and may contain outdated information.\n> Refer to the AP"
},
{
"path": "docs/volumes.rst",
"chars": 559,
"preview": "Volumes\n=======\n\n.. py:module:: docker.models.volumes\n\nManage volumes on the server.\n\nMethods available on ``client.volu"
},
{
"path": "pyproject.toml",
"chars": 2749,
"preview": "[build-system]\nrequires = [\"hatchling\", \"hatch-vcs\"]\nbuild-backend = \"hatchling.build\"\n\n[project]\nname = \"docker\"\ndynami"
},
{
"path": "pytest.ini",
"chars": 87,
"preview": "[pytest]\naddopts = --tb=short -rxs\n\njunit_suite_name = docker-py\njunit_family = xunit2\n"
},
{
"path": "scripts/release.sh",
"chars": 938,
"preview": "#!/bin/bash\n#\n# Create the official release\n#\n\nVERSION=$1\nREPO=docker/docker-py\nGITHUB_REPO=git@github.com:$REPO\n\nif [ -"
},
{
"path": "scripts/versions.py",
"chars": 2186,
"preview": "import operator\nimport re\nfrom collections import namedtuple\n\nimport requests\n\nbase_url = 'https://download.docker.com/l"
},
{
"path": "tests/Dockerfile",
"chars": 1293,
"preview": "# syntax=docker/dockerfile:1\n\nARG PYTHON_VERSION=3.12\nFROM python:${PYTHON_VERSION}\n\nRUN apt-get update && apt-get -y in"
},
{
"path": "tests/Dockerfile-dind-certs",
"chars": 1829,
"preview": "# syntax=docker/dockerfile:1\n\nARG PYTHON_VERSION=3.12\n\nFROM python:${PYTHON_VERSION}\nRUN mkdir /tmp/certs\nVOLUME /certs\n"
},
{
"path": "tests/Dockerfile-ssh-dind",
"chars": 474,
"preview": "# syntax=docker/dockerfile:1\n\nARG API_VERSION=1.45\nARG ENGINE_VERSION=26.1\n\nFROM docker:${ENGINE_VERSION}-dind\n\nRUN apk "
},
{
"path": "tests/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "tests/gpg-keys/ownertrust",
"chars": 166,
"preview": "# List of assigned trustvalues, created Wed 25 Apr 2018 01:28:17 PM PDT\n# (Use \"gpg --import-ownertrust\" to restore them"
},
{
"path": "tests/helpers.py",
"chars": 4435,
"preview": "import functools\nimport os\nimport os.path\nimport random\nimport re\nimport socket\nimport tarfile\nimport tempfile\nimport ti"
},
{
"path": "tests/integration/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "tests/integration/api_build_test.py",
"chars": 20157,
"preview": "import io\nimport os\nimport shutil\nimport tempfile\n\nimport pytest\n\nfrom docker import errors\nfrom docker.utils.proxy impo"
},
{
"path": "tests/integration/api_client_test.py",
"chars": 2117,
"preview": "import time\nimport unittest\nimport warnings\n\nimport docker\nfrom docker.utils import kwargs_from_env\n\nfrom .base import B"
},
{
"path": "tests/integration/api_config_test.py",
"chars": 2818,
"preview": "import pytest\n\nimport docker\n\nfrom ..helpers import force_leave_swarm, requires_api_version\nfrom .base import BaseAPIInt"
},
{
"path": "tests/integration/api_container_test.py",
"chars": 59412,
"preview": "import os\nimport re\nimport signal\nimport tempfile\nimport threading\nfrom datetime import datetime\n\nimport pytest\nimport r"
},
{
"path": "tests/integration/api_exec_test.py",
"chars": 11802,
"preview": "from docker.utils.proxy import ProxyConfig\nfrom docker.utils.socket import next_frame_header, read_exactly\n\nfrom ..helpe"
},
{
"path": "tests/integration/api_healthcheck_test.py",
"chars": 2387,
"preview": "from .. import helpers\nfrom .base import TEST_IMG, BaseAPIIntegrationTest\n\nSECOND = 1000000000\n\n\ndef wait_on_health_stat"
},
{
"path": "tests/integration/api_image_test.py",
"chars": 12533,
"preview": "import contextlib\nimport json\nimport shutil\nimport socket\nimport socketserver\nimport tarfile\nimport tempfile\nimport thre"
},
{
"path": "tests/integration/api_network_test.py",
"chars": 18867,
"preview": "import pytest\n\nimport docker\nfrom docker.types import IPAMConfig, IPAMPool\n\nfrom ..helpers import random_name, requires_"
},
{
"path": "tests/integration/api_plugin_test.py",
"chars": 5122,
"preview": "import os\n\nimport pytest\n\nimport docker\n\nfrom ..helpers import requires_api_version\nfrom .base import BaseAPIIntegration"
},
{
"path": "tests/integration/api_secret_test.py",
"chars": 2289,
"preview": "import pytest\n\nimport docker\n\nfrom ..helpers import force_leave_swarm, requires_api_version\nfrom .base import BaseAPIInt"
},
{
"path": "tests/integration/api_service_test.py",
"chars": 62633,
"preview": "import random\nimport time\n\nimport pytest\n\nimport docker\n\nfrom ..helpers import force_leave_swarm, requires_api_version\nf"
},
{
"path": "tests/integration/api_swarm_test.py",
"chars": 9624,
"preview": "import copy\n\nimport pytest\n\nimport docker\n\nfrom ..helpers import force_leave_swarm, requires_api_version\nfrom .base impo"
},
{
"path": "tests/integration/api_volume_test.py",
"chars": 2618,
"preview": "import pytest\n\nimport docker\n\nfrom ..helpers import requires_api_version\nfrom .base import BaseAPIIntegrationTest\n\n\nclas"
},
{
"path": "tests/integration/base.py",
"chars": 3971,
"preview": "import os\nimport shutil\nimport unittest\n\nimport docker\nfrom docker.utils import kwargs_from_env\n\nfrom .. import helpers\n"
},
{
"path": "tests/integration/client_test.py",
"chars": 1200,
"preview": "import threading\nimport unittest\nfrom datetime import datetime, timedelta\n\nimport docker\n\nfrom ..helpers import requires"
},
{
"path": "tests/integration/conftest.py",
"chars": 772,
"preview": "import sys\nimport warnings\n\nimport pytest\n\nimport docker.errors\nfrom docker.utils import kwargs_from_env\n\nfrom .base imp"
},
{
"path": "tests/integration/context_api_test.py",
"chars": 2086,
"preview": "import os\nimport tempfile\n\nimport pytest\n\nfrom docker import errors\nfrom docker.context import ContextAPI\nfrom docker.tl"
},
{
"path": "tests/integration/credentials/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "tests/integration/credentials/create_gpg_key.sh",
"chars": 227,
"preview": "#!/usr/bin/sh\nhaveged\ngpg --batch --gen-key <<-EOF\n%echo Generating a standard key\nKey-Type: DSA\nKey-Length: 1024\nSubkey"
},
{
"path": "tests/integration/credentials/store_test.py",
"chars": 3105,
"preview": "import os\nimport random\nimport shutil\nimport sys\n\nimport pytest\n\nfrom docker.credentials import (\n DEFAULT_LINUX_STOR"
},
{
"path": "tests/integration/credentials/utils_test.py",
"chars": 499,
"preview": "import os\nfrom unittest import mock\n\nfrom docker.credentials.utils import create_environment_dict\n\n\n@mock.patch.dict(os."
},
{
"path": "tests/integration/errors_test.py",
"chars": 632,
"preview": "import pytest\n\nfrom docker.errors import APIError\n\nfrom .base import TEST_IMG, BaseAPIIntegrationTest\n\n\nclass ErrorsTest"
},
{
"path": "tests/integration/models_containers_test.py",
"chars": 21741,
"preview": "import os\nimport tempfile\nimport threading\n\nimport pytest\n\nimport docker\n\nfrom ..helpers import random_name, requires_ap"
},
{
"path": "tests/integration/models_images_test.py",
"chars": 5807,
"preview": "import io\nimport tempfile\n\nimport pytest\n\nimport docker\n\nfrom ..helpers import random_name\nfrom .base import TEST_API_VE"
},
{
"path": "tests/integration/models_networks_test.py",
"chars": 2558,
"preview": "import docker\n\nfrom .. import helpers\nfrom .base import TEST_API_VERSION, BaseIntegrationTest\n\n\nclass NetworkCollectionT"
},
{
"path": "tests/integration/models_nodes_test.py",
"chars": 1148,
"preview": "import unittest\n\nimport docker\n\nfrom .. import helpers\nfrom .base import TEST_API_VERSION\n\n\nclass NodesTest(unittest.Tes"
},
{
"path": "tests/integration/models_resources_test.py",
"chars": 614,
"preview": "import docker\n\nfrom .base import TEST_API_VERSION, BaseIntegrationTest\n\n\nclass ModelTest(BaseIntegrationTest):\n\n def "
},
{
"path": "tests/integration/models_services_test.py",
"chars": 13200,
"preview": "import unittest\n\nimport pytest\n\nimport docker\nfrom docker.errors import InvalidArgument\nfrom docker.types.services impor"
},
{
"path": "tests/integration/models_swarm_test.py",
"chars": 1620,
"preview": "import unittest\n\nimport pytest\n\nimport docker\n\nfrom .. import helpers\nfrom .base import TEST_API_VERSION\n\n\nclass SwarmTe"
},
{
"path": "tests/integration/models_volumes_test.py",
"chars": 1107,
"preview": "import docker\n\nfrom .base import TEST_API_VERSION, BaseIntegrationTest\n\n\nclass VolumesTest(BaseIntegrationTest):\n def"
},
{
"path": "tests/integration/regression_test.py",
"chars": 2247,
"preview": "import io\nimport random\n\nimport pytest\n\nimport docker\n\nfrom .base import TEST_IMG, BaseAPIIntegrationTest\n\n\nclass TestRe"
},
{
"path": "tests/integration/testdata/dummy-plugin/config.json",
"chars": 420,
"preview": "{\n \"description\": \"Dummy test plugin for docker python SDK\",\n \"documentation\": \"https://github.com/docker/docker-p"
},
{
"path": "tests/integration/testdata/dummy-plugin/rootfs/dummy/file.txt",
"chars": 0,
"preview": ""
},
{
"path": "tests/ssh/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "tests/ssh/api_build_test.py",
"chars": 19709,
"preview": "import io\nimport os\nimport shutil\nimport tempfile\n\nimport pytest\n\nfrom docker import errors\nfrom docker.utils.proxy impo"
},
{
"path": "tests/ssh/base.py",
"chars": 4235,
"preview": "import os\nimport shutil\nimport unittest\n\nimport pytest\n\nimport docker\nfrom docker.utils import kwargs_from_env\n\nfrom .. "
},
{
"path": "tests/ssh/config/client/id_rsa",
"chars": 2578,
"preview": "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn\nNhAAAAAwEAAQA"
},
{
"path": "tests/ssh/config/client/id_rsa.pub",
"chars": 554,
"preview": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC/BiXkbL9oEbE3PJv1S2p12XK5BHW3qQT5Rf+CYG0ATYyMPIVM6+IXVyf3QNxpnvPXvbPBQJCs0qHeuPwZ"
},
{
"path": "tests/ssh/config/server/known_ed25519",
"chars": 411,
"preview": "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACC"
},
{
"path": "tests/ssh/config/server/known_ed25519.pub",
"chars": 115,
"preview": "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIax81dU/Xw3tcLohAa67FdBFtPGU8YuP7n8IHKP16Dh docker-py integration tests known\n"
},
{
"path": "tests/ssh/config/server/sshd_config",
"chars": 70,
"preview": "IgnoreUserKnownHosts yes\nPubkeyAuthentication yes\nPermitRootLogin yes\n"
},
{
"path": "tests/ssh/config/server/unknown_ed25519",
"chars": 411,
"preview": "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW\nQyNTUxOQAAACC"
},
{
"path": "tests/ssh/config/server/unknown_ed25519.pub",
"chars": 117,
"preview": "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIax81dU/Xw3tcLohAa67FdBFtPGU8YuP7n8IHKP16Dh docker-py integration tests unknown\n"
},
{
"path": "tests/ssh/connect_test.py",
"chars": 755,
"preview": "import os\nimport unittest\n\nimport paramiko.ssh_exception\nimport pytest\n\nimport docker\n\nfrom .base import TEST_API_VERSIO"
},
{
"path": "tests/unit/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "tests/unit/api_build_test.py",
"chars": 7872,
"preview": "import gzip\nimport io\nimport shutil\n\nimport pytest\n\nimport docker\nfrom docker import auth, errors\nfrom docker.api.build "
},
{
"path": "tests/unit/api_container_test.py",
"chars": 59098,
"preview": "import datetime\nimport json\nimport signal\nfrom unittest import mock\n\nimport pytest\n\nimport docker\nfrom docker.api import"
},
{
"path": "tests/unit/api_exec_test.py",
"chars": 2314,
"preview": "import json\n\nfrom . import fake_api\nfrom .api_test import (\n DEFAULT_TIMEOUT_SECONDS,\n BaseAPIClientTest,\n fake"
},
{
"path": "tests/unit/api_image_test.py",
"chars": 10984,
"preview": "from unittest import mock\n\nimport pytest\n\nimport docker\nfrom docker import auth\n\nfrom . import fake_api\nfrom .api_test i"
},
{
"path": "tests/unit/api_network_test.py",
"chars": 5664,
"preview": "import json\nfrom unittest import mock\n\nfrom docker.types import IPAMConfig, IPAMPool\n\nfrom .api_test import BaseAPIClien"
},
{
"path": "tests/unit/api_test.py",
"chars": 21734,
"preview": "import datetime\nimport http.server\nimport io\nimport json\nimport os\nimport re\nimport shutil\nimport socket\nimport socketse"
},
{
"path": "tests/unit/api_volume_test.py",
"chars": 3886,
"preview": "import json\n\nimport pytest\n\nfrom ..helpers import requires_api_version\nfrom .api_test import BaseAPIClientTest, fake_req"
},
{
"path": "tests/unit/auth_test.py",
"chars": 28248,
"preview": "import base64\nimport json\nimport os\nimport os.path\nimport random\nimport shutil\nimport tempfile\nimport unittest\nfrom unit"
},
{
"path": "tests/unit/client_test.py",
"chars": 9930,
"preview": "import datetime\nimport os\nimport unittest\nfrom unittest import mock\n\nimport pytest\n\nimport docker\nfrom docker.constants "
},
{
"path": "tests/unit/context_test.py",
"chars": 1624,
"preview": "import unittest\n\nimport pytest\n\nimport docker\nfrom docker.constants import DEFAULT_NPIPE, DEFAULT_UNIX_SOCKET, IS_WINDOW"
},
{
"path": "tests/unit/dockertypes_test.py",
"chars": 18313,
"preview": "import unittest\nfrom unittest import mock\n\nimport pytest\n\nfrom docker.constants import DEFAULT_DOCKER_API_VERSION\nfrom d"
},
{
"path": "tests/unit/errors_test.py",
"chars": 5502,
"preview": "import unittest\n\nimport requests\n\nfrom docker.errors import (\n APIError,\n ContainerError,\n DockerException,\n "
},
{
"path": "tests/unit/fake_api.py",
"chars": 17717,
"preview": "from docker import constants\n\nfrom . import fake_stat\n\nCURRENT_VERSION = f'v{constants.DEFAULT_DOCKER_API_VERSION}'\n\nFAK"
},
{
"path": "tests/unit/fake_api_client.py",
"chars": 2496,
"preview": "import copy\nfrom unittest import mock\n\nimport docker\nfrom docker.constants import DEFAULT_DOCKER_API_VERSION\n\nfrom . imp"
},
{
"path": "tests/unit/fake_stat.py",
"chars": 3757,
"preview": "OBJ = {\n \"read\": \"2015-02-11T19:20:46.667237763+02:00\",\n \"network\": {\n \"rx_bytes\": 567224,\n \"rx_pack"
},
{
"path": "tests/unit/models_configs_test.py",
"chars": 363,
"preview": "import unittest\n\nfrom .fake_api import FAKE_CONFIG_NAME\nfrom .fake_api_client import make_fake_client\n\n\nclass CreateConf"
},
{
"path": "tests/unit/models_containers_test.py",
"chars": 29172,
"preview": "import unittest\n\nimport pytest\n\nimport docker\nfrom docker.constants import DEFAULT_DATA_CHUNK_SIZE, DEFAULT_DOCKER_API_V"
},
{
"path": "tests/unit/models_images_test.py",
"chars": 5925,
"preview": "import unittest\nimport warnings\n\nfrom docker.constants import DEFAULT_DATA_CHUNK_SIZE\nfrom docker.models.images import I"
},
{
"path": "tests/unit/models_networks_test.py",
"chars": 2176,
"preview": "import unittest\n\nfrom .fake_api import FAKE_CONTAINER_ID, FAKE_NETWORK_ID\nfrom .fake_api_client import make_fake_client\n"
},
{
"path": "tests/unit/models_resources_test.py",
"chars": 873,
"preview": "import unittest\n\nfrom .fake_api import FAKE_CONTAINER_ID\nfrom .fake_api_client import make_fake_client\n\n\nclass ModelTest"
},
{
"path": "tests/unit/models_secrets_test.py",
"chars": 362,
"preview": "import unittest\n\nfrom .fake_api import FAKE_SECRET_NAME\nfrom .fake_api_client import make_fake_client\n\n\nclass CreateServ"
},
{
"path": "tests/unit/models_services_test.py",
"chars": 2436,
"preview": "import unittest\n\nfrom docker.models.services import _get_create_service_kwargs\n\n\nclass CreateServiceKwargsTest(unittest."
},
{
"path": "tests/unit/sshadapter_test.py",
"chars": 1144,
"preview": "import unittest\n\nimport docker\nfrom docker.transport.sshconn import SSHSocket\n\n\nclass SSHAdapterTest(unittest.TestCase):"
},
{
"path": "tests/unit/swarm_test.py",
"chars": 2150,
"preview": "import json\n\nfrom ..helpers import requires_api_version\nfrom . import fake_api\nfrom .api_test import BaseAPIClientTest, "
},
{
"path": "tests/unit/testdata/certs/ca.pem",
"chars": 0,
"preview": ""
},
{
"path": "tests/unit/testdata/certs/cert.pem",
"chars": 0,
"preview": ""
},
{
"path": "tests/unit/testdata/certs/key.pem",
"chars": 0,
"preview": ""
},
{
"path": "tests/unit/types_containers_test.py",
"chars": 186,
"preview": "from docker.types.containers import ContainerConfig\n\n\ndef test_uid_0_is_not_elided():\n x = ContainerConfig(image='i',"
},
{
"path": "tests/unit/utils_build_test.py",
"chars": 18168,
"preview": "import os\nimport os.path\nimport shutil\nimport socket\nimport tarfile\nimport tempfile\nimport unittest\n\nimport pytest\n\nfrom"
},
{
"path": "tests/unit/utils_config_test.py",
"chars": 4035,
"preview": "import json\nimport os\nimport shutil\nimport tempfile\nimport unittest\nfrom unittest import mock\n\nfrom pytest import fixtur"
},
{
"path": "tests/unit/utils_json_stream_test.py",
"chars": 1603,
"preview": "from docker.utils.json_stream import json_splitter, json_stream, stream_as_text\n\n\nclass TestJsonSplitter:\n\n def test_"
},
{
"path": "tests/unit/utils_proxy_test.py",
"chars": 2784,
"preview": "import unittest\n\nfrom docker.utils.proxy import ProxyConfig\n\nHTTP = 'http://test:80'\nHTTPS = 'https://test:443'\nFTP = 'f"
},
{
"path": "tests/unit/utils_test.py",
"chars": 23595,
"preview": "import base64\nimport json\nimport os\nimport os.path\nimport shutil\nimport tempfile\nimport unittest\n\nimport pytest\n\nfrom do"
},
{
"path": "tox.ini",
"chars": 229,
"preview": "[tox]\nenvlist = py{37,38,39,310,311,312}, ruff\nskipsdist=True\n\n[testenv]\nusedevelop=True\ncommands =\n py.test -v --cov"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the docker/docker-py GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 192 files (1.2 MB), approximately 282.4k tokens, and a symbol index with 2084 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.