diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..d95b72a20 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true +charset = utf-8 +trim_trailing_whitespace = true + +# JSON files +[*.json] +indent_style = space +indent_size = 4 diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..e5fae30f4 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +version: 2 +updates: + # Maintain dependencies for GitHub Actions + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + # Maintain dependencies for PHP Packages + - package-ecosystem: "composer" + directory: "/" + schedule: + interval: "daily" diff --git a/.github/workflows/continuous-integration.yml b/.github/workflows/continuous-integration.yml new file mode 100644 index 000000000..f54b93af1 --- /dev/null +++ b/.github/workflows/continuous-integration.yml @@ -0,0 +1,113 @@ +name: "Continuous Integration" + +on: + push: + paths-ignore: + - "doc/**" + pull_request: + paths-ignore: + - "doc/**" + +jobs: + phpunit: + name: PHP ${{ matrix.php-version }} (${{ matrix.dependency-versions }}) + + runs-on: ubuntu-latest + continue-on-error: ${{ matrix.experimental }} + + strategy: + fail-fast: false + matrix: + php-version: + - "8.2" + - "8.3" + - "8.4" + - "8.5" + dependency-versions: [lowest, highest] + experimental: [false] + + steps: + - name: Repository checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Setup PHP with PECL extension + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0 + with: + php-version: ${{ matrix.php-version }} + extensions: curl, openssl + tools: composer:v2 + coverage: pcov + + - name: Validate composer.json and composer.lock + run: composer validate --strict + + - name: Install dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # v4.0.0 + with: + dependency-versions: ${{ matrix.dependency-versions }} + composer-options: ${{ matrix.composer-options }} + + - name: Pull the docker image used by the tests. + run: docker pull busybox:latest + + - name: Run PHPUnit test suite + run: composer run-script test-ci + + api-versions: + name: API ${{ matrix.api-line }} (Docker ${{ matrix.docker }}) + + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + api-line: ["7.1.45", "7.1.46", "7.1.47", "7.1.48", "7.1.49", "7.1.50", "7.1.51", "7.1.52", "7.1.53", "7.1.54", "7.1.55", "7.1.56", "7.1.57"] + # The runner's daemon is older than the newest lines, so those negotiate down. + docker: [runner] + include: + # Run the newest line against a daemon that supports it without negotiation. + - api-line: "7.1.57" + docker: "29" + + services: + dind: + image: ${{ matrix.docker == '29' && 'docker:29-dind' || '' }} + options: --privileged + env: + DOCKER_TLS_CERTDIR: "" + ports: + - 2375:2375 + + env: + DOCKER_HOST: ${{ matrix.docker == '29' && 'tcp://127.0.0.1:2375' || '' }} + + steps: + - name: Repository checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Setup PHP with PECL extension + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0 + with: + php-version: "8.5" + extensions: curl, openssl + tools: composer:v2 + coverage: none + + - name: Select the API line + run: composer require --no-update "docker-php/docker-php-api:>=${{ matrix.api-line }}.0 <${{ matrix.api-line }}.99999" + + - name: Install dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # v4.0.0 + with: + dependency-versions: highest + + - name: Wait for the daemon + run: | + for attempt in $(seq 1 30); do docker version && break; sleep 2; done + docker version --format 'Daemon API {{.Server.APIVersion}}' + + - name: Pull the docker image used by the tests. + run: docker pull busybox:latest + + - name: Run PHPUnit test suite + run: composer run-script test-ci diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml new file mode 100644 index 000000000..48f938f10 --- /dev/null +++ b/.github/workflows/documentation.yml @@ -0,0 +1,51 @@ +name: Documentation + +on: + push: + paths: + - 'docs/**' + - '.github/workflows/documentation.yml' + pull_request: + paths: + - 'docs/**' + - '.github/workflows/documentation.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + validate: + name: Mintlify and PHP examples + runs-on: ubuntu-latest + defaults: + run: + working-directory: docs + steps: + - name: Check out the repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '22' + cache: npm + cache-dependency-path: docs/package-lock.json + + - name: Set up PHP + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0 + with: + php-version: '8.2' + coverage: none + + - name: Install documentation tooling + run: npm ci + + - name: Validate Mintlify configuration and pages + run: npm run validate + + - name: Check internal links and anchors + run: npm run check:links + + - name: Check PHP example syntax + run: npm run check:examples diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml new file mode 100644 index 000000000..68fb0cbb8 --- /dev/null +++ b/.github/workflows/static-analysis.yml @@ -0,0 +1,46 @@ +name: "Static Analysis" + +on: + push: + paths-ignore: + - 'doc/**' + pull_request: + paths-ignore: + - 'doc/**' + +jobs: + phpstan: + name: PHPStan (PHP ${{ matrix.php-version }}, ${{ matrix.dependency-versions }}) + + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + include: + - php-version: '8.2' + dependency-versions: lowest + - php-version: '8.5' + dependency-versions: highest + + steps: + - name: Repository checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Setup PHP with PECL extension + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2.40.0 + with: + php-version: ${{ matrix.php-version }} + tools: composer:v2 + coverage: none + + - name: Validate composer.json and composer.lock + run: composer validate --strict + + - name: Install dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # v4.0.0 + with: + dependency-versions: ${{ matrix.dependency-versions }} + + - name: Run PHPStan + run: composer run-script phpstan -- --no-progress diff --git a/.gitignore b/.gitignore index 228f5459f..d4b4f99eb 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,7 @@ vendor/ bin/ composer.lock .vagrant -/.php_cs.cache +/.php-cs-fixer.cache +/.phpunit.result.cache +/docs/node_modules/ +/docs/.mintlify/ diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php new file mode 100644 index 000000000..3bde3b9fc --- /dev/null +++ b/.php-cs-fixer.php @@ -0,0 +1,47 @@ +in([ + __DIR__.'/src', + __DIR__.'/tests', + ]) + ->notPath('/fixtures/') +; + +$config = new \PhpCsFixer\Config(); +return $config + ->setRules([ + '@Symfony' => true, + '@Symfony:risky' => true, + '@PHP56Migration:risky' => true, + '@PHP70Migration' => true, + '@PHP70Migration:risky' => true, + '@PHP71Migration' => true, + '@PHP71Migration:risky' => true, + '@PHP73Migration' => true, + '@PHP74Migration' => true, + '@PHP74Migration:risky' => true, + '@PHP80Migration' => true, + '@PHP80Migration:risky' => true, + '@PHPUnit75Migration:risky' => true, + '@PHPUnit84Migration:risky' => true, + 'array_syntax' => [ + 'syntax' => 'short' + ], + 'combine_consecutive_unsets' => true, + 'declare_strict_types' => true, + 'linebreak_after_opening_tag' => true, + 'modernize_types_casting' => true, + 'native_function_invocation' => true, + 'no_php4_constructor' => true, + 'ordered_imports' => true, + 'php_unit_strict' => true, + 'phpdoc_order' => true, + 'strict_comparison' => true, + 'strict_param' => true, + ]) + ->setRiskyAllowed(true) + ->setIndent(' ') + ->setLineEnding("\n") + ->setFinder($finder) +; diff --git a/.php_cs b/.php_cs deleted file mode 100644 index 3eaf3dae5..000000000 --- a/.php_cs +++ /dev/null @@ -1,38 +0,0 @@ -in([ - __DIR__.'/src', - __DIR__.'/tests', - ]) - ->notPath('/fixtures/') -; - -return \PhpCsFixer\Config::create() - ->setRules([ - '@Symfony' => true, - '@Symfony:risky' => true, - '@PHP56Migration' => true, - '@PHP56Migration:risky' => true, - '@PHP70Migration' => true, - '@PHP70Migration:risky' => true, - '@PHP71Migration' => true, - '@PHP71Migration:risky' => true, - 'array_syntax' => [ - 'syntax' => 'short' - ], - 'combine_consecutive_unsets' => true, - 'declare_strict_types' => true, - 'linebreak_after_opening_tag' => true, - 'modernize_types_casting' => true, - 'native_function_invocation' => true, - 'no_php4_constructor' => true, - 'ordered_imports' => true, - 'php_unit_strict' => true, - 'phpdoc_order' => true, - 'strict_comparison' => true, - 'strict_param' => true, - ]) - ->setRiskyAllowed(true) - ->setFinder($finder) -; diff --git a/.scrutinizer.yml b/.scrutinizer.yml deleted file mode 100644 index 60d211bf7..000000000 --- a/.scrutinizer.yml +++ /dev/null @@ -1,11 +0,0 @@ -filter: - paths: [src/*] -checks: - php: - code_rating: true - duplication: true -tools: - external_code_coverage: true - php_code_sniffer: - config: - standard: "PSR2" diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 41708d6f6..000000000 --- a/.travis.yml +++ /dev/null @@ -1,68 +0,0 @@ -language: php -sudo: required - -services: - - docker - -cache: - directories: - - $HOME/.composer/cache - -php: 7.2 - -env: - global: - - TEST_COMMAND="composer test" - matrix: - - DOCKER_API_VERSION=1.36 DOCKER_VERSION=18.02.0~ce-0~ubuntu - - DOCKER_API_VERSION=1.36 DOCKER_VERSION=18.01.0~ce-0~ubuntu - - DOCKER_API_VERSION=1.35 DOCKER_VERSION=17.12.0~ce-0~ubuntu - - DOCKER_API_VERSION=1.34 DOCKER_VERSION=17.11.0~ce-0~ubuntu - - DOCKER_API_VERSION=1.33 DOCKER_VERSION=17.10.0~ce-0~ubuntu - - DOCKER_API_VERSION=1.32 DOCKER_VERSION=17.09.0~ce-0~ubuntu - - DOCKER_API_VERSION=1.31 DOCKER_VERSION=17.07.0~ce-0~ubuntu - - DOCKER_API_VERSION=1.30 DOCKER_VERSION=17.06.2~ce-0~ubuntu - - DOCKER_API_VERSION=1.29 DOCKER_VERSION=17.05.0~ce-0~ubuntu-trusty - - DOCKER_API_VERSION=1.28 DOCKER_VERSION=17.04.0~ce-0~ubuntu-trusty - - DOCKER_API_VERSION=1.27 DOCKER_VERSION=17.03.2~ce-0~ubuntu-trusty - - DOCKER_API_VERSION=1.26 DOCKER_VERSION=17.03.2~ce-0~ubuntu-trusty - - DOCKER_API_VERSION=1.25 DOCKER_VERSION=17.03.2~ce-0~ubuntu-trusty - -matrix: - allow_failures: - - php: hhvm - fast_finish: true - include: - - php: 7.1 - sudo: required - services: - - docker - env: DOCKER_API_VERSION=1.25 DOCKER_VERSION=17.03.2~ce-0~ubuntu-trusty COMPOSER_FLAGS="--prefer-stable --prefer-lowest" COVERAGE=true TEST_COMMAND="composer test-ci" - - php: 7.1 - env: DOCKER_API_VERSION=1.36 DOCKER_VERSION=18.02.0~ce-0~ubuntu TEST_COMMAND="composer lint" - - php: 7.2 - sudo: required - services: - - docker - env: DOCKER_API_VERSION=1.36 DOCKER_VERSION=18.02.0~ce-0~ubuntu - -before_install: - - sudo apt-get update - - sudo apt-cache madison docker-ce - - sudo apt-get -o Dpkg::Options::="--force-confnew" install -y --force-yes docker-ce=${DOCKER_VERSION} - - travis_retry composer self-update - -install: - - travis_retry composer install - - travis_retry composer update ${COMPOSER_FLAGS} --no-interaction - - travis_retry composer require docker-php/docker-php-api:4.${DOCKER_API_VERSION}.* - -script: - - $TEST_COMMAND - -after_success: - - if [[ "$COVERAGE" = true ]]; then wget https://scrutinizer-ci.com/ocular.phar; fi - - if [[ "$COVERAGE" = true ]]; then php ocular.phar code-coverage:upload --format=php-clover build/coverage.xml; fi - -after_script: - - sudo cat /var/log/upstart/docker.log diff --git a/CHANGELOG.md b/CHANGELOG.md index b3b5716d6..c26f027db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,109 @@ # Changelog +## 4.1.0 + +### Changed + +- Require PHP 8.2 or later. PHP 8.1 reached end of life on 31 December 2025; + Docker PHP 4.0 remains available for it. +- Allow the Docker Engine API v1.57 line (`docker-php/docker-php-api` + `>=7.1.45.0 <7.1.58.0`). Composer installs the newest line unless you require + one. API 1.57 adds a `restarting` attribute to container `die` events and + declares JSON error responses for streaming endpoints; generated model names + are unchanged from 1.56. + +## 4.0.2 + +### Changed + +- Remove the funding links from `composer.json` and the repository, which + pointed to the Beluga maintainer's sponsorship pages. No code changes. + +## 4.0.1 + +### Fixed + +- Stop lowest-dependency installs from pulling in the abandoned + `php-http/message-factory` package. The client now conflicts with Jane + runtimes before 7.14.4, the version that generates the API packages, and with + `php-http/message` before 1.16. + +## 4.0.0 + +### Breaking changes + +- Allow every Docker Engine API line from v1.45 to v1.56 + (`docker-php/docker-php-api` `>=7.1.45.0 <7.1.57.0`). Composer installs the + newest line unless you require one; generated model names and fields differ + between lines. Require `>=7.1.45.0 <7.1.46.0` to keep the 3.x models. +- Negotiate the request API version with the daemon when neither `api_version` + nor `DOCKER_API_VERSION` is set: the bundled factory sends an unversioned + `/_ping` first and uses the lower of the daemon's and the installed line's + versions. +- Throw `UnexpectedClientErrorException` or `UnexpectedServerErrorException` for + error statuses the generated endpoints do not handle. Call + `throwOnUnexpectedStatus(false)` to return `null` instead. +- Apply a context's `.dockerignore` by default. Call `applyDockerignore(false)` + to archive the whole directory. +- Add an optional `$accept` parameter to `Docker::systemEvents()`, matching API + 1.52 and later. Subclasses that override it need the same parameter. + +### Added + +- `DockerClientFactory::defaultApiVersion()` returns the installed API line's + version. +- `FrameError::message()` reads the error from build, pull and push progress + frames on every API line. +- Stats samples decode into `ContainerStatsResponse` models from API 1.48. + +### Fixed + +- Decode integers above `PHP_INT_MAX`, such as the `pids_stats.limit` Docker + reports for a container without a PID limit, as `PHP_INT_MAX`. The generated + integer setters rejected them as floats. + +### Removed + +- The 3.3 deprecation notices, and the direct dependency on + `symfony/deprecation-contracts`. + +## 3.3.0 + +- Add `StatsStream`: `containerStats()` streams samples to `onFrame()` by + default instead of blocking on the endless response. +- Add `stop()` to callback streams, so build, pull, push, event and stats + readers can finish from a callback. +- Add `close()` to `AttachWebsocketStream`. +- Accept a list of tags for `imageBuild()`'s `t` option. +- Add opt-in exceptions for error statuses the generated endpoints do not + handle (`Docker::throwOnUnexpectedStatus()`). Without it, such calls still + return `null` and trigger a deprecation; throwing becomes the default in 4.0. +- Add opt-in `.dockerignore` support for build contexts + (`Context::applyDockerignore()`). Without it, a context with a + `.dockerignore` triggers a deprecation; applying it becomes the default + in 4.0. +- Fix `containerAttachWebsocket()`, which returned `null` for every real + WebSocket upgrade. +- Fix `containerAttach()` losing TTY output, and handle upgraded attach + responses. +- Fix WebSocket close, ping and empty frames, stalled or truncated frames, + 65,536-byte payload lengths, mask key randomness and partial writes. +- Declare the stream return types of `Docker` methods for static analysis. +- Allow Guzzle 8 and PHPStan 2 for development. + +## 3.2.0 + +- Add opt-in interactive exec sessions with nonblocking stdin writes, bounded + output polling, non-TTY stdin EOF and streaming deadlines. +- Keep existing blocking exec APIs unchanged. Interactive sessions require + the bundled socket transport; TTY stdin half-close is rejected. + +## 3.1.0 + +- Add an explicit `api_version` factory option. It overrides `DOCKER_API_VERSION` + without changing the process environment or generated models. +- Preserve the existing environment fallback and default API version 1.45. + ## 2.0 - [BC Break] All endpoints have new names and potentially new parameters diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6be589b9f..d53bf296d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -45,11 +45,11 @@ $ composer test When you are ready with the code, tested it and documented it, you can commit and push it with the following commands: ``` bash -$ git commit -m "Feature or bug fix description" +$ git commit -m "fix(stream): decode Docker frame headers" $ git push origin feature-or-bug-fix-description ``` -**Note:** Please write your commit messages in the imperative and follow the [guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) for clear and concise messages. +**Note:** Commit messages must follow the [commit message format](#commit-messages) below. Please write descriptions in the imperative and follow the [guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) for clear and concise messages. Then [create a pull request](https://help.github.com/articles/creating-a-pull-request/) on GitHub. @@ -67,9 +67,32 @@ $ git pull --rebase upstream master $ git push -f origin feature-or-bug-fix-description ``` -## Internal +## Documentation -This library consist, for the most part, of auto generated code where the reference is an [Open API Specification (Swagger v2)](https://openapis.org/). In order to modify API +Documentation for the 4.0 release lives in `docs/` and uses Mintlify. +See [DOCUMENTATION.md](DOCUMENTATION.md) for the local preview, validation commands +and hosted setup. Test examples against a development Docker daemon, and keep +instructions for unreleased packages clearly marked. + +## Commit messages + +All commits must follow [Conventional Commits 1.0.0](https://www.conventionalcommits.org/en/v1.0.0/). +Start the subject with a type, an optional scope in parentheses, and a colon followed by a space and a short description. + +Use `fix` for bug fixes and `feat` for new features. Other types, such as `docs`, `test`, `refactor`, `ci` and `chore`, are allowed where appropriate: + +```text +fix(stream): decode Docker frame headers +feat: add support for a new Docker API version +docs: clarify the migration instructions +``` + +Mark breaking changes with `!` immediately before the colon or a `BREAKING CHANGE:` footer. +Explain what breaks and how users should migrate in the commit body or footer. + +## Internal + +This library consist, for the most part, of auto generated code where the reference is an [Open API Specification (Swagger v2)](https://openapis.org/). In order to modify API endpoint or requested / returned object, you will need to update the `docker-swagger.json` file instead of files in the `generated` directory. There is a bash script at the root of this repository `generate.sh` which helps launching the command to generate files according to the diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md new file mode 100644 index 000000000..9dd16595f --- /dev/null +++ b/DOCUMENTATION.md @@ -0,0 +1,96 @@ +# Documentation development + +The Docker PHP 4.0 documentation uses Mintlify. Its source lives in `docs/` in +this repository, alongside the client code. This replaces the legacy MkDocs +configuration; earlier documentation remains available in Git history. + +The public site is hosted at [docker-php.mintlify.site](https://docker-php.mintlify.site/). +No custom domain is configured. + +## Local preview + +Use Node.js 22 or 24 LTS and PHP 8.2 or later. From the repository root: + +```bash +cd docs +npm ci +npm run dev +``` + +Open the localhost URL printed by the CLI. `docs/package-lock.json` pins the +tooling used by the preview and CI. + +## Validation + +From `docs/`: + +```bash +npm run validate +npm run check:links +npm run check:examples +``` + +The first two commands use Mintlify's configuration/MDX and internal-link +validators. The last command checks PHP snippet syntax, not runtime behavior. +Test examples which mutate Docker state against a development daemon. + +Selected complex recipes also have mocked HTTP tests in +`tests/DocumentationExamplesTest.php`. With the matching API package installed, +run them from the repository root: + +```bash +vendor/bin/phpunit tests/DocumentationExamplesTest.php +``` + +These tests execute the PHP blocks extracted from the MDX pages, replacing +client creation with a fake transport and local paths with disposable fixtures. +They check request shapes, stream consumption and error handling without a +Docker daemon or real registry credentials. They do not validate daemon-side +builds, mounts, transfers, logging drivers or transport compatibility. The +normal PHP test workflow includes them; the lighter documentation workflow +checks syntax and links only. + +## Tooling updates + +Mintlify is development tooling, not a Composer dependency. Check `npm audit` +when updating it and re-run the validation commands. The initial audit of +`mint` 4.2.986 on 5 October 2026 reported 21 affected dependency packages, +including 18 rated high severity. Some suggested fixes downgrade the CLI; +no forced fixes or dependency overrides have been applied. Review the upstream +fixes before updating the lock file, and use only trusted documentation and +assets with the local tooling. + +## Hosted setup + +The Mintlify project is connected with these settings: + +| Setting | Value | +| --- | --- | +| GitHub repository | `docker-php/docker-php` | +| Deployment branch | `main` | +| `docs.json` in a subdirectory | Enabled | +| Documentation path | `/docs` | +| Configuration file | `docs/docs.json` | + +This uses [Mintlify's monorepo setup](https://www.mintlify.com/docs/deploy/monorepo), +not a separate template repository. The GitHub app installation is restricted to +`docker-php/docker-php`. Review requested permissions before changing that scope; +do not grant access to the Cylo repositories. + +The workspace uses the free Starter plan. Mintlify included a temporary Pro +feature trial during onboarding; these docs use the standard theme and built-in +components and do not depend on Pro features. Do not assume eligibility for +sponsored OSS Pro access or enable a paid upgrade as part of this setup. + +Mintlify deploys from the connected repository. Commit and push only when you +intend those documentation changes to reach the connected site. A dashboard +connection, repository update or custom-domain change can publish the site; +review the draft and confirm the destination before doing that. + +## Before publishing package releases + +- Review the 4.0 migration instructions and test their examples. +- Confirm the connected repository, branch and docs path. +- Check the hosted site's navigation, mobile layout and internal links. +- Configure a custom documentation hostname and DNS separately if needed. +- Keep legacy documentation accessible for users of earlier releases. diff --git a/README.md b/README.md index 27464be66..6f93a2b39 100644 --- a/README.md +++ b/README.md @@ -1,74 +1,180 @@ -# No longer maintained - -I'm backing off maintaining this library due to a lack of motivation, time and usage of docker, contact me on twitter https://twitter.com/joelwurtz if you wish to take over this repository (or just do a fork). - Docker PHP ========== -**Docker PHP** (for lack of a better name) is a [Docker](http://docker.com/) client written in PHP. -This library aim to reach 100% API support of the Docker Engine. - -The test suite currently passes against Docker Remote API v1.25 to v1.36. +**Docker PHP** (for lack of a better name) is a [Docker](https://www.docker.com/) client written in PHP. +This library aims to reach 100% API support of the Docker Engine. -[![Documentation Status](https://readthedocs.org/projects/docker-php/badge/?version=latest)](http://docker-php.readthedocs.org/en/latest/) +[![Documentation](https://img.shields.io/badge/docs-Mintlify-blue?style=flat-square)](https://docker-php.mintlify.site/) [![Latest Version](https://img.shields.io/github/release/docker-php/docker-php.svg?style=flat-square)](https://github.com/docker-php/docker-php/releases) [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE) -[![Build Status](https://img.shields.io/travis/docker-php/docker-php.svg?branch=master&style=flat-square)](https://travis-ci.org/docker-php/docker-php) -[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/docker-php/docker-php.svg?style=flat-square)](https://scrutinizer-ci.com/g/docker-php/docker-php) -[![Quality Score](https://img.shields.io/scrutinizer/g/docker-php/docker-php.svg?style=flat-square)](https://scrutinizer-ci.com/g/docker-php/docker-php) [![Total Downloads](https://img.shields.io/packagist/dt/docker-php/docker-php.svg?style=flat-square)](https://packagist.org/packages/docker-php/docker-php) -[![#docker-php on Slack](http://slack.httplug.io/badge.svg)](http://slack.httplug.io) -Installation ------------- +## Documentation -The recommended way to install Docker PHP is of course to use [Composer](http://getcomposer.org/): +The [version 4.x documentation](https://docker-php.mintlify.site/) is available. +Its source lives in +[docs/](docs/); see [DOCUMENTATION.md](DOCUMENTATION.md) to preview and edit it +locally. The [legacy documentation](https://docker-php.readthedocs.io/en/latest/) +remains available for earlier releases. -```bash -composer require docker-php/docker-php -``` +## New maintainers + +After this repository was archived in 2019, the code was forked in +[beluga-php/docker-php](https://github.com/beluga-php/docker-php), where maintenance +and improvements continued. + +We later contacted [joelwurtz](https://github.com/joelwurtz) and agreed to take over +maintenance of the original `docker-php/docker-php` repository to give you a +better upgrade path. Development will continue here, and we will archive +`beluga-php/docker-php` once the migration is complete. + +Version 4.1 works with Docker Engine API v1.45 to v1.57. See +[Upgrading to 4.0](#upgrading-to-40) below for how to migrate from existing +releases. + +## Requirements + +- PHP 8.2 or later, with the `mbstring` extension. +- [Composer](https://getcomposer.org/). +- Access to a Docker daemon with API v1.45 or later (Docker Engine 26.0 or later). -Docker API Version ------------------- +Docker PHP 4.0 is the last release line that supports PHP 8.1. -By default it will use the last version of docker api available, if you want to fix a version (like 1.25) you can add this -requirement to composer: +## Installation ```bash -composer require "docker-php/docker-php-api:4.1.25.*" +composer require "docker-php/docker-php:^4.0" ``` -Usage ------ +Composer also installs `docker-php/docker-php-api`, choosing the newest API line +unless you require one. See [Docker API versions](#docker-api-versions). -See [the documentation](http://docker-php.readthedocs.org/en/latest/). +## Usage -Unit Tests ----------- +```php +containerList(['all' => true]) as $container) { + printf("%s\t%s\n", $container->getId(), $container->getImage()); +} ``` -$ composer install --dev -``` -Run it using [PHPUnit](http://phpunit.de/): +Endpoint methods return generated models where the API defines a response body. +Their PHPDoc lists accepted parameters, return types and API exceptions. + +`Docker::create()` connects through `unix:///var/run/docker.sock` by default. +Environment variables are optional. See [connection settings](https://docker-php.mintlify.site/connection) +and the [Guzzle examples](https://docker-php.mintlify.site/guides/guzzle) for +custom sockets, remote daemons and TLS configuration. + +For streaming output, see [container logs](https://docker-php.mintlify.site/guides/logs), +[command output](https://docker-php.mintlify.site/guides/exec) and the +[streaming reference](https://docker-php.mintlify.site/reference/streams). +These guides cover callback streams, TTY output and raw response framing. +## Docker API versions + +Each Docker Engine API version has its own `docker-php/docker-php-api` line with +generated endpoints and models. The line uses the four-part version +`Jane-major.Docker-major.Docker-minor.revision`: `7.1.57.0` means Docker API 1.57, +generated with Jane 7, revision 0. To use a specific version, require its line: + +```bash +composer require "docker-php/docker-php:^4.0" "docker-php/docker-php-api:>=7.1.51.0 <7.1.52.0" ``` -$ composer test + +Pin a line if your code names generated models or calls methods that differ +between versions. See the official +[Docker Engine API reference](https://docs.docker.com/reference/api/engine/) for +each version's endpoints, parameters and response schemas. + +The bundled connection factory negotiates the version in request URLs: it uses +the lower of the installed line and the daemon's maximum API version, as the +Docker CLI does. `DOCKER_API_VERSION` or the factory's `api_version` option fix +the version instead. Changing the URL version does not change the generated +models. See [API versions](https://docker-php.mintlify.site/api-versions). + +## Upgrading to 4.0 + +Most applications come from the original docker-php 2.x client or from +`beluga-php/docker-php` 1.45.x. Follow the section for your current package, +then check the [3.x changes](#from-docker-php-3x), because 4.0 also changes +defaults that 2.x and Beluga applications rely on. + +### From docker-php 2.x + +Version 4.1 requires PHP 8.2 or later, PSR-7 v2 and Jane 7-generated models. +Review endpoint signatures, model types and HTTP client dependencies before +upgrading. Check log and exec consumers against the +[streaming documentation](https://docker-php.mintlify.site/reference/streams). + +Change the client requirement to `docker-php/docker-php:^4.0`. Remove an explicit +`docker-php/docker-php-api:4.1.*` requirement, or change it to one API line as +shown above. Update dependencies, test your application and commit its updated +`composer.lock`. + +### From beluga-php + +Version 4.0 continues the client maintained under `beluga-php/docker-php`. +The PHP namespaces remain `Docker` and `Docker\API`. + +Remove the `beluga-php/docker-php` requirement and any explicit +`beluga-php/docker-php-api` requirement from `composer.json`. Add +`docker-php/docker-php:^4.0`; to keep the Beluga v1.45 models, also require +`docker-php/docker-php-api:>=7.1.45.0 <7.1.46.0`. Resolve the package changes +together, then test the application and commit its updated `composer.lock`. + +Install one package family at a time: the Beluga and original packages contain +the same PHP classes. + +### From docker-php 3.x + +- Composer now installs the newest API line unless you require one. Require + `docker-php/docker-php-api:>=7.1.45.0 <7.1.46.0` to keep the 3.x models. +- Requests negotiate the API version with the daemon unless you set one. +- Error statuses the generated endpoints do not handle throw an + `UnexpectedStatusCodeException`. Call `throwOnUnexpectedStatus(false)` to + return `null` instead. +- `Context` applies `.dockerignore`. Call `applyDockerignore(false)` to archive + the whole directory. + +Applications that cannot upgrade yet can stay on `^3.3`. See the +[upgrade guide](https://docker-php.mintlify.site/migration#from-3-x) for model +changes between API versions. + +## Development + +Install dependencies and pull the image used by the integration tests: + +```bash +composer install +docker pull busybox:latest ``` -Contributing ------------- +Run the test suite and static analysis: + +```bash +composer run-script test-ci +composer run-script phpstan +``` -Please see [CONTRIBUTING](CONTRIBUTING.md) for details. +The integration tests create Docker resources on the configured daemon. Use a +development daemon when running them. See [CONTRIBUTING.md](CONTRIBUTING.md) for +contribution instructions. -Credits -------- +## Credits -This README heavily inspired by [willdurand/Negotiation](https://github.com/willdurand/Negotiation) by @willdurand. This guy is pretty awesome. +Docker PHP was created by [Geoffrey Bachelet](https://github.com/ubermuda) and +[Joel Wurtz](https://github.com/joelwurtz). Development continued under +[beluga-php](https://github.com/beluga-php) before the return to the +original repositories. -License -------- +## License -The MIT License (MIT). Please see [License File](LICENSE) for more information. +[MIT](LICENSE). diff --git a/composer.json b/composer.json index 64019814f..2ebc33cea 100644 --- a/composer.json +++ b/composer.json @@ -1,8 +1,40 @@ { "name": "docker-php/docker-php", + "description": "A Docker PHP client", "license": "MIT", "type": "library", - "description": "A Docker PHP client", + "require": { + "php": ">=8.2", + "docker-php/docker-php-api": ">=7.1.45.0 <7.1.58.0", + "nyholm/psr7": "^1.8", + "php-http/client-common": "^2.7", + "php-http/discovery": "^1.19", + "php-http/socket-client": "^2.3", + "psr/http-message": "^2.0", + "symfony/filesystem": "^6.3 || ^7.0 || ^8.0", + "symfony/process": "^6.3 || ^7.0 || ^8.0", + "symfony/serializer": "^6.3 || ^7.0 || ^8.0" + }, + "require-dev": { + "ext-curl": "*", + "ergebnis/composer-normalize": "^2.42", + "friendsofphp/php-cs-fixer": "^3.8", + "guzzlehttp/guzzle": "^7.9 || ^8.0", + "php-parallel-lint/php-parallel-lint": "^1.2", + "phpstan/phpstan": "^1.10 || ^2.0", + "phpunit/phpunit": "^10.5.46", + "psy/psysh": "^0.12.8", + "roave/security-advisories": "dev-latest" + }, + "conflict": { + "beluga-php/docker-php": "*", + "jane-php/json-schema-runtime": "<7.14.4", + "jane-php/open-api-runtime": "<7.14.4", + "nikic/php-parser": "<4.13", + "php-http/message": "<1.16" + }, + "minimum-stability": "dev", + "prefer-stable": true, "autoload": { "psr-4": { "Docker\\": "src/" @@ -13,41 +45,42 @@ "Docker\\Tests\\": "tests/" } }, - "require": { - "php": ">=7.1", - "docker-php/docker-php-api": "4.1.*", - "guzzlehttp/psr7": "^1.2", - "php-http/client-common": "^1.6", - "php-http/socket-client": "^1.3", - "php-http/message": "^1.0", - "symfony/filesystem": "^2.3 || ^3.0 || ^4.0", - "symfony/process": "^2.3 || ^3.0 || ^4.0" - }, - "suggest": { - "php-http/httplug-bundle": "For integration with Symfony", - "amphp/artax": "To use the async api" - }, - "require-dev": { - "phpunit/phpunit": "^6.0", - "friendsofphp/php-cs-fixer": "2.8.1", - "amphp/artax": "^3.0", - "amphp/socket": "^0.10.5" - }, - "conflict": { - "amphp/socket": "<0.10.5", - "amphp/artax": "<3.0" - }, - "scripts": { - "test": "vendor/bin/phpunit", - "test-ci": "vendor/bin/phpunit --coverage-clover build/coverage.xml", - "lint": "vendor/bin/php-cs-fixer fix --dry-run --verbose --diff", - "lint-fix": "vendor/bin/php-cs-fixer fix --verbose" + "config": { + "allow-plugins": { + "ergebnis/composer-normalize": true, + "php-http/discovery": false + }, + "optimize-autoloader": true, + "preferred-install": "dist", + "sort-packages": true }, "extra": { "branch-alias": { - "dev-master": "2.x-dev" + "dev-main": "4.1.x-dev" } }, - "prefer-stable": true, - "minimum-stability": "dev" + "scripts": { + "console": "vendor/bin/psysh", + "lint": "vendor/bin/parallel-lint --exclude vendor .", + "php-cs-fixer": "vendor/bin/php-cs-fixer fix --dry-run --verbose --diff", + "php-cs-fixer-fix": "vendor/bin/php-cs-fixer fix --verbose", + "phpstan": "vendor/bin/phpstan analyse --level 2 src tests/StaticAnalysis", + "phpunit": "vendor/bin/phpunit ./tests/ --coverage-html=./report/coverage/ --testdox-html=./report/testdox.html --disallow-test-output --process-isolation", + "test": [ + "@lint", + "@phpunit" + ], + "test-ci": "vendor/bin/phpunit ./tests/ --disallow-test-output --process-isolation", + "test-coverage": "vendor/bin/phpunit ./tests/ --whitelist=./src/ --coverage-clover=clover.xml", + "test-guzzle": "vendor/bin/phpunit ./tests/GuzzleClientTest.php --disallow-test-output --process-isolation" + }, + "scripts-descriptions": { + "console": "Runs PsySH Console", + "lint": "Runs complete codebase lint testing", + "phpunit": "Runs library test suite", + "test": "Runs all tests", + "test-ci": "Runs library test suite (for continuous integration)", + "test-coverage": "Runs test-coverage analysis", + "test-guzzle": "Runs Guzzle connection examples against local socket fixtures" + } } diff --git a/docs/.mintignore b/docs/.mintignore new file mode 100644 index 000000000..6f3653081 --- /dev/null +++ b/docs/.mintignore @@ -0,0 +1,4 @@ +node_modules +scripts +package.json +package-lock.json diff --git a/docs/api-versions.mdx b/docs/api-versions.mdx new file mode 100644 index 000000000..883277a07 --- /dev/null +++ b/docs/api-versions.mdx @@ -0,0 +1,87 @@ +--- +title: "API versions" +description: "Choose a Docker Engine API version and how requests negotiate with the daemon." +--- + +## Choose an API version + +Docker PHP 4.1 works with Docker Engine API v1.45 to v1.57. Each version has its +own `docker-php/docker-php-api` release line with generated endpoints and +models. Without a direct API requirement, Composer installs the newest line. + +To use a specific version, require its line next to the client: + +```bash +composer require "docker-php/docker-php:^4.0" "docker-php/docker-php-api:>=7.1.51.0 <7.1.52.0" +``` + +Pin a line if your code names generated models or calls methods that differ +between versions. Docker renames models and changes fields between API versions; +for example, API 1.48 replaced `ContainersIdJsonGetResponse200` with +`ContainerInspectResponse`, and API 1.52 removed `getError()` from build, pull and +push progress frames. Check Docker's +[API version history](https://docs.docker.com/reference/api/engine/version-history/) +and the [Docker Engine API reference](https://docs.docker.com/reference/api/engine/) +for the version you use. + +## Package versions + +`docker-php/docker-php` follows semantic versioning. + +`docker-php/docker-php-api` uses a four-part scheme: +`Jane-major.Docker-major.Docker-minor.revision`. For example, `7.1.57.0` means +Docker Engine API v1.57, generated with Jane 7, revision 0. Keep a direct API +requirement within one line, as above. A constraint such as `^7.1.45.0` allows +every newer Docker specification. + +## Request URL version + +The bundled factory negotiates the version in request URLs. Before the first +request it sends an unversioned `/_ping` and reads the daemon's maximum API +version from the response. Requests then use the lower of that version and the +installed API line, as the Docker CLI does. An older daemon keeps working with a +newer API package, and requests never ask for a version the installed models do +not describe. `DockerClientFactory::defaultApiVersion()` returns the installed +line's version. + +To skip negotiation, set the version yourself. `DOCKER_API_VERSION` sets it from +the environment: + +```bash +DOCKER_API_VERSION=1.51 php your-script.php +``` + +The factory's `api_version` option sets it in PHP and overrides the environment: + +```php + 'unix:///var/run/docker.sock', + 'api_version' => '1.51', +]); +$docker = Docker::create($httpClient, [], [], false); +``` + +Both `1.51` and `v1.51` are accepted. The fourth argument disables the generated +server plugins because the factory already adds the API path. + +A client you build yourself, such as [Guzzle](/guides/guzzle), does not negotiate. +The generated server plugins prefix requests with the installed line's version, +so install a line your daemon supports. + + +Changing the URL version does not regenerate models or add newer fields and +endpoints. With an older daemon, fields added after its API version are absent +from responses and ignored in requests. + + +## Generated code + +Each line is generated from Docker's specification for that version with Jane +7.14.4, without local patches. The API repository has one branch per line, +such as [`7.1.57`](https://github.com/docker-php/docker-php-api/tree/7.1.57); see its +[generation instructions](https://github.com/docker-php/docker-php-api#generation). diff --git a/docs/async.md b/docs/async.md deleted file mode 100644 index 2411e9dc4..000000000 --- a/docs/async.md +++ /dev/null @@ -1,52 +0,0 @@ -# Asynchronous Client - -Starting from 2.0, Docker-PHP proposes an Asynchronous PHP Client using [Amp](https://amphp.org/) and -[Artax](https://amphp.org/artax/). - -## Installation - -Since it's optional you will have to require artax with composer to use it: - -``` -composer require amphp/artax:^3.0 -``` - -## Usage - -Then you can use the `DockerAsync` API Client: - -```php -setImage('busybox:latest'); - $containerConfig->setCmd(['echo', '-n', 'output']); - $containerConfig->setAttachStdout(true); - $containerConfig->setLabels(new \ArrayObject(['docker-php-test' => 'true'])); - - $response = yield $docker->imageCreate(null, [ - 'fromImage' => 'busybox:latest', - ], DockerAsync::FETCH_RESPONSE); - - yield $response->getBody(); - - $containerCreate = yield $docker->containerCreate($containerConfig); - $containerStart = yield $docker->containerStart($containerCreate->getId()); - /** @var \Docker\API\Model\ContainersIdJsonGetResponse200 $containerInfo */ - $containerInfo = yield $docker->containerInspect($containerCreate->getId()); - - var_dump($containerInfo->getName()); -}); -``` - -API of `DockerAsync` is exactly the same as `Docker`, at the exception that each endpoint will always return an `Amp\Promise` -object, which allows to you to do parallelism and await them with the `yield` keyword. - -If you are not familiar with this kind of API, please look at the [Amp documentation on that subject](https://amphp.org/getting-started/) diff --git a/docs/basic.md b/docs/basic.md deleted file mode 100644 index 52a7f200a..000000000 --- a/docs/basic.md +++ /dev/null @@ -1,19 +0,0 @@ -# Basic Usage - -`Docker\Docker` API Client offers all endpoints available for your version of Docker. Each endpoint has a strong PHPDoc -documentation in its comment, so the best way to know what values to set for an endpoint and what it returns is to go -directly to the endpoint documentation in the code. - -As an example for listing container you can do: - -```php -containerList(); - -foreach ($containers as $container) { - var_dump($container->getNames()); -} -``` diff --git a/docs/basic.mdx b/docs/basic.mdx new file mode 100644 index 000000000..a9e65e096 --- /dev/null +++ b/docs/basic.mdx @@ -0,0 +1,72 @@ +--- +title: "Basic usage" +description: "Create a client, call endpoints, and work with generated models." +--- + +## List containers + +```php +containerList(['all' => true]) as $container) { + printf("%s\t%s\n", $container->getId(), $container->getImage()); +} +``` + +By default the client connects to `unix:///var/run/docker.sock`. +See [Connection settings](/connection) for remote daemons and TLS. + +`Docker::create()` makes a system-info request to the daemon. Creating the +client therefore requires a working connection and permission for that request. + +## Endpoint parameters + +Endpoint methods accept generated request models and query-parameter arrays. +The PHPDoc in [the generated client](https://github.com/docker-php/docker-php-api/blob/main/src/Client.php) +lists the accepted parameters, response models and API exceptions. + +For example, `containerList(['all' => true])` includes stopped containers. +Filters use the JSON format accepted by Docker: + +```php +$containers = $docker->containerList([ + 'filters' => json_encode(['status' => ['running']], JSON_THROW_ON_ERROR), +]); +``` + +Use [generated models](https://github.com/docker-php/docker-php-api/tree/main/src/Model) +for request bodies, such as `ContainersCreatePostBody`. Read response fields +through their getters. Some fields are nullable or absent depending on the +daemon response. + +Most methods follow this order: resource ID, request body if applicable, query +parameters, header parameters if applicable, and fetch mode. Parameters which +do not apply are omitted from the method signature, so do not assume the same +argument positions for every endpoint. For example, `containerList()` takes +query parameters first, while `containerCreate()` takes a request model first. + +The client sends these requests to the daemon; it does not run the Docker CLI. +Container commands are arrays of arguments, not shell command strings. Use an +explicit shell such as `['sh', '-c', '...']` only when you need shell behavior, +and never interpolate untrusted input into that shell command. + +See [Requests and responses](/reference/requests-and-responses) for JSON-valued +query parameters, generated models, raw responses and error handling. + +## Streaming endpoints + +Pulling or building an image, reading logs, and starting an attached exec command +can return callback streams. Register callbacks and call `wait()` to consume +them. See [container logs](/guides/logs), [command output](/guides/exec) and +[image builds](/cookbook/build-image) for examples. + +Not every streaming endpoint has a callback wrapper. Archive downloads need a +raw response. The +[streaming reference](/reference/streams) lists the differences and links to +the relevant recipes. diff --git a/docs/connection.md b/docs/connection.md deleted file mode 100644 index 92c152125..000000000 --- a/docs/connection.md +++ /dev/null @@ -1,74 +0,0 @@ -# Connecting to Docker - -## Default, with environment variables - -By default, Docker-PHP uses the the same environment variables as the Docker command line to connect to a running `docker daemon`: - - * `DOCKER_HOST`: tcp address for the docker daemon (i.e. tcp://127.0.0.1:2376) - * `DOCKER_TLS_VERIFY`: if set to true use tls for authentication of the client - * `DOCKER_CERT_PATH`: path for the client certificates to use for authentication - * `DOCKER_PEER_NAME`: peer name of the docker daemon (as set in the certificate) - -If the `DOCKER_HOST` environment variable is not set, it will use `unix:///var/run/docker.sock` as the default tcp address. - -```php - 'tcp://127.0.0.1:2375', - 'ssl' => false, -]); -$docker = Docker::create($client); -``` - -Since `DockerClientFactory` will create a `Http\Client\Socket\Client`, you can go on the -[official documentation of the socket client](http://docs.php-http.org/en/latest/clients/socket-client.html) -to learn about possible options. - -## Custom client - -In fact `Docker\Docker` accepts any client from [Httplug](http://httplug.io/) (respecting the `Http\Client\HttpClient` interface). - -So you can use [React](https://github.com/reactphp/http-client), [Guzzle](http://docs.guzzlephp.org/en/latest/) -or any [other adapters / clients](http://docs.php-http.org/en/latest/clients.html). - - -```php - +Access to a Docker socket is privileged. Use a development daemon for examples +that create containers or images, and do not expose an unauthenticated daemon +to an untrusted network. + + +## TCP and HTTP + +The factory accepts both `tcp://` and `http://` daemon addresses: + +```bash +DOCKER_HOST=tcp://docker.example.com:2375 php your-script.php +DOCKER_HOST=http://docker.example.com:2375 php your-script.php +``` + +These connections are unencrypted unless TLS is enabled. An `http://` address +without a port uses port `80`; use the daemon's configured port explicitly if +it differs. + +## TLS connections + +Use the daemon's TCP address and its client certificates: + +```bash +export DOCKER_HOST=tcp://docker.example.com:2376 +export DOCKER_TLS_VERIFY=1 +export DOCKER_CERT_PATH=/path/to/client-certificates +php your-script.php +``` + +The certificate directory must contain `ca.pem`, `cert.pem` and `key.pem`. +If needed, set `DOCKER_PEER_NAME` to the name used to verify the server +certificate. Set `DOCKER_TLS_VERIFY` to exactly `1` to enable this certificate +configuration. + +An `https://` address also enables TLS, even without `DOCKER_TLS_VERIFY`: + +```bash +DOCKER_HOST=https://docker.example.com:2376 php your-script.php +``` + +Without a port, HTTPS uses port `443`. By default, the server certificate must +be trusted by PHP's configured certificate authorities and match the daemon's +hostname. For a private CA or mutual TLS, use `DOCKER_TLS_VERIFY=1` and +`DOCKER_CERT_PATH` as above; `https://` works with those settings too. + +## Factory options + +Environment variables are optional. You can configure the bundled socket +client directly in PHP instead: + +```php + 'unix:///var/run/docker.sock', + 'api_version' => '1.51', + 'timeout' => 10000, +]); + +$docker = Docker::create($httpClient, [], [], false); +``` + +The fourth argument disables the generated server plugins. The factory already +adds the daemon address and versioned path. See +[the factory implementation](https://github.com/docker-php/docker-php/blob/main/src/DockerClientFactory.php) +for the plugins it configures. + +`api_version` fixes the request path in PHP, even if `DOCKER_API_VERSION` is set +on the process. It accepts `1.51`, `v1.51` or `/v1.51`. If omitted, the factory +uses `DOCKER_API_VERSION`; without either, it +[negotiates](/api-versions#request-url-version) with the daemon. The timeout is +in milliseconds. + +For a private CA without client certificates, pass the CA file directly: + +```php + 'https://docker.example.com:2376', + 'stream_context_options' => [ + 'ssl' => ['cafile' => '/path/to/ca.pem'], + ], +]); +``` + +For mutual TLS, add `local_cert` and `local_pk` to the SSL options: + +```php + 'https://docker.example.com:2376', + 'stream_context_options' => [ + 'ssl' => [ + 'cafile' => '/path/to/ca.pem', + 'local_cert' => '/path/to/cert.pem', + 'local_pk' => '/path/to/key.pem', + ], + ], +]); + +$docker = Docker::create($httpClient, [], [], false); +``` + +The factory keeps the socket client's options, including timeouts and SSL +context options. An HTTPS address always enables TLS, including when `ssl` +is set to `false`; use `http://` or `tcp://` for a plaintext connection. + +## Custom HTTP clients + +`Docker::create($httpClient)` accepts a compatible PSR-18 HTTP client. Configure +its daemon address, TLS options and socket support. Check that it also supports +unbuffered responses and Docker's upgraded connections if you use log, attach +or exec streams. + +See [HTTP clients](/guides/guzzle) for a comparison of the bundled client and +Guzzle, with PHP examples and their streaming limits. For a socket client with +your own plugin chain, see +[the streaming decoder example](/reference/streams#custom-socket-clients). + +`api_version` and `DOCKER_API_VERSION` affect the factory's request path; neither +changes the generated models. See [API versions](/api-versions). diff --git a/docs/contributing.mdx b/docs/contributing.mdx new file mode 100644 index 000000000..e213557fa --- /dev/null +++ b/docs/contributing.mdx @@ -0,0 +1,62 @@ +--- +title: "Contribute to the docs" +description: "Edit the Git-maintained documentation and preview it locally." +--- + +The documentation lives in the `docs/` directory of +[docker-php/docker-php](https://github.com/docker-php/docker-php). Pages are MDX +files; `docs.json` defines their navigation and site settings. + +## Preview locally + +Use Node.js 22 or 24 LTS and PHP 8.2 or later. From the repository root: + +```bash +cd docs +npm ci +npm run dev +``` + +Open the localhost URL printed by Mintlify. The preview updates when you edit +pages. Stop it with Ctrl+C. + +## Check changes + +```bash +npm run validate +npm run check:links +npm run check:examples +``` + +The checks validate Mintlify configuration and MDX, internal links and heading +anchors, and PHP example syntax. Syntax checks do not prove an example's daemon +behavior. Test operational examples separately against a development daemon. + +The [Guzzle connection examples](/guides/guzzle) have a separate test suite. +After installing the development dependencies, run it from the repository root: + +```bash +composer test-guzzle +``` + +These tests execute the documented PHP snippets against temporary local Unix, +HTTP and HTTPS servers. They do not need a Docker daemon. They also check +certificate rejection, client certificates, request bodies, API errors and +the handlers' streaming behavior. + +Add new pages to `docs.json`, use site-relative links such as `/connection`, and +keep examples aligned with the current API models. Do not edit generated API +code to make an example work. + +Keep unreleased instructions clearly marked until their packages are published. +Avoid documenting legacy `DockerAsync` behavior as part of 4.0. + +## Pull requests + +Commit messages must follow +[Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/). +For example, `docs: explain exec stream callbacks`. + +See [CONTRIBUTING.md](https://github.com/docker-php/docker-php/blob/main/CONTRIBUTING.md) +for the library's contribution workflow. Report documentation errors through +[GitHub issues](https://github.com/docker-php/docker-php/issues). diff --git a/docs/cookbook/build-image.md b/docs/cookbook/build-image.md deleted file mode 100644 index 71a5d4bc1..000000000 --- a/docs/cookbook/build-image.md +++ /dev/null @@ -1,81 +0,0 @@ -# Building an Image - -In order to build an image you need to provide the `$inputStream` variable which correspond to the tar binary of a -folder containing a `Dockerfile` (or another name by using the `dockerfile` parameters) and other files used during the -build. - -Since `Docker` build directory can be heavy, Docker PHP override this call and allows passing a `resource` or a -`Psr\Http\Message\StreamInterface` instance (string is also possible but not recommended). -This avoid using too much memory in PHP. - -## Build return - -This function can return 3 different objects depending on the value of the `$fetch` parameter: - -### Docker::FETCH_OBJECT - -This is default mode, where this function will block until the build is finished and return an array of `BuildInfo` -object. - -This object contains the log of the build: - -```php -imageBuild($inputStream); -$buildStream->onFrame(function (BuildInfo $buildInfo) { - echo $buildInfo->getStream(); -}); - -$buildStream->wait(); -``` - -### Docker::FETCH_RESPONSE - -The build function will return the raw [PSR7](http://www.php-fig.org/psr/psr-7/) Response. It's up to you to handle -decoding and receiving correct output in this case. - -## Context - -Docker PHP provides a `ContextInterface` and a default `Context` object for creating the `$inputStream` of the build -method. - -```php -toStream(); -$docker = Docker::create(); - -$docker->imageBuild($inputStream); -``` - -You can safely use this context object to build image with a huge directory to size without consuming any memory or disk -on the PHP side as it will directly pipe the output of a `tar` process into the Docker Remote API. - -### Context Builder - -Additionally you can use the `ContextBuilder` to have a dynamic generation of your `Dockerfile`: - -```php -from('ubuntu:latest'); -$contextBuilder->run('apt-get update && apt-get install -y php5'); - -$docker = Docker::create(); -$docker->imageBuild($contextBuilder->getContext()->toStream()); -``` - diff --git a/docs/cookbook/build-image.mdx b/docs/cookbook/build-image.mdx new file mode 100644 index 000000000..0423ff046 --- /dev/null +++ b/docs/cookbook/build-image.mdx @@ -0,0 +1,177 @@ +--- +title: "Build an image" +description: "Stream a build context and consume Docker's build output." +--- + +The image-build endpoint accepts a tar archive containing a Dockerfile and its +build files. `Docker\Context\Context` can stream a directory through the system +`tar` command without first loading the whole archive into a PHP string. + +Create a `build/Dockerfile` next to your PHP script: + +```dockerfile +FROM busybox:latest +CMD ["sh", "-c", "printf 'hello\\n'"] +``` + +Then build it on a development daemon: + +```php +imageBuild($context->toStream(), ['t' => 'docker-php-example:latest']); +$build->onFrame(function (BuildInfo $frame): void { + $error = FrameError::message($frame); + if ($error !== null) { + throw new RuntimeException($error); + } + + echo $frame->getStream() ?? ''; +}); +$build->wait(); +``` + +`imageBuild()` returns a `BuildStream` in the default fetch mode, not an array +of completed build results. The callback receives generated `BuildInfo` models. +Check the frames for daemon-reported build errors as well as handling endpoint +exceptions. + +`Context` requires GNU or BSD `tar` on the machine running PHP. It leaves out +the paths a `.dockerignore` file in the context directory excludes, as +`docker build` does. Patterns follow the Docker CLI: `*`, `?`, character +classes, `**` for any number of directories, `!` to re-include a path, and the +last matching pattern wins. The `Dockerfile` and `.dockerignore` are always +sent, because the daemon reads them; it then drops them if your patterns +exclude them. If you build with a differently named Dockerfile through the +`dockerfile` option, add a `!` exception for it. + +To archive the whole directory, as 3.x did by default: + +```php +$context = (new Context(__DIR__ . '/build'))->applyDockerignore(false); +``` + +The example leaves the tagged image on your development daemon. Remove that +specific image when you no longer need it. + +## Build arguments and other query options + +JSON-valued build options are strings. Continue with the `$docker` client from +above, but create a fresh context for each request: + +```php +$context = new Context(__DIR__ . '/build'); +$build = $docker->imageBuild($context->toStream(), [ + 't' => 'docker-php-example:configured', + 'dockerfile' => 'Dockerfile', + 'buildargs' => json_encode(['APP_MODE' => 'development'], JSON_THROW_ON_ERROR), + 'labels' => json_encode(['docker-php-example' => 'true'], JSON_THROW_ON_ERROR), + 'nocache' => true, + 'pull' => 'true', +]); +$build->onFrame(function (BuildInfo $frame): void { + $error = FrameError::message($frame); + if ($error !== null) { + throw new RuntimeException($error); + } + echo $frame->getStream() ?? ''; +}); +$build->wait(); +``` + +`pull` is string-valued in this specification, while `nocache` is boolean. +Do not pre-URL-encode the JSON options. Declare `ARG APP_MODE` in the Dockerfile +if the build uses it. Build arguments are not a safe channel for secrets. + +To apply several tags, pass a list to `t`, for example +`'t' => ['docker-php-example:latest', 'docker-php-example:1.0']`. Docker PHP +sends one `t` parameter per tag. Lists require client `3.3.0` or later. + +A streamed context is consumed by the first request. The original tar process +is not rewindable. Keep the context alive until the request has +finished, and do not assume a process-backed stream has a known byte length. + +## Construct a small context in PHP + +`ContextBuilder` creates a temporary context directory and a Dockerfile. It is +useful when the build has a few generated files, without maintaining a separate +directory in your application: + +```php +use Docker\Context\ContextBuilder; + +$builder = new ContextBuilder(); +$context = $builder + ->from('busybox:latest') + ->workdir('/example') + ->add('message.txt', "hello from the build context\n") + ->command('cat /example/message.txt') + ->getContext(); + +$build = $docker->imageBuild($context->toStream(), ['t' => 'docker-php-example:generated']); +$build->onFrame(function (BuildInfo $frame): void { + $error = FrameError::message($frame); + if ($error !== null) { + throw new RuntimeException($error); + } + echo $frame->getStream() ?? ''; +}); +$build->wait(); +``` + +The builder's context is cleaned up when the `Context` is destroyed. It is +not a complete Dockerfile parser or a Buildx replacement. Prefer an ordinary +Dockerfile when the build needs features the helper does not express. + +## Private base images + +Pass a registry credential **map** in `X-Registry-Config`, not the single +`X-Registry-Auth` object used for pull/push. For example, construct the header +from credentials already held in `$username` and `$token`: + +```php +$registryConfig = base64_encode(json_encode([ + 'registry.example.com' => [ + 'username' => $username, + 'password' => $token, + ], +], JSON_THROW_ON_ERROR)); + +$context = new Context(__DIR__ . '/build'); +$build = $docker->imageBuild( + $context->toStream(), + ['t' => 'docker-php-example:private-base'], + ['X-Registry-Config' => $registryConfig] +); +$build->onFrame(function (BuildInfo $frame): void { + $error = FrameError::message($frame); + if ($error !== null) { + throw new RuntimeException($error); + } + echo $frame->getStream() ?? ''; +}); +$build->wait(); +``` + +See [registry authentication](/guides/registry) for credential handling. Docker +Hub's legacy key for this header is `https://index.docker.io/v1/`, rather than +just its hostname. Do not include registry-config headers in request logs. + +## Builder backend limits + +Docker's specification defaults the `version` query parameter to the classic builder +(`'1'`). Whether that builder is available depends on your daemon. Merely +setting `version => '2'` does not implement BuildKit session handling, secret +mounts, SSH forwarding or Buildx workflows in this client. Validate the backend +and required features against your development daemon; these examples are not +a promise of full BuildKit support. diff --git a/docs/cookbook/container-config.mdx b/docs/cookbook/container-config.mdx new file mode 100644 index 000000000..4ec8bfcac --- /dev/null +++ b/docs/cookbook/container-config.mdx @@ -0,0 +1,89 @@ +--- +title: "Configure a container" +description: "Combine ports, mounts, environment variables and restart policy in a request." +--- + +Container creation is a nested request. Publishing a port belongs in +`HostConfig`, while the container-side port declaration belongs in +`ContainersCreatePostBody`. Declaring an exposed port alone does not publish it. + +## Ports, a bind mount and restart policy + +This example creates, but does not start, a development container. Pull +`nginx:alpine` first using the [image pull recipe](/guides/registry). Create +`/srv/docker-php-example/html` on the **daemon host**, with an `index.html` file, +before running it. Choose an unused example name and host port. + +```php +setHostIp('127.0.0.1'); +$binding->setHostPort('8080'); + +$mount = new Mount(); +$mount->setType('bind'); +$mount->setSource('/srv/docker-php-example/html'); +$mount->setTarget('/usr/share/nginx/html'); +$mount->setReadOnly(true); + +$restart = new RestartPolicy(); +$restart->setName('no'); + +$host = new HostConfig(); +$host->setPortBindings(new ArrayObject(['80/tcp' => [$binding]])); +$host->setMounts([$mount]); +$host->setRestartPolicy($restart); + +$body = new ContainersCreatePostBody(); +$body->setImage('nginx:alpine'); +$body->setEnv(['EXAMPLE_MODE=development']); +$body->setLabels(new ArrayObject(['docker-php-example' => 'true'])); +$body->setExposedPorts(new ArrayObject(['80/tcp' => new ArrayObject()])); +$body->setHostConfig($host); + +$created = $docker->containerCreate($body, ['name' => 'docker-php-example-web']); +printf("Created %s\n", $created->getId()); +``` + +Review the returned ID, then use `containerStart($created->getId())` to start +that container. The example deliberately leaves it stopped. Remove only that +created container when you are done; do not use a broad prune operation. + +## Details worth checking + +- Port keys include the protocol: `80/tcp` and `80/udp` are different entries. +- Each port maps to a **list** of `PortBinding` models, even for one binding. +- `HostPort` is a string. An empty string requests a daemon-assigned host port; + inspect the container after starting it to discover the binding. +- `HostIp` above binds the published port to the daemon host's loopback address. + It does not refer to the PHP client's machine when using a remote daemon. +- Bind-mount source paths are on the daemon host, not the PHP client. Docker + Desktop may add another host/VM file-sharing boundary. +- Mounting over a container path hides its existing contents. A read-only mount + still exposes its files to the container, so do not mount secrets casually. +- Environment entries are `NAME=value` strings. Do not log sensitive values or + treat ordinary container environment variables as a secret store. +- `containerCreate()` does not pull a missing image. Pull and check the progress + stream before creating the container. + +An explicit restart policy makes example lifecycle behavior clear. For an +application which should retry failed runs, use `on-failure` and set +`MaximumRetryCount`; do not set that count as a general limit on `always` or +`unless-stopped`. + +For networking beyond port publication, look at `NetworkingConfig` and its +`EndpointsConfig` map of `EndpointSettings` models. Keep network attachment +and port publication separate; attaching to a network does not expose a port +on the host. diff --git a/docs/cookbook/container-run.md b/docs/cookbook/container-run.md deleted file mode 100644 index 2ee824bff..000000000 --- a/docs/cookbook/container-run.md +++ /dev/null @@ -1,251 +0,0 @@ -# Running a container - -Running a container in Docker PHP like it would be done with the docker client `docker run image command` is not a -single call to api, even with the docker run command, it involves multiple calls to the API. - -## Creating the container - -First step is to create a container and its associated configuration, by creating a `ContainerConfig` instance and -passing to the `create` api endpoint. - -```php -setImage('busybox:latest'); -$containerConfig->setCmd(['echo', 'I am running a command']); - -$containerCreateResult = $docker->containerCreate($containerConfig); -``` - -This will return a `ContainersCreatePostResponse201` object with the id of the created container. If you don't want to use -container id you can also specify a unique name for this container: - -```php -$containerCreateResult = $docker->containerCreate($containerConfig, ['name' => 'my-container-unique-name']); -``` - -Be aware that the container is immutable if you need to change a configuration for a container, you will need to remove -the existing one and create it again with the new configuration. - -## Starting the container - -Once a container has been created, you can start it, this will in fact, only launch the process inside the isolated -container. This is done with the `containerStart` method, you can use the id of the container or the -name: - -```php -$docker->containerStart($containerCreateResult->getId()); -// Or -$docker->containerStart('my-container-unique-name'); -``` - -The start method will always return the raw [PSR7](http://www.php-fig.org/psr/psr-7/) Response, but you don't need -to check it as on failure it will throw an exception. - -## Waiting for the container to end - -Once your container is started you can wait for it end by using the `containerWait` method, be aware that your PHP script will -block until the container has stopped or that the default timeout set on the client has been reached (default to 60 -seconds) - -```php -$docker->containerWait('my-container-unique-name'); -``` - -## Stopping the container - -Once your container is started you can stop it by using the `containerStop` method. You can use the id of the container or the name: - -```php -$docker->containerStop($containerCreateResult->getId()); -// Or -$docker->containerStop('my-container-unique-name'); -``` - - -## Reading logs in real time - -Sometimes you will need to read logs in real time for a container. You can use the `containerAttach` method for that. -Be aware that you will only receive them if you configure the container with -[json log driver](https://docs.docker.com/engine/reference/logging/overview/), which is the default configuration. - -```php -$attachStream = $docker->containerAttach('my-container-unique-name'); -``` - -The `$attachStream` returned will be an instance of a `DockerRawStream`. You can use this object afterwards to add -callbacks on the different streams: - - * `addStdin` to add a callback on the stdin stream - * `addStdout` for the stdout stream - * `addStderr` for the stderr stream - -The callback for each of this method takes a string for the first argument which correspond to the log line. - -Use then the wait method to activate real time logging, this method will only stop when then stream is closed which -correspond to when the container has stopped. - -```php -$attachStream->onStdout(function ($stdout) { - echo $stdout; -}); -$attachStream->onStderr(function ($stderr) { - echo $stderr; -}); - -$attachStream->wait(); -``` - -If you follow all the example, you will not see the log and this normal. In fact the container and the call to the attach -method need extra configuration: - -```php -$containerConfig = new ContainersCreatePostBody(); -$containerConfig->setImage('busybox:latest'); -$containerConfig->setCmd(['echo', 'I am running a command']); -// You need to attach stream of the container to docker -$containerConfig->setAttachStdin(true); -$containerConfig->setAttachStdout(true); -$containerConfig->setAttachStderr(true); - -$docker->containerCreate($containerConfig, ['name' => 'my-container-unique-name']); - -// You also need to set stream to true to get the logs, and tell which stream you want to attach -$attachStream = $docker->containerAttach('my-container-unique-name', [ - 'stream' => true, - 'stdin' => true, - 'stdout' => true, - 'stderr' => true -]); -$docker->containerStart('my-container-unique-name'); - -$attachStream->onStdout(function ($stdout) { - echo $stdout; -}); -$attachStream->onStderr(function ($stderr) { - echo $stderr; -}); - -$attachStream->wait(); -``` - -If you read the following example, you will notice that we call the `containerAttach` method before starting the container with -`containerStart`. This is normal, as otherwise during the time the container is started and the call to the `containerAttach` endpoint -some logs may have been processed and you will loose this information. That's why it is strongly recommended to attach -the container before starting it. - -## Interacting with a container - -WIth the last example we can now read the log a container in real time. However you may need to send input to this -container. This can be done by attaching a websocket with the `containerAttachWebsocket` method:` - -```php -$webSocketStream = $docker->containerAttachWebsocket('my-container-unique-name', [ - 'stream' => true, - 'stdout' => true, - 'stderr' => true, - 'stdin' => true, -]); -``` - -The returned stream will be an instance of `AttachWebsocketStream` and it can be used to both reading and writing to -the container: - -```php -$line = $webSocketStream->read(); -$websocketStream->write('i send input to the container'); -``` - -If the `$line` is `null` then the stream is no longer available (container is certainly stopped), if it's equal to -`false` then the stream is still available but no output was received, otherwise it will return output from the container. - -To actually write on the stream (having the stdin stream open) you will, again, need extra configuration when creating -the container: - -```php -// Open the stdin stream from docker engine to the container -$containerConfig->setOpenStdin(true); -// Needed if you want to use process that rely on a tty, be aware as there is, in fact, no tty this may cause bug to -// the underlying process in your container -$containerConfig->setTty(true); -``` - -Be aware that there is no distinction between stdout and stderr in this mode. - -## Port Mapping - -This example shows how you can map port 8080 on your host machine to port 80 on the container. - -```php -setTty(true); -$containerConfig->setExposedPorts(['80/tcp' => new \stdClass]); - -$portBinding = new PortBinding(); -$portBinding->setHostPort('8080'); -$portBinding->setHostIp('0.0.0.0'); - -$portMap = new \ArrayObject(); -$portMap['80/tcp'] = [$portBinding]; - -$hostConfig = new HostConfig(); -$hostConfig->setPortBindings($portMap); - -$containerConfig->setHostConfig($hostConfig); -``` - -## Executing a command on a running container - -This example shows how you can execute an command on any running container. It is same as `docker exec CONTAINER_ID some_command `. - -```php -setTty(true); -$execConfig->setAttachStdout(true); -$execConfig->setAttachStderr(true); -$execConfig->setCmd(['mkdir', '/tmp/testDir']); - -$execid = $docker->containerExec('android',$execConfig)->getId(); -$execStartConfig = new ExecIdStartPostBody(); -$execStartConfig->setDetach(false); - -// Execute the command -$stream = $docker->execStart($execid,$execStartConfig); - -// To see the output stream of the 'exec' command -$stdoutText = ""; -$stderrText = ""; - -$stream->onStdout(function ($stdout) use (&$stdoutText) { - $stdoutText .= $stdout; -}); - -$stream->onStderr(function ($stderr) use (&$stderrText) { - $stderrText .= $stderr; -}); - -$stream->wait(); -var_dump([ "stdout" => $stdoutText, "stderr" => $stderrText ]) ; -``` diff --git a/docs/cookbook/container-run.mdx b/docs/cookbook/container-run.mdx new file mode 100644 index 000000000..0a5761607 --- /dev/null +++ b/docs/cookbook/container-run.mdx @@ -0,0 +1,90 @@ +--- +title: "Run a container" +description: "Pull an image, create a container, start it, and read its output." +--- + +Docker's `run` operation involves several API calls. First make sure the image +exists on the daemon, then create and start the container. + + +This example creates a container and pulls an image on the configured daemon. +Run it against a development daemon. + + +```php +imageCreate(null, [ + 'fromImage' => 'busybox', + 'tag' => 'latest', +]); +$pull->onFrame(function (CreateImageInfo $frame): void { + $error = FrameError::message($frame); + if ($error !== null) { + throw new RuntimeException($error); + } +}); +$pull->wait(); + +$config = new ContainersCreatePostBody(); +$config->setImage('busybox:latest'); +$config->setCmd(['sh', '-c', 'printf "hello\n"']); +$config->setAttachStdout(true); +$config->setAttachStderr(true); +$config->setTty(false); + +$container = $docker->containerCreate($config); +$id = $container->getId(); + +try { + $docker->containerStart($id); + $result = $docker->containerWait($id, ['condition' => 'not-running']); + if ($result->getError()?->getMessage() !== null) { + throw new RuntimeException($result->getError()->getMessage()); + } + + $logs = $docker->containerLogs($id, ['stdout' => true, 'stderr' => true]); + $logs->onStdout(function (string $chunk): void { + echo $chunk; + }); + $logs->onStderr(function (string $chunk): void { + fwrite(STDERR, $chunk); + }); + $logs->wait(); + + printf("Exit code: %d\n", $result->getStatusCode()); +} finally { + $docker->containerDelete($id, ['force' => true]); +} +``` + +The cleanup removes only the container created by this example. If you need to +inspect it afterwards, adapt the cleanup for your development workflow. + +Use `containerInspect($id)` for its current state and `containerStop($id)` to +stop a running container. These endpoints throw API exceptions on errors; +do not depend on a raw response being returned by `containerStart()`. + +For live output, see [Container logs](/guides/logs). To run another command in +an existing container, see [Command output](/guides/exec). + +`containerWait()` blocks; it is not a background task. `not-running` waits for +the current stopped state, while `next-exit` waits for a subsequent exit. Pick +the condition which matches your lifecycle and configure transport timeouts +accordingly. `getStatusCode()` on its response is the **container exit code**, +not the HTTP status. A non-zero command exit is separate from a failed API +request. + +Avoid `AutoRemove` for this particular recipe: Docker can remove the container +before the log/inspect calls which follow the wait. For production orchestration, +decide who owns cleanup and do not let an unconditional cleanup exception hide +the original operation failure. diff --git a/docs/docs.json b/docs/docs.json new file mode 100644 index 000000000..81822a5d9 --- /dev/null +++ b/docs/docs.json @@ -0,0 +1,69 @@ +{ + "$schema": "https://mintlify.com/docs.json", + "theme": "mint", + "name": "Docker PHP", + "description": "Documentation for the Docker PHP 3.0 client and its generated Docker Engine API models.", + "colors": { + "primary": "#1D63ED", + "light": "#1D63ED", + "dark": "#60A5FA" + }, + "navigation": { + "groups": [ + { + "group": "Get started", + "pages": ["index", "installation", "connection", "basic"] + }, + { + "group": "Guides", + "pages": [ + "guides/guzzle", + "cookbook/container-run", + "cookbook/container-config", + "guides/logs", + "guides/exec", + "guides/interactive-exec", + "cookbook/build-image", + "guides/registry", + "guides/archives", + "guides/image-transfer", + "guides/events-and-stats" + ] + }, + { + "group": "Reference", + "pages": [ + "reference/requests-and-responses", + "reference/streams", + "api-versions", + "migration", + "contributing" + ] + } + ] + }, + "navbar": { + "links": [ + { + "label": "Engine API", + "href": "https://docs.docker.com/reference/api/engine/" + }, + { + "label": "Issues", + "href": "https://github.com/docker-php/docker-php/issues" + } + ], + "primary": { + "type": "github", + "href": "https://github.com/docker-php/docker-php" + } + }, + "footer": { + "socials": { + "github": "https://github.com/docker-php/docker-php" + } + }, + "redirects": [ + { "source": "/async", "destination": "/migration#asynchronous-client" } + ] +} diff --git a/docs/guides/archives.mdx b/docs/guides/archives.mdx new file mode 100644 index 000000000..90d6878b2 --- /dev/null +++ b/docs/guides/archives.mdx @@ -0,0 +1,132 @@ +--- +title: "Copy files with tar archives" +description: "Download files, read path metadata and upload archives without buffering whole tarballs." +--- + +Docker copies container files through tar archives, not JSON models or a +multipart form. The target path belongs to the container filesystem. Local +input/output paths belong to the machine running PHP. + +## Download an archive + +Use a raw endpoint: `containerArchive()`'s default generated result is `null`, +so it does not retain the tar body for you. This example saves an archive of +`/etc` from an existing development container. Pick an output filename which +does not already exist; `xb` prevents overwriting a local file. + +```php +executeRawEndpoint(new ContainerArchive('my-container', [ + 'path' => '/etc', +])); +$body = $response->getBody(); +$file = null; + +try { + if ($response->getStatusCode() !== 200) { + throw new RuntimeException('Archive download failed: HTTP '.$response->getStatusCode()); + } + $file = fopen(__DIR__ . '/container-etc.tar', 'xb'); + if ($file === false) { + throw new RuntimeException('Could not create the destination archive'); + } + while (!$body->eof()) { + $chunk = $body->read(65536); + while ($chunk !== '') { + $written = fwrite($file, $chunk); + if ($written === false || $written === 0) { + throw new RuntimeException('Could not write the archive'); + } + $chunk = substr($chunk, $written); + } + } +} finally { + $body->close(); + if (is_resource($file)) { + fclose($file); + } +} +``` + +This copies in bounded chunks, including handling short file writes. Your HTTP +client must also provide an unbuffered response for end-to-end streaming. A +failed transfer can leave an incomplete file; do not consume it as a completed +archive. For application downloads, write to a new temporary file and rename +it to the final destination only after success. + +The result is a **tar archive**, even when the requested path is one file. +Review the contents before extracting, and do not blindly extract an untrusted +archive over an existing directory. `containerExport()` uses the same raw-body +pattern for a container filesystem export; it is not an image save or a backup +of mounted volume data. + +## Read path metadata + +The HEAD endpoint returns metadata in `X-Docker-Container-Path-Stat`, not a +response body. Decode its base64-encoded JSON value: + +```php +use Docker\API\Endpoint\ContainerArchiveInfo; + +$response = $docker->executeRawEndpoint(new ContainerArchiveInfo('my-container', [ + 'path' => '/etc', +])); +if ($response->getStatusCode() !== 200) { + throw new RuntimeException('Path lookup failed: HTTP '.$response->getStatusCode()); +} +$decoded = base64_decode($response->getHeaderLine('X-Docker-Container-Path-Stat'), true); +if ($decoded === false || $decoded === '') { + throw new RuntimeException('Missing or invalid path metadata'); +} +$metadata = json_decode($decoded, true, 512, JSON_THROW_ON_ERROR); +printf("%s\n", $metadata['name']); +``` + +This avoids downloading the file contents. Check the raw status explicitly; +HEAD error responses may not have a JSON body for a generated error model. + +## Upload a tar archive + +Create `upload.tar` containing only files intended for the destination. The +destination directory must already exist in the container. Uploading can +overwrite files, so use a development container and a dedicated path. + +```php +use Docker\API\Endpoint\PutContainerArchive; + +$archive = fopen(__DIR__ . '/upload.tar', 'rb'); +if ($archive === false) { + throw new RuntimeException('Could not open the upload archive'); +} +$body = null; +try { + $response = $docker->executeRawEndpoint(new PutContainerArchive( + 'my-container', + $archive, + ['path' => '/tmp', 'noOverwriteDirNonDir' => 'true'] + )); + $body = $response->getBody(); + if ($response->getStatusCode() !== 200) { + throw new RuntimeException('Archive upload failed: HTTP '.$response->getStatusCode()); + } +} finally { + $body?->close(); + if (is_resource($archive)) { + fclose($archive); + } +} +``` + +Pass the file resource directly; do not JSON-encode or base64-encode the tar. +`noOverwriteDirNonDir` prevents replacing a directory with a non-directory +or vice versa. It does **not** prevent replacing an existing regular file. +`copyUIDGID`, if needed, is also a string-valued query option in this API line. +The convenience `putContainerArchive()` call uses the same tar request shape +and returns `null` on successful typed parsing. diff --git a/docs/guides/events-and-stats.mdx b/docs/guides/events-and-stats.mdx new file mode 100644 index 000000000..ad92e4c78 --- /dev/null +++ b/docs/guides/events-and-stats.mdx @@ -0,0 +1,107 @@ +--- +title: "Events and resource stats" +description: "Read bounded event history, a single stats sample or live stats without opening an unintended endless stream." +--- + +These calls can stay open. Decide whether you want a finite query or a live +subscription before starting the request. + +## Read a bounded event window + +The client wraps `systemEvents()` in an `EventStream`. Its callback receives +one `EventMessage` model per event. Query timestamps are **strings** in this +API line, even when expressed as Unix seconds. + +```php +systemEvents([ + 'since' => (string) ($end - 60), + 'until' => (string) $end, + 'filters' => json_encode(['type' => ['container']], JSON_THROW_ON_ERROR), +]); +$events->onFrame(function (EventMessage $event): void { + printf("%s\t%s\t%s\n", + (string) $event->getTime(), + $event->getAction() ?? '', + $event->getActor()?->getId() ?? '' + ); +}); +$events->wait(); +``` + +Omit `until` only when you intend to keep listening. Filtering limits which +events arrive; it does not impose a timeout. Docker event history is bounded, +so this is not a durable audit log. Persist relevant events yourself, handle +reconnects and reconcile current state through inspect/list calls rather than +assuming no events were lost. Keep slow work out of the synchronous callback. + +## Read one stats sample + +`containerStats()` streams by default and returns a `StatsStream` (see +[continuous stats](#continuous-stats)). Set `stream => false` to get one sample +instead: + +```php +$stats = $docker->containerStats('my-container', ['stream' => false]); +printf("Memory usage: %s bytes\n", (string) ($stats?->getMemoryStats()?->getUsage() ?? 'unavailable')); +``` + +From API 1.48, samples are generated `ContainerStatsResponse` models. With an +earlier [API line](/api-versions), they are decoded `stdClass` objects: read +`$stats->memory_stats->usage` instead. Use null checks: cgroup versions and +daemon configuration affect which fields are present. `one-shot => true` can +reduce waiting for a single sample, but must be combined with `stream => false` +and may not provide the previous CPU sample needed for a percentage calculation. + +Raw memory usage is not necessarily the cache-adjusted value shown by the +Docker CLI. Likewise, CPU percentage needs current/previous CPU counters, +system counter deltas and a CPU count; it is not one field which can simply +be divided by a constant. Check zero/missing counters and the daemon's cgroup +version before calculating percentages. + +## Continuous stats + +With the default `stream => true`, `containerStats()` returns a `StatsStream`. +Docker sends a sample about once a second until the container stops, so call +`stop()` once you have what you need. Its callback receives each sample in the +same form as `stream => false`: + +```php +containerStats('my-container'); +$samples = 0; +$stats->onFrame(function (ContainerStatsResponse $sample) use ($stats, &$samples): void { + printf("Memory usage: %s bytes\n", (string) ($sample->getMemoryStats()?->getUsage() ?? 'unavailable')); + + if (++$samples === 5) { + $stats->stop(); + } +}); +$stats->wait(); +``` + +`stop()` closes the response body, and `wait()` returns after the current +sample's callbacks have run. Each sample's `precpu_stats` holds the previous +reading, so a CPU percentage can be calculated from the second sample onwards. +With an API line before 1.48, type the callback parameter as `stdClass`. + +Live samples need a transport that reads +incrementally, such as the bundled socket client. Guzzle's cURL handler +buffers the whole response; see [HTTP clients](/guides/guzzle). Keep the reader +in a worker rather than an ordinary web request, and see +[stream lifetime and cancellation](/reference/streams#lifetime-cancellation-and-timeouts). diff --git a/docs/guides/exec.mdx b/docs/guides/exec.mdx new file mode 100644 index 000000000..1372ceaac --- /dev/null +++ b/docs/guides/exec.mdx @@ -0,0 +1,100 @@ +--- +title: "Command output" +description: "Execute a command in a running container and read decoded output." +--- + +```php +setCmd(['sh', '-c', 'printf "hello\n"']); +$command->setAttachStdout(true); +$command->setAttachStderr(true); +$command->setTty(false); + +$exec = $docker->containerExec('my-container', $command); + +$start = new ExecIdStartPostBody(); +$start->setDetach(false); +$start->setTty(false); + +$output = $docker->execStart($exec->getId(), $start); +$output->onStdout(function (string $chunk): void { + echo $chunk; +}); +$output->onStderr(function (string $chunk): void { + fwrite(STDERR, $chunk); +}); +$output->wait(); +``` + +Replace `my-container` with an existing running container. `Detach` must be +`false` to consume attached output. Use the same `Tty` value when creating and +starting the exec command. + +For non-TTY commands, stdout and stderr are separate. TTY commands combine both +streams on `onStdout`. Callbacks receive chunks that may contain partial lines. + +To check the exit status after consuming the output, use +`execInspect($exec->getId())` and inspect `getRunning()` and `getExitCode()`. + +## Exit status is separate from HTTP success + +Continue with the `$exec` created above, after `$output->wait()`: + +```php +$result = $docker->execInspect($exec->getId()); +if ($result->getRunning() !== false) { + throw new RuntimeException('The command has not finished yet'); +} +$exitCode = $result->getExitCode(); +if ($exitCode === null) { + throw new RuntimeException('No exit status was returned'); +} +if ($exitCode !== 0) { + throw new RuntimeException('The command failed with exit status '.$exitCode); +} +``` + +An HTTP-successful start can still run a command which exits non-zero. Do not +infer success from the presence of output, the absence of stderr, or HTTP 200. +If a connection ends early, inspect the exec state before deciding whether it +finished or retrying a command with side effects. + +## Detached execution + +For a background command, set `Detach` to `true` on the start model. Do not +register callbacks or call `wait()` on its result; a detached start can return +`null` on success. Poll `execInspect()` with a bounded interval/deadline in +your application if you need completion and an exit code. This is a different +lifecycle from the attached example, not an asynchronous PHP promise. + +## TTY and upgraded connections + +The attached wrapper handles HTTP 200 and HTTP 101 responses when their media +type identifies Docker raw or multiplexed output. Set `Tty` explicitly and +consistently at creation and start; do not try to autodetect it from the bytes. +A TTY combines stdout/stderr and may produce terminal control sequences. + +Custom transports and proxies must preserve upgraded connections and provide +an unbuffered body. A normal buffered HTTP response adapter may pass list or +inspect calls but fail on exec output. + +This recipe is output-only: it does not implement interactive stdin or a +terminal UI. `onStdin()` on `DockerRawStream` is not a write method. See +[attach limitations](/reference/streams#attach-and-websocket-limitations). + +For the API added in client 3.2.0 with stdin, nonblocking polling and heartbeat hooks, +see [interactive exec](/guides/interactive-exec). + +Raw response bodies can contain binary frame headers. See +[Container logs](/guides/logs#raw-response-bodies) before working with raw fetch +modes. diff --git a/docs/guides/guzzle.mdx b/docs/guides/guzzle.mdx new file mode 100644 index 000000000..f73edaea8 --- /dev/null +++ b/docs/guides/guzzle.mdx @@ -0,0 +1,180 @@ +--- +title: "HTTP clients" +description: "Compare the bundled socket client and Guzzle, with connection examples and streaming limits." +--- + +Docker PHP uses its bundled socket client by default. You can also pass a +configured Guzzle 7 or 8 client to `Docker::create()`. Both support connection +settings directly in PHP; environment variables are optional. + +## Choosing a client + +| | Bundled socket client | Guzzle with the cURL handler shown below | +| --- | --- | --- | +| Dependencies | Included with Docker PHP; no cURL extension required | Requires Guzzle and PHP's cURL extension | +| Configuration | Socket options and PHP SSL contexts; optional Docker environment variables | Guzzle request options and middleware configured in PHP | +| Unix sockets | Set `remote_socket` | Set `CURLOPT_UNIX_SOCKET_PATH` | +| Streaming | Reads log, exec and progress output as it arrives | Buffers responses; works for completed responses, not indefinite streams | +| Timeouts | Milliseconds | Seconds | + +The bundled client needs little setup and includes Docker's streaming decoder. +Guzzle provides its own middleware and familiar HTTP/TLS options, which can be +useful if your application already uses it. Choose based on the operations you +need and the transport you want to configure. Attach and WebSocket calls have +[additional wrapper limitations](/reference/streams#attach-and-websocket-limitations) +regardless of which client you use. + +## Bundled socket client + +Without connection environment variables, this connects to `/var/run/docker.sock`: + +```php Default socket + 'unix:///run/custom/docker.sock', + 'timeout' => 10000, +]); + +$docker = Docker::create($httpClient, [], [], false); +``` + +The fourth argument is `false` because this factory already configures the API +path. For HTTP, HTTPS and certificate examples, see +[connection settings](/connection#factory-options). + +The factory negotiates the API version with the daemon. To fix a version, add +the `api_version` option; see [API versions](/api-versions#request-url-version). + +`DockerClientFactory` includes `StreamingDecoderPlugin` automatically. If you +build your own socket client and plugin chain, see +[custom socket clients](/reference/streams#custom-socket-clients). + +## Guzzle + +Install Guzzle in your application: + +```bash +composer require guzzlehttp/guzzle +``` + +These examples use an explicit cURL handler for Unix-socket and client-key +support. The PHP process must have permission to access the socket or +certificate files. + +### Custom Unix socket + +```php Guzzle Unix socket + 'http://localhost', + 'handler' => HandlerStack::create(new CurlHandler()), + 'curl' => [ + CURLOPT_UNIX_SOCKET_PATH => '/run/custom/docker.sock', + ], + 'proxy' => '', + 'timeout' => 10, +]); + +$docker = Docker::create($httpClient); +``` + +`base_uri` supplies the HTTP hostname; `CURLOPT_UNIX_SOCKET_PATH` selects the +socket using a filesystem path, without `unix://`. Docker PHP keeps these +options when wrapping the supplied client. + +For a TCP daemon over HTTP, change `base_uri` to +`http://docker.example.com:2375` and remove the `curl` option. Guzzle expects +`http://` or `https://`, not `tcp://`. + +### HTTPS and mutual TLS + +```php Guzzle HTTPS + 'https://docker.example.com:2376', + 'handler' => HandlerStack::create(new CurlHandler()), + 'verify' => '/path/to/ca.pem', + 'cert' => '/path/to/cert.pem', + 'ssl_key' => '/path/to/key.pem', + 'proxy' => '', + 'timeout' => 10, +]); + +$docker = Docker::create($httpClient); +``` + +`verify` selects the CA used to verify the server. The certificate must also +match the hostname. Omit `cert` and `ssl_key` if the daemon does not require a +client certificate. For a publicly trusted server certificate, omit `verify` +to use Guzzle's default trust configuration. Keep private keys outside source +control, and do not disable certificate verification to bypass errors. + + +Access to a Docker daemon is privileged. Plain HTTP is unencrypted; do not +expose an unauthenticated daemon to an untrusted network. + + +### Paths, timeouts and streaming + +Use the daemon's root URL for `base_uri`, without a version such as `/v1.57`. +These Guzzle examples keep the generated server plugins enabled, so Docker PHP +adds the installed API line's path. Guzzle clients do not negotiate, and +`DOCKER_API_VERSION` only configures the bundled factory, so install an +[API line](/api-versions) your daemon supports. Do not copy the bundled example's fourth argument (`false`) into +these examples. + +The empty `proxy` option disables HTTP proxy environment settings. Configure +a proxy explicitly if needed. The ten-second timeout is for ordinary calls; +adjust it for builds, transfers or other long-running operations. + +The cURL handler buffers response bodies even with `stream => true`. Completed +logs can still be decoded, but following logs or subscribing to events can +wait indefinitely or hit the timeout before returning output. Guzzle's PHP +stream handler can read incrementally, but cannot connect to a Unix socket: +Guzzle 7 ignores the `curl` option on that handler and Guzzle 8 rejects it. +Changing handlers changes which options work. + +`StreamingDecoderPlugin` handles decoding after the transport returns a +response. It cannot remove buffering inside Guzzle's cURL handler. If you +choose a custom transport for live streams or upgraded exec/attach connections, +test those operations with it. PSR-18 compatibility alone does not guarantee +unbuffered reads or a writable upgraded connection. See +[streaming](/reference/streams#custom-socket-clients). + +For more options, see Guzzle's +[request options](https://docs.guzzlephp.org/en/stable/request-options.html) +and [handlers](https://docs.guzzlephp.org/en/stable/handlers-and-middleware.html). diff --git a/docs/guides/image-transfer.mdx b/docs/guides/image-transfer.mdx new file mode 100644 index 000000000..16e03c53e --- /dev/null +++ b/docs/guides/image-transfer.mdx @@ -0,0 +1,90 @@ +--- +title: "Save and load images" +description: "Distinguish image archives from container exports and root-filesystem imports." +--- + +An image archive, a build context and a container filesystem export are not +interchangeable. Choose the matching API operation: + +| Archive | Produce it with | Consume it with | +| --- | --- | --- | +| Image layers, configuration and tags | `imageGet()` / `imageGetAll()` or `docker image save` | `imageLoad()` | +| Container/root filesystem | `containerExport()` or a suitable rootfs tar | `imageCreate()` with `fromSrc` | +| Files to copy into a container | A tar created for that destination | `putContainerArchive()` | +| Dockerfile and build files | `Context` / `ContextBuilder` | `imageBuild()` | + +## Save an image + +Use `executeRawEndpoint(new Docker\API\Endpoint\ImageGet($imageName))` and +require HTTP 200, then save the body in chunks using the +[archive download pattern](/guides/archives#download-an-archive). The default +generated `imageGet()` result is `null`; it does not give you a tar stream. + +For more than one image, use `new ImageGetAll(['names' => ['image-a:tag', +'image-b:tag']])` with the raw endpoint. Specify the names explicitly rather +than accidentally exporting every image on the daemon. + +## Load an image archive + +Loading creates or updates image records and tags on the daemon. Use a tar +produced by an image-save operation and a development daemon. This call has +no `BuildStream`/`CreateImageStream` wrapper; its progress response must be +handled separately. + +```php +executeRawEndpoint(new ImageLoad($archive, ['quiet' => true])); + $body = $response->getBody(); + if ($response->getStatusCode() !== 200) { + throw new RuntimeException('Image load failed: HTTP '.$response->getStatusCode()); + } + // The quiet response is finite; it can still contain several JSON lines. + foreach (preg_split('/\r?\n/', $body->getContents()) as $line) { + if (trim($line) === '') { + continue; + } + $frame = json_decode($line, true, 512, JSON_THROW_ON_ERROR); + if (isset($frame['error']) || isset($frame['errorDetail']['message'])) { + throw new RuntimeException($frame['error'] ?? $frame['errorDetail']['message']); + } + echo $frame['stream'] ?? ''; + } +} finally { + $body?->close(); + if (is_resource($archive)) { + fclose($archive); + } +} +``` + +The archive is sent as a resource, so PHP does not load the tar file into a +string first. This example buffers only the quiet progress response. For a +verbose or long-lived JSON stream, use a bounded incremental JSON-line reader +instead. Reading the progress is necessary: HTTP 200 alone does not prove that +the daemon accepted all of the image data. + +## Root-filesystem import is different + +`imageCreate()` with `fromSrc` imports a root filesystem, not an image-save +archive. Use `fromSrc => '-'` for a request-body import, or a source URL for +the daemon to download. Remote source URLs are fetched by the daemon, not PHP; +do not accept arbitrary URLs from untrusted callers. + +In this API line, `imageCreate()`'s request body is `?string`, unlike the +resource/PSR-7-stream bodies supported by `imageBuild()`, `imageLoad()` and +`putContainerArchive()`. Do not pass a file resource to `imageCreate()` and +expect it to behave like an image load. Choose the operation and payload type +deliberately, especially for large archives. diff --git a/docs/guides/interactive-exec.mdx b/docs/guides/interactive-exec.mdx new file mode 100644 index 000000000..1cdd207cf --- /dev/null +++ b/docs/guides/interactive-exec.mdx @@ -0,0 +1,184 @@ +--- +title: "Interactive exec" +description: "Send stdin while polling output, with application heartbeats and deadlines." +--- + + +Interactive exec is available from client `3.2.0`. The existing blocking +`execStart()` and `wait()` APIs are unchanged. + + +Use interactive exec when a command needs stdin or your application must keep +working while it runs. The session reads and writes without blocking on command +output. A caller can renew a lock, check cancellation or enforce its own deadline +between `poll()` calls, even if the command is silent. + +## Non-TTY stdin and output + +The default `Docker::create()` socket client supports this API. For explicit PHP +configuration, use `DockerClientFactory::createInteractive()`: + +```php + 'unix:///var/run/docker.sock', + 'timeout' => 2000, +]), [], [], false); + +$command = new ContainersIdExecPostBody(); +$command->setCmd(['timeout', '-s', 'KILL', '30', 'cat']); +$command->setAttachStdin(true); +$command->setAttachStdout(true); +$command->setAttachStderr(true); +$command->setTty(false); +$exec = $docker->containerExec('my-container', $command); + +$start = new ExecIdStartPostBody(); +$start->setTty(false); +$session = $docker->execStartInteractive($exec->getId(), $start, 35000); +$session->onStdout(static function (string $chunk): void { + echo $chunk; +}); +$session->onStderr(static function (string $chunk): void { + fwrite(STDERR, $chunk); +}); + +$input = "{\"example\":true}\n"; +$offset = 0; +$stdinClosed = false; +$nextHeartbeat = 0; +try { + while (!$session->isFinished()) { + $now = hrtime(true); + if ($now >= $nextHeartbeat) { + // Renew your application lock here; throw if ownership was lost. + $nextHeartbeat = $now + 10000000000; + } + if ($offset < strlen($input)) { + $offset += $session->writeStdin(substr($input, $offset, 16384)); + } elseif (!$stdinClosed) { + $session->closeStdin(); + $stdinClosed = true; + } + $session->poll(50); + } +} finally { + $session->close(); +} + +$result = $docker->execInspect($exec->getId()); +if ($result->getRunning() !== false || $result->getExitCode() === null) { + throw new RuntimeException('The exec result is not known yet; inspect it before retrying'); +} +if ($result->getExitCode() !== 0) { + throw new RuntimeException('The command failed with exit status '.$result->getExitCode()); +} +``` + +Replace `my-container` with a running development container. `timeout` must exist +inside its image; use the image's own timeout/supervision mechanism if it does not. + +`writeStdin()` returns the number of bytes accepted, at most 16 KiB per call. +Zero means backpressure: poll output, then retry the unsent suffix. The library +does not retain or queue stdin. Once all input has been sent, `closeStdin()` sends +EOF without closing the non-TTY output channels. + +`poll(50)` reads at most 16 KiB and waits at most 50 milliseconds for data. It +returns `true` while the connection remains open, including during idle periods; +`false` means clean output EOF. Callbacks receive chunks, which can split frames +or lines. Without a callback, that channel is drained and discarded. + +If stdin is already complete, `wait($tick, 50)` is a convenience loop. `$tick` +runs between polls even with no output; it can also send input. Callbacks and +ticks must return promptly. Their exceptions close the local session and propagate. + +## Deadlines and completion + +The factory's `timeout` controls connection and socket I/O timeouts for synchronous +HTTP setup/status calls. It is not a total request deadline: a response that keeps +arriving can extend a request, and application heartbeats cannot run during it. +The third argument to `execStartInteractive()` is a total streaming deadline in milliseconds, +starting after the HTTP upgrade. It is not reset when output arrives. Expiry throws +`Docker\Exception\InteractiveExecTimeoutException` and closes local I/O. + + +Closing the stream or reaching a local deadline does not guarantee that Docker +terminated the command. Keep an in-container timeout for unattended operations. +Output EOF is not an exit code: inspect `Running` and `ExitCode`, with a bounded +application deadline if you need to poll for the final result. Never automatically +retry a command with side effects after an ambiguous disconnect. + + +## Worker locks and retries + +Your application owns its queue, lock leases and execution records. Docker PHP +provides the polling and stdin APIs; it does not acquire Redis locks, acknowledge +jobs or deduplicate executions. + +Acquire the lease and persist the application execution ID and Docker exec ID +before starting the command. Renew the lease between polls, atomically comparing +its unique owner token so an expired worker cannot renew another worker's lock. +Use the ten-second heartbeat hook above even when the command is silent. +Choose a lease duration with enough margin for synchronous setup/status requests +and delayed heartbeats; a ten-second schedule is not a guarantee of exact timing. + +If renewal fails, stop sending input and close the local session. A heartbeat +exception passed through `wait($tick)` does this automatically. Record the failed +or uncertain attempt before acknowledging its job, and retain the Docker exec ID +for later inspection. A failed worker result does not prove the command stopped +or that it had no side effects. + +Use persisted execution state to deduplicate repeated job deliveries. Before +starting another attempt after a lost lease or disconnect, confirm the previous +command has stopped and reconcile any side effects. A new queue delivery or an +expired lock alone does not make another exec safe. + +## Transports and TTY + +This feature supports the bundled Unix, TCP and TLS socket transport. Guzzle and +arbitrary PSR-18 clients are rejected before sending an interactive start request. +HTTP proxies must preserve the HTTP 101 connection upgrade and bidirectional traffic. + +TTY sessions support stdin writes and combined output on `onStdout()`. They have +terminal semantics, not separate stdout/stderr pipes. `closeStdin()` deliberately +rejects TTY sessions: Docker can close their output when socket stdin reaches EOF. +Use terminal input or let the command exit; use `Tty=false` for JSON-input managers. +The `Tty` setting must match at exec creation and start. + +## Maintainer validation + +On 6 October 2026, a private application canary tested +[client revision `fbdb2cc`](https://github.com/docker-php/docker-php/commit/fbdb2cc2432b1ba9341f144a2f551523536e4a4c) +with API package `7.1.45.0` against Docker Engine `29.8.1`, using API `1.45`. +Its worker sent fixed JSON stdin, closed stdin and polled a command that produced +no output for 40 seconds. + +| Application check | Observed result | +| --- | --- | +| Silent execution | Four Redis lease renewals; completed result callback delivered; queue job acknowledged. | +| Lease loss after the first renewal | The next renewal failed and the failed result callback was delivered. The disconnected container command later completed. | +| Identical admission and job replay after either result | One manager start per execution, one attempt and no second command. | + +The locks, result callbacks and replay guards in these checks belonged to the +application. Concurrent workers, HTTP submission retries and network-failure +recovery still need separate tests. + +The library's stream and local transport-fixture tests cover partial stdin +writes, backpressure, EOF, idle ticks, deadline expiry, callback failures and +Unix/TCP/TLS connections. Run them without a Docker daemon: + +```bash +vendor/bin/phpunit --filter 'InteractiveExec(Stream|Transport)Test' --disallow-test-output +``` + +`tests/Resource/InteractiveExecResourceTest.php` also exercises stdin, TTY output, +exit codes and container-side timeouts against a development Docker daemon. +Those resource tests create and remove their own containers. diff --git a/docs/guides/logs.mdx b/docs/guides/logs.mdx new file mode 100644 index 000000000..cc4f8205d --- /dev/null +++ b/docs/guides/logs.mdx @@ -0,0 +1,107 @@ +--- +title: "Container logs" +description: "Read decoded stdout and stderr with callback streams." +--- + +```php +containerLogs('my-container', [ + 'stdout' => true, + 'stderr' => true, + 'follow' => true, +]); + +$logs->onStdout(function (string $chunk): void { + echo $chunk; +}); +$logs->onStderr(function (string $chunk): void { + fwrite(STDERR, $chunk); +}); +$logs->wait(); +``` + +Replace `my-container` with the ID or name of an existing container. With +`follow` enabled, `wait()` keeps consuming output until the stream ends or the +underlying client interrupts it. Omit `follow` to read the currently available +logs. + +## Output chunks and TTY mode + +Callbacks receive output chunks, not necessarily complete lines. Buffer chunks +in your application if it processes output line by line. + +Non-TTY output has separate stdout and stderr channels. TTY containers combine +both on `onStdout`. + +For a response marked `application/vnd.docker.raw-stream`, the client inspects +the container's TTY setting to distinguish terminal output from framed output. +Your daemon credentials need permission to inspect the container. Responses +marked `application/vnd.docker.multiplexed-stream` do not need that extra +request. + +## Read recent output without following + +Continue with the `$docker` client above. This query is finite: + +```php +$recent = $docker->containerLogs('my-container', [ + 'stdout' => true, + 'stderr' => true, + 'follow' => false, + 'tail' => '100', + 'timestamps' => true, + 'since' => time() - 300, +]); +$recent->onStdout(function (string $chunk): void { echo $chunk; }); +$recent->onStderr(function (string $chunk): void { fwrite(STDERR, $chunk); }); +$recent->wait(); +``` + +`tail` is a string, including numeric-looking values; `since` is an integer +for this endpoint. That differs from the string timestamps accepted by +`systemEvents()`. Log availability also depends on the daemon's logging driver +and configuration; this call is not a replacement for a durable logging service. + +## Process output line by line + +Maintain separate buffers for stdout and stderr. For a single channel, a simple +bounded line buffer can be registered as a callback: + +```php +$pending = ''; +$logs = $docker->containerLogs('my-container', ['stdout' => true, 'tail' => '100']); +$logs->onStdout(function (string $chunk) use (&$pending): void { + $pending .= $chunk; + while (($newline = strpos($pending, "\n")) !== false) { + $line = substr($pending, 0, $newline); + $pending = substr($pending, $newline + 1); + printf("line: %s\n", rtrim($line, "\r")); + } + if (strlen($pending) > 1024 * 1024) { + throw new RuntimeException('Output line exceeded the buffer limit'); + } +}); +$logs->wait(); +if ($pending !== '') { + printf("last line: %s\n", $pending); +} +``` + +This handles lines split across chunks and a final line without a newline. +It limits the incomplete-line buffer; applications should also cap or stream +their total retained output. Use separate buffers if you add `onStderr()`. +Terminal escape sequences are not removed by Docker frame decoding. + +## Raw response bodies + +`executeRawEndpoint()` and the deprecated `FETCH_RESPONSE` mode return the raw +body. Non-TTY output includes Docker's binary frame headers in that body. Do +not print it directly if you want readable output; use the callback stream. + +The same distinction applies to [exec output](/guides/exec). diff --git a/docs/guides/registry.mdx b/docs/guides/registry.mdx new file mode 100644 index 000000000..a0f0c48c2 --- /dev/null +++ b/docs/guides/registry.mdx @@ -0,0 +1,112 @@ +--- +title: "Pull and push images" +description: "Handle registry authentication and streamed progress, including daemon-side errors." +--- + +The daemon contacts the registry. PHP sends the registry credentials to the +daemon in request headers; it does not perform `docker login` or read your +Docker CLI credential helpers automatically. + +Use a trusted daemon connection, with TLS for remote TCP connections. Keep +tokens out of source control, query parameters and request-header logs. + +## Pull a private image + +`imageCreate()` takes a nullable body first, then query parameters and headers. +For a pull, pass `null` as the body and set `fromImage` and an explicit `tag`. +`X-Registry-Auth` must be an encoded **string** on this call; it does not accept +an `AuthConfig` model. + +Set `DOCKER_REGISTRY_USER` and `DOCKER_REGISTRY_TOKEN` in your process's secret +configuration. Replace the example registry/repository with one you can access. + +```php + $username, + 'password' => $token, + 'serveraddress' => 'registry.example.com', +], JSON_THROW_ON_ERROR)), '+/', '-_'), '='); + +$pull = $docker->imageCreate(null, [ + 'fromImage' => 'registry.example.com/team/app', + 'tag' => 'example', +], ['X-Registry-Auth' => $auth]); + +$pull->onFrame(function (CreateImageInfo $frame): void { + $error = FrameError::message($frame); + if ($error !== null) { + throw new RuntimeException($error); + } + echo ($frame->getStatus() ?? ''), "\n"; +}); +$pull->wait(); +``` + +For a public image, omit the authentication header. Use an explicit tag or +digest: an empty pull tag can request all tags. The returned `CreateImageStream` +contains progress, not a completed image model. Inspect the image separately +if you need its metadata. + +## Push a tagged image + +Tag a local image for the target registry before pushing. This sends image +layers and the tag to the registry, so use a repository reserved for testing. +Keep the credentials from the pull example available in `$username` and `$token`. + +```php +use Docker\API\Model\AuthConfig; +use Docker\API\Model\PushImageInfo; + +$authConfig = new AuthConfig(); +$authConfig->setUsername($username); +$authConfig->setPassword($token); +$authConfig->setServeraddress('registry.example.com'); + +$docker->imageTag('docker-php-example:latest', [ + 'repo' => 'registry.example.com/team/app', + 'tag' => 'example', +]); + +$push = $docker->imagePush('registry.example.com/team/app', ['tag' => 'example'], [ + 'X-Registry-Auth' => $authConfig, +]); +$push->onFrame(function (PushImageInfo $frame): void { + $error = FrameError::message($frame); + if ($error !== null) { + throw new RuntimeException($error); + } + echo ($frame->getStatus() ?? ''), "\n"; +}); +$push->wait(); +``` + +Unlike `imageCreate()`, the `Docker\Docker::imagePush()` convenience method +accepts an `AuthConfig` in the exact `X-Registry-Auth` header key and serializes +and base64-encodes it for you. Do not pre-encode that model. You can instead pass +an already encoded string, as used in the pull example. A generated +`Docker\API\Endpoint\ImagePush` used directly does not perform the model +conversion. + +## Builds use a different authentication header + +Building from private base images uses `X-Registry-Config`: an encoded map of +registry names to credential objects, rather than one auth object. See +[private build dependencies](/cookbook/build-image#private-base-images). + +Authentication to a Docker daemon and authentication to an image registry are +separate concerns. A registry token does not secure an exposed Docker socket. diff --git a/docs/index.md b/docs/index.md deleted file mode 100644 index d00780dc4..000000000 --- a/docs/index.md +++ /dev/null @@ -1,22 +0,0 @@ -# Docker-PHP - -This is the documentation for [docker-php](https://github.com/docker-php/docker-php) library. - -This library aim to reach 100% API support of the Docker Engine. - -## Basics - -First you need to learn the basics of this library : - -* [Installation](installation.md) -* [Connecting to Docker](connection.md) -* [Basic usage](basic.md) -* [Asynchronous Client](async.md) - -## Cookbook - -The cookbook is a collection of recipes that explain how to solve common -problems and advanced usage when using Docker-PHP - -* [Running a container](cookbook/container-run.md) -* [Build an image](cookbook/build-image.md) diff --git a/docs/index.mdx b/docs/index.mdx new file mode 100644 index 000000000..bf70074a9 --- /dev/null +++ b/docs/index.mdx @@ -0,0 +1,45 @@ +--- +title: "Docker PHP" +description: "Use the Docker Engine API from PHP." +--- + +Docker PHP is a PHP client for the Docker Engine API. It provides generated +endpoint methods and models, connection handling, and decoded log and command +output streams. + + +These docs cover the Docker PHP 4.1 client, which works with Docker Engine API +v1.45 to v1.57. Upgrading from the original +[docker-php 2.x](/migration#from-the-original-2-x-client) client, +[beluga-php/docker-php](/migration#from-beluga) or +[docker-php 3.x](/migration#from-3-x)? Start with the upgrade guide. + + +Choose a Docker API version by installing its +[API package line](/api-versions); requests negotiate with the daemon. The PHP +namespaces remain `Docker` and `Docker\API`, including for applications +migrating from Beluga. + + + + Check the requirements and make your first request. + + + Migrate from docker-php 2.x, Beluga or 3.x. + + + Consume stdout and stderr without Docker frame headers. + + + Understand package versions and daemon compatibility. + + + Set up mounts, published ports, labels and restart policies. + + + Find the right approach for streams, archives and blocking calls. + + + +Development continues in [docker-php/docker-php](https://github.com/docker-php/docker-php). +The generated API is maintained in [docker-php/docker-php-api](https://github.com/docker-php/docker-php-api). diff --git a/docs/installation.md b/docs/installation.md deleted file mode 100644 index 2cc4fcecd..000000000 --- a/docs/installation.md +++ /dev/null @@ -1,21 +0,0 @@ -# Installation - -The recommended way to install Docker PHP is to use [Composer](http://getcomposer.org/): - -Run `composer require docker-php/docker-php` to add the dependency - -By default it will use the last API version. However you can specify the API version of docker by setting a specific -version for the `docker-php/docker-php-api`. - -To use the 1.29 version you can do the following: - -``` -composer require docker-php/docker-php-api:4.1.29.* -``` - -Do not use `^4.1.29.0`; otherwise, you will also depend on the latest version. The first digit of this version number matches the -major version of [Jane PHP](https://github.com/janephp/janephp), which is the lib generating the API Client code. - -Note that some endpoints of the Docker API may have BC breaks during minor version updates. This library may -try to hide those BC breaks but it will always be a best effort. Feel free to raise an issue or pull request on github when -you encounter one. diff --git a/docs/installation.mdx b/docs/installation.mdx new file mode 100644 index 000000000..4fe16d64d --- /dev/null +++ b/docs/installation.mdx @@ -0,0 +1,37 @@ +--- +title: "Installation" +description: "Install the client and its matching generated API package." +--- + +## Requirements + +- PHP 8.2 or later, with the `mbstring` extension. +- [Composer](https://getcomposer.org/). +- Access to a Docker daemon with API v1.45 or later (Docker Engine 26.0 or later). + +Docker PHP 4.0 is the last release line that supports PHP 8.1. + +## Stable installation + +```bash +composer require "docker-php/docker-php:^4.0" +``` + +Composer also installs `docker-php/docker-php-api`, choosing the newest +[API line](/api-versions) unless you require one. Requests negotiate with the +daemon, so an older daemon still works. Require a specific line if your code +depends on generated model names or fields. + +## Test the development version + +For a disposable test application, explicitly allow both development packages: + +```bash +composer require "docker-php/docker-php:4.1.x-dev" --with-all-dependencies +``` + +Do not use these moving development versions for an unattended production +upgrade. Commit your application's `composer.lock` after testing. + +If you already use Docker PHP or Beluga, follow the [migration guide](/migration) +instead of installing both package families together. diff --git a/docs/migration.mdx b/docs/migration.mdx new file mode 100644 index 000000000..73ac85ec4 --- /dev/null +++ b/docs/migration.mdx @@ -0,0 +1,160 @@ +--- +title: "Upgrade to 4.0" +description: "Migrate from the original 2.x client, the Beluga fork or 3.x." +--- + +Most applications come from the original `docker-php/docker-php` 2.x client +or from `beluga-php/docker-php` 1.45.x. Follow the section for your current +package, then apply the [changes from 3.x](#from-3-x), because 4.0 also changes +defaults that 2.x and Beluga applications rely on. + +## From the original 2.x client + +The new client requires PHP 8.2 or later, the `mbstring` extension, PSR-7 v2 and +Jane 7 runtimes. Check your application's other dependencies against these +requirements before changing its Composer constraints. + +Change the client requirement to `docker-php/docker-php:^4.0`. Remove an explicit +`docker-php/docker-php-api:4.1.*` requirement, or change it to one +[API line](/api-versions) if your application depends on the API package directly. + +```json +{ + "require": { + "docker-php/docker-php": "^4.0" + } +} +``` + +Resolve the package changes together: + +```bash +composer update docker-php/docker-php docker-php/docker-php-api --with-all-dependencies +``` + +Review endpoint signatures and generated model types. The PHP namespaces remain +`Docker` and `Docker\API`, but that does not make all old API models or calling +patterns compatible. The specification changes from the old API line to the one +you install. Then apply the [changes from 3.x](#from-3-x). + +### Asynchronous client + +The old `DockerAsync` client and its Amp/Artax examples do not apply to 4.0. +The maintained client uses synchronous endpoint calls and callback streams. +Applications using `DockerAsync` need to adapt those call sites; this is not a +drop-in replacement for the old promise-based client. + +### HTTP clients + +The default client now uses the maintained PSR-7 v2 dependency set. Review custom +HTTP adapters for PSR-18 compatibility, daemon connection settings, unbuffered +responses and upgraded Docker connections. See [Connection settings](/connection). + +### Log and exec consumers + +Use `onStdout()` and `onStderr()` with `wait()` to consume decoded output. Do not +print non-TTY raw response bodies directly: they contain binary frame headers. +TTY output combines stdout and stderr, and callbacks receive chunks rather +than guaranteed complete lines. See [logs](/guides/logs) and +[exec output](/guides/exec). + +## From Beluga + +The new client continues the code maintained under `beluga-php/docker-php`. +For applications on the Beluga API v1.45 line, the package-name migration does +not require a PHP namespace change. + +Remove both Beluga requirements from your application's `composer.json`, if +present. Add `docker-php/docker-php:^4.0`. If you require the API package +directly, add the matching line as well, for example +`docker-php/docker-php-api:>=7.1.45.0 <7.1.46.0` for the Beluga v1.45 models. + +Do not install both package families together: they contain the same PHP +classes and the new packages declare conflicts with their Beluga counterparts. +Resolve the dependency changes together, rather than installing the new client +while keeping an old direct API requirement. + +```bash +composer update --with-all-dependencies +``` + +Run that broader update in a test checkout, review unrelated dependency changes, +and commit the tested lock file. If you use another Beluga Docker API line, +require the matching line here. Then apply the [changes from 3.x](#from-3-x). + +## From 3.x + +Change the client requirement to `docker-php/docker-php:^4.0`. Applications that +cannot upgrade yet can stay on `^3.3`, which keeps Docker Engine API v1.45. + +### API version + +4.1 works with API v1.45 to v1.57, and Composer installs the newest API line +unless you require one. Generated models and their methods differ between +versions. To keep the 3.x models, require the v1.45 line: + +```bash +composer require "docker-php/docker-php:^4.0" "docker-php/docker-php-api:>=7.1.45.0 <7.1.46.0" +``` + +To move to a newer line, check the models your code names. For example: + +- API 1.46 renamed `NetworksCreatePostResponse201` to `NetworkCreateResponse`. +- API 1.48 renamed `ContainersIdJsonGetResponse200` to `ContainerInspectResponse` + and added `ContainerStatsResponse`. +- API 1.52 removed `getError()` from `BuildInfo`, `CreateImageInfo` and + `PushImageInfo`. Use `Docker\Stream\FrameError::message($frame)`, which works + with every line. + +See [API versions](/api-versions) and Docker's +[API version history](https://docs.docker.com/reference/api/engine/version-history/). + +### Request version negotiation + +Without `api_version` or `DOCKER_API_VERSION`, the bundled factory now sends an +unversioned `/_ping` before its first request and uses the lower of the daemon's +API version and the installed line. Setting either keeps a fixed version, as in +3.x. + +### Unexpected error statuses throw + +An error status of 400 or above that the generated endpoint does not handle now +throws `UnexpectedClientErrorException` or `UnexpectedServerErrorException`. +In 3.x those calls returned `null`. To keep that behaviour: + +```php +$docker = Docker::create()->throwOnUnexpectedStatus(false); +``` + +See [unexpected error statuses](/reference/requests-and-responses#unexpected-error-statuses). + +### `.dockerignore` is applied + +`Context` now leaves out the paths a context's `.dockerignore` excludes, as +`docker build` does. To archive the whole directory as 3.x did, call +`applyDockerignore(false)` on the context. + +### Stats samples + +From API 1.48, `containerStats()` returns `ContainerStatsResponse` models, for one +sample and for each `StatsStream` frame. Earlier lines still return decoded +`stdClass` objects. + +### Subclasses of `Docker` + +`Docker::systemEvents()` has a new optional `$accept` parameter. A subclass that +overrides it needs the same parameter. + +## Verify the application + +- Confirm only the original package family is installed with `composer show`. +- Test the daemon connection and representative inspect, list and create calls. +- Check log and exec output, including TTY and non-TTY containers. +- Review custom HTTP clients and nullable model fields. +- Commit `composer.lock` and keep the prior release and lock file available for + rollback before deploying. + +Existing bounded client constraints such as `^2.0` or `^3.0` do not +automatically admit 4.0. Existing API `4.1.*` constraints do not admit the new +7.x packages. Broad or +unbounded requirements do not provide that protection. diff --git a/docs/package-lock.json b/docs/package-lock.json new file mode 100644 index 000000000..2bf737770 --- /dev/null +++ b/docs/package-lock.json @@ -0,0 +1,1742 @@ +{ + "name": "docker-php-documentation", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "docker-php-documentation", + "devDependencies": { + "mint": "4.3.37" + }, + "engines": { + "node": ">=20.17 <25" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@mintlify/cli": { + "version": "4.1.37", + "resolved": "https://registry.npmjs.org/@mintlify/cli/-/cli-4.1.37.tgz", + "integrity": "sha512-9ygWtTDz1x3vDijroATRJtryzmX0TCn0UdK41NoBTvzWJuZFGlOHsboqqiRMrtKoYsAcOc1CwNkGRN5aSGJGjQ==", + "dev": true, + "license": "Elastic-2.0", + "dependencies": { + "sharp": "0.33.5" + }, + "bin": { + "mint": "dist/index.js", + "mintlify": "dist/index.js" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "@mintlify/package-builder": "0.0.159", + "fsevents": "2.3.3", + "keytar": "7.9.0" + } + }, + "node_modules/@mintlify/package-builder": { + "version": "0.0.159", + "resolved": "https://registry.npmjs.org/@mintlify/package-builder/-/package-builder-0.0.159.tgz", + "integrity": "sha512-g8hcoyWkCGJnvtf+OqzaCCZUKFn9k9eWZipMWSSDq8wqvvg6Y8aQ37rmeb6PktTVi9DbO9fSjqAcRhuC3jKvdQ==", + "dev": true, + "license": "Elastic-2.0", + "optional": true, + "dependencies": { + "entities": "7.0.1", + "esbuild": "0.25.12", + "js-yaml": "4.3.1", + "semver": "7.7.4" + }, + "bin": { + "mint-package-builder": "dist/cli.js" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0", + "optional": true + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", + "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, + "license": "BSD-2-Clause", + "optional": true, + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "dev": true, + "license": "(MIT OR WTFPL)", + "optional": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause", + "optional": true + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true, + "license": "ISC", + "optional": true + }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/keytar": { + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/keytar/-/keytar-7.9.0.tgz", + "integrity": "sha512-VPD8mtVtm5JNtA2AErl6Chp06JBfy7diFQ7TQQhdpWOl6MrCRB+eRbvAZUsbGQS9kiMq0coJsy0W0vHpDCkWsQ==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "dependencies": { + "node-addon-api": "^4.3.0", + "prebuild-install": "^7.0.1" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "license": "MIT", + "optional": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mint": { + "version": "4.3.37", + "resolved": "https://registry.npmjs.org/mint/-/mint-4.3.37.tgz", + "integrity": "sha512-vuobDcMnsiEpnktMy+78QW51cHywJEGaN20mJblT0TcoUsaA6etQnqozHVIrVRRI42mtO5o24DJ86RhkHuUjGQ==", + "dev": true, + "license": "Elastic-2.0", + "dependencies": { + "@mintlify/cli": "4.1.37" + }, + "bin": { + "mint": "index.js" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/napi-build-utils": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", + "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/node-abi": { + "version": "3.101.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.101.0.tgz", + "integrity": "sha512-bkb/RkuWCE64eWu1PCh3Fu2pGc9mKRs+kOE+FU2bGHRYlQa86/D321DSATV54AsCQMKz3/xSt9sRgraZTpqdhQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-addon-api": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz", + "integrity": "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "optional": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", + "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", + "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^2.0.0", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/pump": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", + "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "dev": true, + "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", + "optional": true, + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, + "license": "ISC", + "optional": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/sharp/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "optional": true, + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tar-fs": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", + "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "dev": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC", + "optional": true + } + } +} diff --git a/docs/package.json b/docs/package.json new file mode 100644 index 000000000..49b4d889c --- /dev/null +++ b/docs/package.json @@ -0,0 +1,21 @@ +{ + "name": "docker-php-documentation", + "private": true, + "description": "Local preview and checks for the Docker PHP Mintlify documentation", + "engines": { + "node": ">=20.17 <25" + }, + "scripts": { + "dev": "mint dev --no-open --telemetry false", + "validate": "mint validate --telemetry false", + "check:links": "mint broken-links --check-anchors --telemetry false", + "check:examples": "php scripts/check-php-examples.php" + }, + "devDependencies": { + "mint": "4.3.37" + }, + "overrides": { + "js-yaml@^4": "^4.3.2", + "sharp": "^0.35.5" + } +} diff --git a/docs/reference/requests-and-responses.mdx b/docs/reference/requests-and-responses.mdx new file mode 100644 index 000000000..b57445427 --- /dev/null +++ b/docs/reference/requests-and-responses.mdx @@ -0,0 +1,192 @@ +--- +title: "Requests and responses" +description: "Understand models, JSON-valued parameters, raw responses and errors." +--- + +The generated API describes the Docker Engine API version you install. `Docker\Docker` extends that +client with connection handling and wrappers for selected streaming endpoints. +Use `Docker\Docker`, not `Docker\API\Client`, for those wrappers. + +## Request models and nested configuration + +JSON request bodies use generated models, rather than arbitrary PHP arrays. +Construct the outer request model and the nested models it expects. Use arrays +for lists and maps where the setter accepts an iterable. + +For example, container creation combines `ContainersCreatePostBody`, +`HostConfig`, `PortBinding` and `Mount`. See +[Configure a container](/cookbook/container-config) for a complete example. + +Calling a setter marks that field as initialized. An unset field is different +from one explicitly set to `null`, an empty list or an empty object. Leave +optional fields unset unless you intend to send them. Nullable setters do not +mean that every Docker operation accepts `null` in every context. + +Docker's JSON shapes matter: + +| Shape | Example | Typical use | +| --- | --- | --- | +| List | `["sh", "-c", "echo hello"]` | `Cmd`, `Env`, mounts | +| Map | `{"example":"true"}` | Labels, network endpoints | +| Map of lists | `{"80/tcp":[{"HostPort":"8080"}]}` | Port bindings | +| Map of empty objects | `{"80/tcp":{}}` | Exposed ports | + +Use `new ArrayObject()` when constructing an empty object in these examples; +an empty PHP array normally represents a JSON list. The generated normalizers +preserve the object shapes required by the API. + +## JSON-valued query parameters + +Some query parameters are strings containing JSON, even though other query +parameters use booleans, integers or arrays. Examples include `filters`, +`buildargs`, `labels` on `imageBuild()`, and `cachefrom`. + +```php +containerList([ + 'all' => true, + 'filters' => json_encode([ + 'label' => ['docker-php-example=true'], + 'status' => ['running'], + ], JSON_THROW_ON_ERROR), +]); +``` + +JSON-encode the value once. Do not also apply `urlencode()` or +`http_build_query()`; the client performs query-string encoding. Pass an actual +boolean for `all`, not the string `'true'`. Conversely, archive upload options +such as `noOverwriteDirNonDir` are declared as strings in this API line and +must be passed as strings. + +The generated endpoint's PHPDoc and options resolver are the authority for the +parameter types accepted by this version. A CLI flag's name or apparent type +is not enough to determine the PHP signature. + +## Response models and empty responses + +The default fetch mode returns a generated response model, a list of models, +a callback stream, a plain decoded object, or `null`, depending on the endpoint. +Use getters on models; do not assume every result is an array. + +Successful operations such as starting a container can have no response body. +A `null` result is therefore not a general failure indicator. Check the endpoint +contract, or use a raw response when you need the HTTP status. To make sure a +`null` never hides an error response, enable +[unexpected status exceptions](#unexpected-error-statuses). + +For absent or nullable response fields, use null checks or null-safe getters. +Some Docker counters and limits are unsigned 64-bit integers. Values above +`PHP_INT_MAX`, such as the `pids_stats.limit` Docker reports for a container +without a PID limit, are returned as `PHP_INT_MAX`. +Inspect responses and create request models serve different purposes; do not +send an entire inspect response back as a creation or update payload. + +## Raw responses and headers + +Use `executeRawEndpoint()` with an endpoint object when you need the HTTP +status, headers, tar content or an unsupported streaming response: + +```php +executeRawEndpoint(new ContainerStart('my-container')); + +if ($response->getStatusCode() !== 204) { + throw new RuntimeException(sprintf( + 'Unexpected start response: HTTP %d', + $response->getStatusCode() + )); +} +``` + +This returns a PSR-7 response. It bypasses generated response parsing, +including API exception conversion and the custom stream wrappers. Check the +status yourself **before** treating the body as an archive, log stream or other +successful result. Transport exceptions and request-parameter validation can +still occur. + +`FETCH_RESPONSE` on the convenience methods is deprecated by Jane. Prefer +`executeRawEndpoint()` in new code. A response body is also a cursor: reading +it consumes bytes. Do not assume you can rewind a live socket body. + +## Error handling + +There are three separate failure paths: + +1. Local validation or serialization fails before the request is sent. +2. A transport error or a documented HTTP API error occurs. +3. An operation starts successfully but reports an error inside its progress + stream, such as a pull, push or build failure after HTTP 200. + +Handle documented API exceptions on typed calls, and inspect progress frames +on streaming calls. For example: + +```php +containerInspect('my-container'); + printf("%s\n", $container->getId()); +} catch (ContainerInspectNotFoundException $error) { + throw new RuntimeException( + $error->getErrorResponse()->getMessage() ?? 'Container not found', + 0, + $error + ); +} catch (ClientExceptionInterface $error) { + throw new RuntimeException('The Docker request could not be completed', 0, $error); +} +``` + +The factory itself makes an `/info` request and can fail before the `try` block +above. Include client creation in your application's outer connection/error +handling. + +### Unexpected error statuses + +Generated exceptions cover the status codes and JSON responses listed in +Docker's API specification. Docker also returns errors the specification +leaves out: `containerUpdate()` answers an invalid memory limit with HTTP 400, +`networkCreate()` answers a duplicate name with 409, and a proxy in front of +the daemon can return its own errors. + +An error status of 400 or above that the endpoint does not handle throws +`Docker\Exception\UnexpectedClientErrorException` (4xx) or +`UnexpectedServerErrorException` (5xx). Both extend +`Docker\Exception\UnexpectedStatusCodeException`, which exposes the status +code, the request method and path, Docker's error message and the response. +They also implement the generated `ClientException` and `ServerException` +interfaces, so existing `catch` blocks for those still match. + +Success responses are unchanged: a `304` from starting a running container +still returns `null`, and raw responses (`FETCH_RESPONSE`) are never checked. + +To return `null` for these responses instead, as 3.x did by default: + +```php +$docker = Docker::create()->throwOnUnexpectedStatus(false); +``` + +Do not automatically retry every failed request. A connection failure after +submission can leave the operation's outcome unknown. Reconcile the container +or image state before retrying a create, start, upload or other mutation. diff --git a/docs/reference/streams.mdx b/docs/reference/streams.mdx new file mode 100644 index 000000000..68b4a83a7 --- /dev/null +++ b/docs/reference/streams.mdx @@ -0,0 +1,182 @@ +--- +title: "Streaming and special calls" +description: "Find the calls which return streams, binary bodies, headers or untyped data." +--- + +These calls need more than the usual request-model/response-model pattern. +The table applies to every supported API line. + +| Call | Default result / special behavior | Guide | +| --- | --- | --- | +| `imageCreate()` | `CreateImageStream`; pull/import progress frames | [Registries](/guides/registry) | +| `imageBuild()` | Tar request body and `BuildStream` | [Build an image](/cookbook/build-image) | +| `imagePush()` | `PushStream`; optional `AuthConfig` header conversion | [Registries](/guides/registry#push-a-tagged-image) | +| `containerLogs()` | `DockerRawStream`; TTY-aware output decoding | [Logs](/guides/logs) | +| `execStart()` | Attached output stream, or no output when detached | [Exec](/guides/exec) | +| `systemEvents()` | `EventStream`, not one event model | [Events and stats](/guides/events-and-stats) | +| `containerStats()` | `StatsStream` by default; one sample with `stream=false` | [Events and stats](/guides/events-and-stats#continuous-stats) | +| `containerArchive()` / `containerExport()` | Tar response; use a raw endpoint to retain the body | [Archive transfers](/guides/archives) | +| `containerArchiveInfo()` | Metadata in a response header, not a response model | [Archive transfers](/guides/archives#read-path-metadata) | +| `putContainerArchive()` | Tar request body; successful typed result is `null` | [Archive transfers](/guides/archives#upload-a-tar-archive) | +| `imageGet()` / `imageGetAll()` | Image tar archive; use a raw response | [Image transfers](/guides/image-transfer) | +| `imageLoad()` | Tar request and JSON progress response; no custom progress wrapper | [Image transfers](/guides/image-transfer#load-an-image-archive) | +| `containerWait()` | Blocking call returning a `ContainerWaitResponse` | [Run a container](/cookbook/container-run) | + +## Callback streams + +Register callbacks before calling `wait()`. The endpoint call obtains the +response; `wait()` reads its body and invokes callbacks synchronously. +Registering a callback alone does not consume output or finish the operation. + +`onFrame()` receives generated models for build, pull, push and event streams, +and decoded objects for stats streams. Their responses contain multiple JSON +documents, not one JSON array. +`onStdout()` and `onStderr()` receive strings for logs and exec output. +See [output framing](/guides/logs#output-chunks-and-tty-mode) for the difference +between output chunks and lines. + +Do not decode a whole progress stream with one `json_decode()` call. Check +`Docker\Stream\FrameError::message($frame)` on every build, pull or push +frame: HTTP 200 means the stream opened, not that the operation succeeded. The +helper reads whichever error field the installed API line has. + +## Custom socket clients + +`DockerClientFactory::create()` and `Docker::create()` without a supplied client +already use `Docker\Http\StreamingDecoderPlugin`. You do not need to add it +when using the bundled factory. + +If you build a socket client and its plugin chain yourself, use this plugin +in place of `Http\Client\Common\Plugin\DecoderPlugin`. It decodes HTTP chunked +responses incrementally and adapts socket reads so TTY output can arrive +before the stream finishes: + +```php Custom socket client + 'unix:///run/custom/docker.sock', + 'timeout' => 10000, + ]), + [ + new ContentLengthPlugin(), + new StreamingDecoderPlugin(), + new AddHostPlugin(new Uri('http://localhost')), + ] +); + +$docker = Docker::create($httpClient); +``` + +The generated server plugin supplies the installed API line's path, such as +`/v1.57`, in this example. If your custom +chain already supplies the versioned path, disable the server plugins with +`Docker::create($httpClient, [], [], false)` to avoid configuring it twice. + +`Docker::create($httpClient)` does not replace an existing client's decoder. +The streaming plugin handles HTTP transfer decoding, not Docker's stdout/stderr +frames, and cannot undo buffering inside another HTTP transport. In particular, +adding it to Guzzle's cURL handler does not make that handler stream responses. +See [HTTP clients](/guides/guzzle) for the transport comparison. + +## Lifetime, cancellation and timeouts + +`wait()` blocks until the stream ends, `stop()` is called or an error +interrupts it. A log follow +or event subscription can remain open indefinitely. The client does not turn +these calls into background jobs, promises or an event loop. + +Use bounded event queries for batch jobs. Set transport timeouts appropriate +to the operation, and keep long-lived readers in a supervised worker rather +than an ordinary web request. Reconnect and reconcile state in your application +after a connection failure; there is no automatic durable event subscription. + +Call `stop()` on a callback stream to close its body and end `wait()`. From +inside a frame callback, `wait()` returns after that frame's callbacks have +run. `stop()` requires `3.3.0` or later. Do not treat +`CallbackStream::closeAndRead()` as a graceful stop signal: it closes the +underlying body before calling `wait()`. For explicit stream ownership, use a +raw endpoint, manage its PSR-7 body and close it in a `finally` block. +Closing a build or pull connection can cancel the daemon operation. + +## Raw and generated endpoints + +`Docker\Docker`'s convenience methods select the custom endpoint wrappers. +Calling `executeEndpoint(new Docker\API\Endpoint\SystemEvents(...))` directly +selects the generated endpoint, not the event-stream wrapper. Likewise, a raw +endpoint returns bytes and headers without either wrapper's decoding. + +Choose deliberately between: + +- A `Docker\Docker` convenience method for supported callback streams. +- A generated endpoint with `executeRawEndpoint()` for tar bodies, headers or + streams that your application decodes itself. + +See [Requests and responses](/reference/requests-and-responses#raw-responses-and-headers) +for status checks and raw-fetch error handling. + +## Attach and WebSocket limitations + +`containerAttach()` attaches to the container's existing process; it does not +create a new command like `containerExec()` followed by `execStart()`. + +`containerAttach()` returns a `DockerRawStream` for plain and upgraded +responses. Docker labels TTY output and framed non-TTY output on plain +responses with the same content type, so the client inspects the container's +TTY setting to choose the decoder. TTY output arrives through `onStdout()`. +Since `3.3.0`, attaching to a TTY container no longer loses its output. + +`containerAttachWebsocket()` returns an `AttachWebsocketStream` with `read()`, +`write()` and `close()`, not `onStdout()`/`wait()`. It is useful when you need +to write to the container's stdin over the attach connection: + +```php +containerAttachWebsocket('my-container', [ + 'stream' => true, + 'stdin' => true, + 'stdout' => true, + 'stderr' => true, +]); + +$attach->write("echo hello\n"); +// Print output until a second passes without any. +while (is_string($output = $attach->read(1))) { + echo $output; +} +$attach->close(); +``` + +`read()` waits up to the given seconds and microseconds for one frame. It +returns the frame's bytes, `false` when nothing arrived in time, or `null` once +Docker has closed the connection. A frame is a chunk of output, not a line. +Docker mixes stdout and stderr in the same frames, with no marker for which +stream a chunk came from. The stream answers pings and closes itself when +Docker sends a close frame. `write()` sends one binary frame. + +WebSocket attach needs `3.3.0` or later; earlier clients returned `null` +instead of a stream. Docker Desktop's socket proxy upgrades the connection but +does not forward attach output; a Linux daemon or a remote engine works. For +driving commands, [interactive exec](/guides/interactive-exec) gives separate +stdout and stderr, exit codes and deadlines. + +`DockerRawStream::onStdin()` is an output-channel callback; it is not a method +for writing commands into a container. Prefer the [exec recipe](/guides/exec) +for non-interactive command execution. diff --git a/docs/scripts/check-php-examples.php b/docs/scripts/check-php-examples.php new file mode 100644 index 000000000..21ab0c711 --- /dev/null +++ b/docs/scripts/check-php-examples.php @@ -0,0 +1,40 @@ + !$entry->isDir() + || !in_array($entry->getFilename(), ['node_modules', '.mintlify'], true) +)); +$count = 0; + +foreach ($pages as $page) { + if (!$page->isFile() || $page->getExtension() !== 'mdx') { + continue; + } + + $relativePath = substr($page->getPathname(), strlen($directory) + 1); + preg_match_all('/^```php[^\r\n]*\R(.*?)^```/ms', file_get_contents($page->getPathname()), $blocks); + + foreach ($blocks[1] as $index => $code) { + $code = preg_replace('/^\s*<\?php\s*/', '', $code); + + try { + token_get_all("getMessage())); + exit(1); + } + + ++$count; + } +} + +if ($count === 0) { + fwrite(STDERR, "No PHP documentation examples found.\n"); + exit(1); +} + +printf("Checked the syntax of %d PHP documentation examples on PHP %s.\n", $count, PHP_VERSION); diff --git a/mkdocs.yml b/mkdocs.yml deleted file mode 100644 index 1f127ad32..000000000 --- a/mkdocs.yml +++ /dev/null @@ -1,15 +0,0 @@ -site_name: Docker PHP -site_url: http://docker-php.readthedocs.org/ -site_description: A Docker client in PHP -repo_url: https://github.com/docker-php/docker-php - -pages: - - Home: index.md - - Docker PHP: - - Installation: installation.md - - Connecting to Docker: connection.md - - Basic Usage: basic.md - - Asynchronous Client: async.md - - Cookbook: - - Running a container: cookbook/container-run.md - - Build an image: cookbook/build-image.md diff --git a/phpunit.xml.dist b/phpunit.xml.dist index c40525666..cbc386105 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,27 +1,23 @@ - - - - - - tests/ - - - - - src - - - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.4/phpunit.xsd" + backupGlobals="false" + colors="true" + processIsolation="false" + stopOnFailure="false" + bootstrap="vendor/autoload.php" + cacheDirectory=".phpunit.cache" + backupStaticProperties="false"> + + + + tests/ + + + + + src + + diff --git a/src/Client/AmpArtaxStreamEndpoint.php b/src/Client/AmpArtaxStreamEndpoint.php deleted file mode 100644 index ec7f3b9a0..000000000 --- a/src/Client/AmpArtaxStreamEndpoint.php +++ /dev/null @@ -1,26 +0,0 @@ -transformResponseBody($chunk, $response->getStatus(), $serializer); - }; - } - - return new ArtaxCallbackStream($response->getBody(), $cancellationTokenSource, $responseTransformer); - }); - } -} diff --git a/src/Client/ProvideAmpArtaxClientOptions.php b/src/Client/ProvideAmpArtaxClientOptions.php deleted file mode 100644 index cd1aa87db..000000000 --- a/src/Client/ProvideAmpArtaxClientOptions.php +++ /dev/null @@ -1,15 +0,0 @@ -directory = $directory; $this->format = $format; @@ -86,7 +91,20 @@ public function setDirectory($directory): void */ public function getDockerfileContent() { - return \file_get_contents($this->directory.DIRECTORY_SEPARATOR.'Dockerfile'); + return file_get_contents($this->directory.\DIRECTORY_SEPARATOR.'Dockerfile'); + } + + /** + * Whether to leave out paths matched by the context's .dockerignore file, + * as `docker build` does (the default). + * + * Pass false to archive the whole directory, as 3.x did by default. + */ + public function applyDockerignore(bool $enabled = true): static + { + $this->applyDockerignore = $enabled; + + return $this; } /** @@ -114,7 +132,7 @@ public function read() */ public function toTar() { - $process = new Process('/usr/bin/env tar c .', $this->directory); + $process = new Process($this->tarCommand(), $this->directory); $process->run(); if (!$process->isSuccessful()) { @@ -132,7 +150,7 @@ public function toTar() public function toStream() { if (!\is_resource($this->process)) { - $this->process = \proc_open('/usr/bin/env tar c .', [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes, $this->directory); + $this->process = proc_open($this->tarCommand(), [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes, $this->directory); $this->stream = $pipes[1]; } @@ -142,11 +160,15 @@ public function toStream() public function __destruct() { if (\is_resource($this->stream)) { - \fclose($this->stream); + fclose($this->stream); } if (\is_resource($this->process)) { - \proc_close($this->process); + proc_close($this->process); + } + + if (null !== $this->pathList) { + $this->fs->remove($this->pathList); } if ($this->cleanup) { @@ -154,6 +176,28 @@ public function __destruct() } } + /** + * @return list + */ + private function tarCommand(): array + { + $dockerignore = $this->directory.\DIRECTORY_SEPARATOR.'.dockerignore'; + if (!$this->applyDockerignore || !is_file($dockerignore)) { + return ['/usr/bin/env', 'tar', '-c', '.']; + } + + // Write the list to a file rather than tar's stdin, so tar can stream + // the archive without waiting for the whole list to be read. + if (null === $this->pathList) { + $paths = Dockerignore::fromFile($dockerignore)->paths($this->directory); + $this->pathList = $this->fs->tempnam(sys_get_temp_dir(), 'docker-context-'); + // "./" keeps names that start with "-" from being read as options. + $this->fs->dumpFile($this->pathList, implode('', array_map(static fn (string $path): string => './'.$path."\0", $paths))); + } + + return ['/usr/bin/env', 'tar', '-c', '--no-recursion', '--null', '-T', $this->pathList]; + } + /** * @param bool $value whether to remove the context directory */ diff --git a/src/Context/ContextBuilder.php b/src/Context/ContextBuilder.php index 74a4308bf..cda9629f5 100644 --- a/src/Context/ContextBuilder.php +++ b/src/Context/ContextBuilder.php @@ -39,9 +39,9 @@ class ContextBuilder private $entrypoint; /** - * @param \Symfony\Component\Filesystem\Filesystem + * @param \Symfony\Component\Filesystem\Filesystem $fs */ - public function __construct(Filesystem $fs = null) + public function __construct(?Filesystem $fs = null) { $this->fs = $fs ?: new Filesystem(); $this->format = Context::FORMAT_STREAM; @@ -255,7 +255,7 @@ public function volume($volume) */ public function getContext() { - $directory = \sys_get_temp_dir().'/ctb-'.\microtime(); + $directory = sys_get_temp_dir().'/ctb-'.microtime(); $this->fs->mkdir($directory); $this->write($directory); @@ -276,7 +276,7 @@ private function write($directory): void { $dockerfile = []; // Insert a FROM instruction if the file does not start with one. - if (empty($this->commands) || $this->commands[0]['type'] !== 'FROM') { + if (empty($this->commands) || 'FROM' !== $this->commands[0]['type']) { $dockerfile[] = 'FROM base'; } foreach ($this->commands as $command) { @@ -325,7 +325,7 @@ private function write($directory): void $dockerfile[] = 'CMD '.$this->command; } - $this->fs->dumpFile($directory.DIRECTORY_SEPARATOR.'Dockerfile', \implode(PHP_EOL, $dockerfile)); + $this->fs->dumpFile($directory.\DIRECTORY_SEPARATOR.'Dockerfile', implode(\PHP_EOL, $dockerfile)); } /** @@ -338,12 +338,12 @@ private function write($directory): void */ private function getFile($directory, $content) { - $hash = \md5($content); + $hash = md5($content); if (!\array_key_exists($hash, $this->files)) { - $file = \tempnam($directory, ''); + $file = tempnam($directory, ''); $this->fs->dumpFile($file, $content); - $this->files[$hash] = \basename($file); + $this->files[$hash] = basename($file); } return $this->files[$hash]; @@ -359,14 +359,14 @@ private function getFile($directory, $content) */ private function getFileFromStream($directory, $stream) { - $file = \tempnam($directory, ''); - $target = \fopen($file, 'w'); - if (0 === \stream_copy_to_stream($stream, $target)) { + $file = tempnam($directory, ''); + $target = fopen($file, 'w'); + if (0 === stream_copy_to_stream($stream, $target)) { throw new \RuntimeException('Failed to write stream to file'); } - \fclose($target); + fclose($target); - return \basename($file); + return basename($file); } /** @@ -379,10 +379,10 @@ private function getFileFromStream($directory, $stream) */ private function getFileFromDisk($directory, $source) { - $hash = 'DISK-'.\md5(\realpath($source)); + $hash = 'DISK-'.md5(realpath($source)); if (!\array_key_exists($hash, $this->files)) { // Check if source is a directory or a file. - if (\is_dir($source)) { + if (is_dir($source)) { $this->fs->mirror($source, $directory.'/'.$hash, null, ['copy_on_windows' => true]); } else { $this->fs->copy($source, $directory.'/'.$hash); diff --git a/src/Context/Dockerignore.php b/src/Context/Dockerignore.php new file mode 100644 index 000000000..470fcbc6b --- /dev/null +++ b/src/Context/Dockerignore.php @@ -0,0 +1,207 @@ + */ + private array $patterns = []; + + private bool $hasExclusions = false; + + /** + * @param list $keep Paths the daemon always needs, re-included as the Docker CLI does + */ + public function __construct(string $content, array $keep = ['Dockerfile', '.dockerignore']) + { + foreach (preg_split('/\r\n|\n|\r/', $content) as $line) { + // Comments are only recognised at the very start of a line. + if (str_starts_with($line, '#')) { + continue; + } + $this->addPattern(trim($line)); + } + foreach ($keep as $path) { + $this->addPattern('!'.$path); + } + } + + public static function fromFile(string $file): self + { + $content = file_get_contents($file); + if (false === $content) { + throw new \RuntimeException(\sprintf('Cannot read %s.', $file)); + } + + // Ignore a UTF-8 byte order mark, as Docker does. + return new self(preg_replace('/^\xEF\xBB\xBF/', '', $content)); + } + + /** + * Whether a path, relative to the context root with `/` separators, is excluded. + */ + public function excludes(string $path): bool + { + $parts = explode('/', $path); + $excluded = false; + foreach ($this->patterns as $pattern) { + $matches = 1 === preg_match($pattern['regex'], $path); + // A pattern that matches a parent directory also matches its contents. + for ($i = 1; !$matches && $i < \count($parts); ++$i) { + $matches = 1 === preg_match($pattern['regex'], implode('/', \array_slice($parts, 0, $i))); + } + if ($matches) { + $excluded = !$pattern['exclusion']; + } + } + + return $excluded; + } + + /** + * List the paths to archive, relative to $directory and sorted. + * + * Directories are listed before their contents. An excluded directory is + * left out, but its re-included contents are still listed. + * + * @return list + */ + public function paths(string $directory): array + { + $paths = []; + $this->walk(rtrim($directory, '/'), '', $paths); + + return $paths; + } + + private function walk(string $directory, string $relative, array &$paths): void + { + $entries = scandir('' === $relative ? $directory : $directory.'/'.$relative); + if (false === $entries) { + throw new \RuntimeException(\sprintf('Cannot read the build context directory %s.', $directory.'/'.$relative)); + } + sort($entries, \SORT_STRING); + + foreach ($entries as $name) { + if ('.' === $name || '..' === $name) { + continue; + } + $path = '' === $relative ? $name : $relative.'/'.$name; + $full = $directory.'/'.$path; + // Symbolic links are archived as links, not followed. + $isDirectory = is_dir($full) && !is_link($full); + + if ($this->excludes($path)) { + if ($isDirectory && $this->hasExclusions) { + $this->walk($directory, $path, $paths); + } + continue; + } + + $paths[] = $path; + if ($isDirectory) { + $this->walk($directory, $path, $paths); + } + } + } + + private function addPattern(string $pattern): void + { + $exclusion = str_starts_with($pattern, '!'); + if ($exclusion) { + $pattern = trim(substr($pattern, 1)); + } + if ('' === $pattern) { + return; + } + + $pattern = self::clean($pattern); + if ($exclusion) { + $this->hasExclusions = true; + } + $this->patterns[] = ['regex' => self::compile($pattern), 'exclusion' => $exclusion]; + } + + /** + * Go's filepath.Clean, then strip a leading `/`: patterns are relative to the context root. + */ + private static function clean(string $pattern): string + { + $parts = []; + foreach (explode('/', $pattern) as $part) { + if ('' === $part || '.' === $part) { + continue; + } + if ('..' === $part) { + array_pop($parts); + continue; + } + $parts[] = $part; + } + + return [] === $parts ? '.' : implode('/', $parts); + } + + /** + * Translate a pattern to a regular expression, following moby/patternmatcher. + */ + private static function compile(string $pattern): string + { + $regex = ''; + $inClass = false; + $length = \strlen($pattern); + for ($i = 0; $i < $length; ++$i) { + $char = $pattern[$i]; + if ($inClass) { + // Character classes pass through, including ranges and `^` negation. + if (']' === $char) { + $inClass = false; + } elseif ('#' === $char) { + $char = '\\#'; + } elseif ('\\' === $char && $i + 1 < $length) { + $char .= $pattern[++$i]; + } + $regex .= $char; + } elseif ('[' === $char) { + $inClass = true; + $regex .= $char; + } elseif ('*' === $char) { + if ('*' === ($pattern[$i + 1] ?? '')) { + ++$i; + // Treat "**/" as "**". + if ('/' === ($pattern[$i + 1] ?? '')) { + ++$i; + } + // A trailing "**" matches everything; otherwise any number of directories. + $regex .= $i + 1 >= $length ? '.*' : '(.*/)?'; + } else { + $regex .= '[^/]*'; + } + } elseif ('?' === $char) { + $regex .= '[^/]'; + } elseif ('\\' === $char) { + $regex .= $i + 1 < $length ? preg_quote($pattern[++$i], '#') : '\\\\'; + } else { + $regex .= preg_quote($char, '#'); + } + } + + $regex = '#^'.$regex.'$#'; + if ($inClass || false === @preg_match($regex, '')) { + throw new \InvalidArgumentException(\sprintf('Invalid .dockerignore pattern "%s".', $pattern)); + } + + return $regex; + } +} diff --git a/src/Docker.php b/src/Docker.php index 591acb5f0..d38dd6211 100644 --- a/src/Docker.php +++ b/src/Docker.php @@ -5,95 +5,309 @@ namespace Docker; use Docker\API\Client; +use Docker\API\Endpoint\SystemInfo; use Docker\API\Model\AuthConfig; +use Docker\API\Model\ExecIdStartPostBody; use Docker\Endpoint\ContainerAttach; use Docker\Endpoint\ContainerAttachWebsocket; use Docker\Endpoint\ContainerLogs; +use Docker\Endpoint\ContainerStats; use Docker\Endpoint\ExecStart; use Docker\Endpoint\ImageBuild; use Docker\Endpoint\ImageCreate; use Docker\Endpoint\ImagePush; +use Docker\Endpoint\InteractiveExecStart; use Docker\Endpoint\SystemEvents; +use Docker\API\Normalizer\JaneObjectNormalizer; +use Docker\API\Runtime\Client\Endpoint; +use Docker\API\Runtime\Client\FormEncoder; +use Docker\Exception\BadRequestException; +use Docker\Exception\UnexpectedStatusCodeException; +use Docker\Http\InteractiveHttpClient; +use Docker\Serializer\LargeIntegerJsonDecode; +use Docker\Stream\AttachWebsocketStream; +use Docker\Stream\BuildStream; +use Docker\Stream\CreateImageStream; +use Docker\Stream\DockerRawStream; +use Docker\Stream\EventStream; +use Docker\Stream\InteractiveExecStream; +use Docker\Stream\PushStream; +use Docker\Stream\StatsStream; +use Docker\Stream\SocketReadStream; +use Http\Client\Socket\Stream as SocketStream; +use Nyholm\Psr7\Stream; +use Psr\Http\Message\ResponseInterface; +use Symfony\Component\Serializer\Encoder\JsonEncode; +use Symfony\Component\Serializer\Encoder\JsonEncoder; +use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer; +use Symfony\Component\Serializer\Serializer; /** * Docker\Docker. */ class Docker extends Client { + private bool $interactiveExecEnabled = false; + + private bool $throwOnUnexpectedStatus = true; + + /** + * Whether an error status that the generated endpoint does not handle + * throws an UnexpectedStatusCodeException (the default). + * + * Pass false to return null for those responses, as 3.x did by default. + */ + public function throwOnUnexpectedStatus(bool $enabled = true): static + { + $this->throwOnUnexpectedStatus = $enabled; + + return $this; + } + + public function executeEndpoint(Endpoint $endpoint, string $fetch = self::FETCH_OBJECT) + { + if (self::FETCH_OBJECT !== $fetch) { + return parent::executeEndpoint($endpoint, $fetch); + } + + $response = $this->executeRawEndpoint($endpoint); + if ($response->getStatusCode() < 400) { + return $endpoint->parseResponse($response, $this->serializer, $fetch); + } + + // Error bodies are small. Buffer them so the message is still readable + // after the generated endpoint has parsed the body. + $response = $response->withBody(Stream::create((string) $response->getBody())); + $result = $endpoint->parseResponse($response, $this->serializer, $fetch); + if (null !== $result) { + return $result; + } + + if ($this->throwOnUnexpectedStatus) { + throw UnexpectedStatusCodeException::fromResponse($endpoint->getMethod(), $endpoint->getUri(), $response); + } + + return null; + } + + /** + * {@inheritdoc} + * + * @return ($fetch is 'object' ? DockerRawStream|null : ResponseInterface) + */ + public function containerAttach(string $id, array $queryParameters = [], string $fetch = self::FETCH_OBJECT, array $accept = []) + { + return $this->executeEndpoint(new ContainerAttach( + $id, + $queryParameters, + $accept, + fn (): bool => (bool) $this->containerInspect($id)->getConfig()?->getTty() + ), $fetch); + } + /** * {@inheritdoc} + * + * @return ($fetch is 'object' ? AttachWebsocketStream|null : ResponseInterface) */ - public function containerAttach(string $id, array $queryParameters = [], string $fetch = self::FETCH_OBJECT) + public function containerAttachWebsocket(string $id, array $queryParameters = [], string $fetch = self::FETCH_OBJECT, array $accept = []) { - return $this->executePsr7Endpoint(new ContainerAttach($id, $queryParameters), $fetch); + return $this->executeEndpoint(new ContainerAttachWebsocket($id, $queryParameters, $accept), $fetch); } /** * {@inheritdoc} + * + * @return ($fetch is 'object' ? DockerRawStream|null : ResponseInterface) */ - public function containerAttachWebsocket(string $id, array $queryParameters = [], string $fetch = self::FETCH_OBJECT) + public function containerLogs(string $id, array $queryParameters = [], string $fetch = self::FETCH_OBJECT, array $accept = []) { - return $this->executePsr7Endpoint(new ContainerAttachWebsocket($id, $queryParameters), $fetch); + return $this->executeEndpoint(new ContainerLogs( + $id, + $queryParameters, + $accept, + fn (): bool => (bool) $this->containerInspect($id)->getConfig()?->getTty() + ), $fetch); } /** * {@inheritdoc} + * + * With `stream => true` (the default) the result is a StatsStream that + * delivers one sample per frame; with `stream => false` it is one sample. + * Samples are ContainerStatsResponse models from API 1.48, and decoded + * \stdClass objects for earlier API versions. + * + * @return ($fetch is 'object' ? StatsStream|object|null : ResponseInterface) */ - public function containerLogs(string $id, array $queryParameters = [], string $fetch = self::FETCH_OBJECT) + public function containerStats(string $id, array $queryParameters = [], string $fetch = self::FETCH_OBJECT) { - return $this->executePsr7Endpoint(new ContainerLogs($id, $queryParameters), $fetch); + return $this->executeEndpoint(new ContainerStats($id, $queryParameters), $fetch); } /** * {@inheritdoc} + * + * @return ($fetch is 'object' ? DockerRawStream|null : ResponseInterface) + */ + public function execStart(string $id, ?ExecIdStartPostBody $requestBody = null, string $fetch = self::FETCH_OBJECT, array $accept = []) + { + return $this->executeEndpoint(new ExecStart($id, $requestBody, $accept), $fetch); + } + + /** + * Start attached exec with nonblocking stdin/stdout/stderr. timeoutMs is a + * streaming deadline after upgrade; HTTP setup uses the factory timeout. + * Inspect the exec separately after output EOF to obtain its exit status. */ - public function execStart(string $id, \Docker\API\Model\ExecIdStartPostBody $execStartConfig, string $fetch = self::FETCH_OBJECT) + public function execStartInteractive(string $id, ?ExecIdStartPostBody $requestBody = null, ?int $timeoutMs = null): InteractiveExecStream { - return $this->executePsr7Endpoint(new ExecStart($id, $execStartConfig), $fetch); + if (!$this->interactiveExecEnabled) { + throw new \LogicException('Interactive exec requires DockerClientFactory::createInteractive() or the default socket client.'); + } + if (null !== $timeoutMs && ($timeoutMs < 1 || $timeoutMs > 86400000)) { + throw new \InvalidArgumentException('Interactive exec timeout must be between 1 and 86400000 milliseconds.'); + } + if ('' === $id) { + throw new \InvalidArgumentException('An exec ID is required.'); + } + $body = null === $requestBody ? new ExecIdStartPostBody() : clone $requestBody; + if ($body->getDetach()) { + throw new \InvalidArgumentException('Interactive exec cannot be detached.'); + } + $body->setDetach(false); + $response = $this->executeRawEndpoint(new InteractiveExecStart($id, $body)); + $stream = $response->getBody(); + $mediaType = strtolower(trim(explode(';', $response->getHeaderLine('Content-Type'))[0])); + if (101 !== $response->getStatusCode() + || 'tcp' !== strtolower(trim($response->getHeaderLine('Upgrade'))) + || !preg_match('/(?:^|,)\s*upgrade\s*(?:,|$)/i', $response->getHeaderLine('Connection')) + || $response->hasHeader('Transfer-Encoding') + || $response->hasHeader('Content-Encoding') + || !\in_array($mediaType, [DockerRawStream::HEADER, DockerRawStream::MULTIPLEXED_HEADER], true) + || (!$stream instanceof SocketReadStream && !$stream instanceof SocketStream)) { + $stream->close(); + throw new \RuntimeException('Docker did not provide a supported interactive exec upgrade (HTTP '.$response->getStatusCode().').'); + } + // The detached resource keeps bytes PHP read ahead with the headers. + $socket = $stream->detach(); + try { + return new InteractiveExecStream($socket, !(bool) $body->getTty(), $timeoutMs); + } catch (\Throwable $error) { + if (\is_resource($socket)) { + fclose($socket); + } + throw $error; + } } /** * {@inheritdoc} + * + * @param array{ + * "dockerfile"?: string, + * "t"?: string|list, + * "extrahosts"?: string, + * "remote"?: string, + * "q"?: bool, + * "nocache"?: bool, + * "cachefrom"?: string, + * "pull"?: string, + * "rm"?: bool, + * "forcerm"?: bool, + * "memory"?: int, + * "memswap"?: int, + * "cpushares"?: int, + * "cpusetcpus"?: string, + * "cpuperiod"?: int, + * "cpuquota"?: int, + * "buildargs"?: string, + * "shmsize"?: int, + * "squash"?: bool, + * "labels"?: string, + * "networkmode"?: string, + * "platform"?: string, + * "target"?: string, + * "outputs"?: string, + * "version"?: string, + * } $queryParameters + * + * @return ($fetch is 'object' ? BuildStream|null : ResponseInterface) */ - public function imageBuild($inputStream, array $queryParameters = [], array $headerParameters = [], string $fetch = self::FETCH_OBJECT) + public function imageBuild($requestBody = null, array $queryParameters = [], array $headerParameters = [], string $fetch = self::FETCH_OBJECT) { - return $this->executePsr7Endpoint(new ImageBuild($inputStream, $queryParameters, $headerParameters), $fetch); + return $this->executeEndpoint(new ImageBuild($requestBody, $queryParameters, $headerParameters), $fetch); } /** * {@inheritdoc} + * + * @return ($fetch is 'object' ? CreateImageStream|null : ResponseInterface) */ - public function imageCreate(string $inputImage, array $queryParameters = [], array $headerParameters = [], string $fetch = self::FETCH_OBJECT) + public function imageCreate(?string $requestBody = null, array $queryParameters = [], array $headerParameters = [], string $fetch = self::FETCH_OBJECT) { - return $this->executePsr7Endpoint(new ImageCreate($inputImage, $queryParameters, $headerParameters), $fetch); + return $this->executeEndpoint(new ImageCreate($requestBody, $queryParameters, $headerParameters), $fetch); } /** * {@inheritdoc} + * + * @return ($fetch is 'object' ? PushStream|null : ResponseInterface) */ - public function imagePush(string $name, array $queryParameters = [], array $headerParameters = [], string $fetch = self::FETCH_OBJECT) + public function imagePush(string $name, array $queryParameters = [], array $headerParameters = [], string $fetch = self::FETCH_OBJECT, array $accept = []) { if (isset($headerParameters['X-Registry-Auth']) && $headerParameters['X-Registry-Auth'] instanceof AuthConfig) { - $headerParameters['X-Registry-Auth'] = \base64_encode($this->serializer->serialize($headerParameters['X-Registry-Auth'], 'json')); + $headerParameters['X-Registry-Auth'] = base64_encode($this->serializer->serialize($headerParameters['X-Registry-Auth'], 'json')); } - return $this->executePsr7Endpoint(new ImagePush($name, $queryParameters, $headerParameters), $fetch); + return $this->executeEndpoint(new ImagePush($name, $queryParameters, $headerParameters, $accept), $fetch); } /** * {@inheritdoc} + * + * @return ($fetch is 'object' ? EventStream|null : ResponseInterface) */ - public function systemEvents(array $queryParameters = [], string $fetch = self::FETCH_OBJECT) + public function systemEvents(array $queryParameters = [], string $fetch = self::FETCH_OBJECT, array $accept = []) { - return $this->executePsr7Endpoint(new SystemEvents($queryParameters), $fetch); + // API 1.52 and later accept an Accept header; earlier endpoints ignore it. + return $this->executeEndpoint(new SystemEvents($queryParameters, $accept), $fetch); } - public static function create($httpClient = null) - { + public static function create( + $httpClient = null, + array $additionalPlugins = [], + array $additionalNormalizers = [], + bool $applyServerPlugins = true + ): self { if (null === $httpClient) { - $httpClient = DockerClientFactory::createFromEnv(); + $httpClient = DockerClientFactory::createInteractiveFromEnv(); + $applyServerPlugins = false; + } + + $client = parent::create($httpClient, $additionalPlugins, $additionalNormalizers, $applyServerPlugins); + $client->serializer = new Serializer( + [new ArrayDenormalizer(), new JaneObjectNormalizer(), ...$additionalNormalizers], + [new JsonEncoder(new JsonEncode(), new LargeIntegerJsonDecode(['json_decode_associative' => true])), new FormEncoder()] + ); + $client->interactiveExecEnabled = $httpClient instanceof InteractiveHttpClient; + $response = $client->executeRawEndpoint(new SystemInfo()); + $testClient = $response->getBody()->getContents(); + $jsonObj = json_decode($testClient); + + if ($jsonObj !== null) { + if (isset($jsonObj->message)) { + // Check if the client is too new + if (strpos($jsonObj->message, 'client version') !== false && strpos($jsonObj->message, 'is too new') !== false) { + throw new BadRequestException("The client version is not supported by your version of Docker. Message: {$jsonObj->message}", $response); + } else { + throw new BadRequestException($jsonObj->message, $response); + } + } + } else { + throw new BadRequestException("Failed to decode JSON.", $response); } - return parent::create($httpClient); + return $client; } } diff --git a/src/DockerAsync.php b/src/DockerAsync.php deleted file mode 100644 index 111b4efc5..000000000 --- a/src/DockerAsync.php +++ /dev/null @@ -1,74 +0,0 @@ -executeArtaxEndpoint(new SystemEvents($queryParameters), $fetch); - } - - /** - * {@inheritdoc} - */ - public function executeArtaxEndpoint(AmpArtaxEndpoint $endpoint, string $fetch = self::FETCH_OBJECT): Promise - { - return call(function () use ($endpoint, $fetch) { - [$bodyHeaders, $body] = $endpoint->getBody($this->serializer); - $queryString = $endpoint->getQueryString(); - $uri = '' !== $queryString ? $endpoint->getUri().'?'.$queryString : $endpoint->getUri(); - $request = new Request($uri, $endpoint->getMethod()); - $request = $request->withBody($body); - $request = $request->withHeaders($endpoint->getHeaders($bodyHeaders)); - $options = []; - if ($endpoint instanceof ProvideAmpArtaxClientOptions) { - $options = $endpoint->getAmpArtaxClientOptions(); - } - - if ($endpoint instanceof AmpArtaxStreamEndpoint) { - $cancellationTokenSource = new CancellationTokenSource(); - - return $endpoint->parseArtaxStreamResponse( - yield $this->httpClient->request($request, $options, $cancellationTokenSource->getToken()), - $this->serializer, - $cancellationTokenSource, - $fetch - ); - } - - return $endpoint->parseArtaxResponse( - yield $this->httpClient->request($request, $options), - $this->serializer, - $fetch - ); - }); - } -} diff --git a/src/DockerAsyncClient.php b/src/DockerAsyncClient.php deleted file mode 100644 index ca440bd7b..000000000 --- a/src/DockerAsyncClient.php +++ /dev/null @@ -1,87 +0,0 @@ -resolveOptions($options); - $socketPool = new HttpSocketPool(new StaticSocketPool($options['remote_socket'], new BasicSocketPool())); - $this->client = new DefaultClient(null, $socketPool, $options['ssl']); - } - - public function request($uriOrRequest, array $options = [], CancellationToken $cancellation = null): Promise - { - if ($uriOrRequest instanceof Request) { - $uriOrRequest = $uriOrRequest->withUri('http://localhost'.$uriOrRequest->getUri()); - } - - return $this->client->request($uriOrRequest, $options, $cancellation); - } - - protected function resolveOptions(array $options = []): array - { - $resolver = new OptionsResolver(); - - $resolver->setDefaults([ - 'ssl' => null, - ]); - - $resolver->setRequired([ - 'remote_socket', - ]); - - $resolver->setAllowedTypes('ssl', ['null', ClientTlsContext::class]); - - return $resolver->resolve($options); - } - - public static function createFromEnv(): self - { - $options = [ - 'remote_socket' => \getenv('DOCKER_HOST') ? \getenv('DOCKER_HOST') : 'unix:///var/run/docker.sock', - ]; - - if (\getenv('DOCKER_TLS_VERIFY') && '1' === \getenv('DOCKER_TLS_VERIFY')) { - if (!\getenv('DOCKER_CERT_PATH')) { - throw new \RuntimeException('Connection to docker has been set to use TLS, but no PATH is defined for certificate in DOCKER_CERT_PATH docker environment variable'); - } - - $tlsContext = new ClientTlsContext(); - - $cafile = \getenv('DOCKER_CERT_PATH').DIRECTORY_SEPARATOR.'ca.pem'; - $certfile = \getenv('DOCKER_CERT_PATH').DIRECTORY_SEPARATOR.'cert.pem'; - $keyfile = \getenv('DOCKER_CERT_PATH').DIRECTORY_SEPARATOR.'key.pem'; - - $certificate = new Certificate($certfile, $keyfile); - - $tlsContext = $tlsContext->withCaFile($cafile); - $tlsContext = $tlsContext->withCertificate($certificate); - - if (\getenv('DOCKER_PEER_NAME')) { - $tlsContext = $tlsContext->withPeerName(\getenv('DOCKER_PEER_NAME')); - } - - $options['ssl'] = $tlsContext; - } - - return new static($options); - } -} diff --git a/src/DockerClientFactory.php b/src/DockerClientFactory.php index 918d87240..7c354f134 100644 --- a/src/DockerClientFactory.php +++ b/src/DockerClientFactory.php @@ -4,55 +4,158 @@ namespace Docker; -use GuzzleHttp\Psr7\Uri; +use Docker\API\Client as GeneratedClient; +use Docker\Http\ApiVersionNegotiationPlugin; +use Docker\Http\InteractiveHttpClient; +use Docker\Http\StreamingDecoderPlugin; use Http\Client\Common\Plugin\AddHostPlugin; +use Http\Client\Common\Plugin\AddPathPlugin; use Http\Client\Common\Plugin\ContentLengthPlugin; -use Http\Client\Common\Plugin\DecoderPlugin; +use Http\Client\Common\Plugin\HeaderDefaultsPlugin; +use Http\Client\Common\PluginClient; use Http\Client\Common\PluginClientFactory; -use Http\Client\HttpClient; -use Http\Client\Socket\Client as SocketHttpClient; -use Http\Message\MessageFactory\GuzzleMessageFactory; +use Http\Client\Socket\Client; +use Http\Discovery\Psr17FactoryDiscovery; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; final class DockerClientFactory { + private static ?string $defaultApiVersion = null; + + /** + * The Docker API version of the installed docker-php/docker-php-api package, + * for example "1.56". Requests use it unless api_version or DOCKER_API_VERSION + * says otherwise. + */ + public static function defaultApiVersion(): string + { + if (null !== self::$defaultApiVersion) { + return self::$defaultApiVersion; + } + + // The generated client adds its specification's base path to requests. + // Capture one request instead of trusting Composer metadata, so the + // version always matches the classes that are actually loaded. + $recorder = new class implements ClientInterface { + public ?RequestInterface $request = null; + + public function sendRequest(RequestInterface $request): ResponseInterface + { + $this->request = $request; + + return Psr17FactoryDiscovery::findResponseFactory()->createResponse(204); + } + }; + $client = GeneratedClient::create($recorder); + $httpClient = (fn (): ClientInterface => $this->httpClient)->call($client); + $httpClient->sendRequest(Psr17FactoryDiscovery::findRequestFactory()->createRequest('GET', '/')); + + $path = (string) $recorder->request?->getUri()->getPath(); + if (!preg_match('#^/v([0-9]+\.[0-9]+)/#', $path, $matches)) { + throw new \LogicException('Cannot determine the Docker API version of the installed docker-php/docker-php-api package.'); + } + + return self::$defaultApiVersion = $matches[1]; + } + /** - * ( . + * The api_version option overrides DOCKER_API_VERSION. Without either, the + * client negotiates: it uses the installed API package's version, or the + * daemon's maximum if that is lower. Other options are passed to the socket + * client. No setting changes the generated models. */ - public static function create(array $config = [], PluginClientFactory $pluginClientFactory = null): HttpClient + public static function create(array $config = [], ?PluginClientFactory $pluginClientFactory = null): PluginClient { + if (\array_key_exists('api_version', $config)) { + if (!\is_string($config['api_version']) || !preg_match('#^/?v?[0-9]+\.[0-9]+$#D', $config['api_version'])) { + throw new \InvalidArgumentException('api_version must be a Docker API version such as 1.45 or v1.45.'); + } + $dockerApiVersion = $config['api_version']; + unset($config['api_version']); + } else { + // Null negotiates with the daemon, up to the installed API package's version. + $dockerApiVersion = getenv('DOCKER_API_VERSION') ?: null; + } + if (null !== $dockerApiVersion) { + $dockerApiVersion = ltrim($dockerApiVersion, '/'); + if (!str_starts_with($dockerApiVersion, 'v')) { + $dockerApiVersion = 'v'.$dockerApiVersion; + } + } + if (!\array_key_exists('remote_socket', $config)) { $config['remote_socket'] = 'unix:///var/run/docker.sock'; } - $messageFactory = new GuzzleMessageFactory(); - $socketClient = new SocketHttpClient($messageFactory, $config); - $host = \preg_match('/unix:\/\//', $config['remote_socket']) ? 'http://localhost' : $config['remote_socket']; + $uriFactory = Psr17FactoryDiscovery::findUriFactory(); + $unixSocket = str_starts_with($config['remote_socket'], 'unix://'); + $host = $uriFactory->createUri($unixSocket ? 'http://localhost' : $config['remote_socket']); + $scheme = $unixSocket ? 'unix' : $host->getScheme(); + + if (\in_array($scheme, ['http', 'https', 'tcp'], true)) { + if ('https' === $scheme) { + $config['ssl'] = true; + } + + if ('http' === $scheme || 'https' === $scheme) { + // The socket client negotiates TLS after opening the TCP connection. + $port = $host->getPort() ?? ('https' === $scheme ? 443 : 80); + $config['remote_socket'] = 'tcp://'.$host->getHost().':'.$port; + } + + $host = $host->withScheme(($config['ssl'] ?? false) ? 'https' : 'http'); + } + + $socketClient = new Client($config); + + $pluginClientFactory ??= new PluginClientFactory(); + + return $pluginClientFactory->createClient( + $socketClient, + [ + new ContentLengthPlugin(), + new StreamingDecoderPlugin(), + null === $dockerApiVersion + ? new ApiVersionNegotiationPlugin(self::defaultApiVersion(), $uriFactory, Psr17FactoryDiscovery::findRequestFactory()) + : new AddPathPlugin($uriFactory->createUri('/'.$dockerApiVersion)), + new AddHostPlugin($host), + new HeaderDefaultsPlugin([ + 'host' => $host->withUserInfo('')->getAuthority(), + ]), + ], + [ + 'client_name' => 'docker-client', + ] + ); + } - $pluginClientFactory = $pluginClientFactory ?? new PluginClientFactory(); + /** Socket transport with opt-in interactive exec support. */ + public static function createInteractive(array $config = [], ?PluginClientFactory $pluginClientFactory = null): InteractiveHttpClient + { + return new InteractiveHttpClient(self::create($config, $pluginClientFactory)); + } - return $pluginClientFactory->createClient($socketClient, [ - new ContentLengthPlugin(), - new DecoderPlugin(), - new AddHostPlugin(new Uri($host)), - ], [ - 'client_name' => 'docker-client', - ]); + public static function createInteractiveFromEnv(?PluginClientFactory $pluginClientFactory = null): InteractiveHttpClient + { + return new InteractiveHttpClient(self::createFromEnv($pluginClientFactory)); } - public static function createFromEnv(PluginClientFactory $pluginClientFactory = null): HttpClient + public static function createFromEnv(?PluginClientFactory $pluginClientFactory = null): PluginClient { $options = [ - 'remote_socket' => \getenv('DOCKER_HOST') ? \getenv('DOCKER_HOST') : 'unix:///var/run/docker.sock', + 'remote_socket' => getenv('DOCKER_HOST') ? getenv('DOCKER_HOST') : 'unix:///var/run/docker.sock', ]; - if (\getenv('DOCKER_TLS_VERIFY') && '1' === \getenv('DOCKER_TLS_VERIFY')) { - if (!\getenv('DOCKER_CERT_PATH')) { + if (getenv('DOCKER_TLS_VERIFY') && '1' === getenv('DOCKER_TLS_VERIFY')) { + if (!getenv('DOCKER_CERT_PATH')) { throw new \RuntimeException('Connection to docker has been set to use TLS, but no PATH is defined for certificate in DOCKER_CERT_PATH docker environment variable'); } - $cafile = \getenv('DOCKER_CERT_PATH').DIRECTORY_SEPARATOR.'ca.pem'; - $certfile = \getenv('DOCKER_CERT_PATH').DIRECTORY_SEPARATOR.'cert.pem'; - $keyfile = \getenv('DOCKER_CERT_PATH').DIRECTORY_SEPARATOR.'key.pem'; + $cafile = getenv('DOCKER_CERT_PATH').\DIRECTORY_SEPARATOR.'ca.pem'; + $certfile = getenv('DOCKER_CERT_PATH').\DIRECTORY_SEPARATOR.'cert.pem'; + $keyfile = getenv('DOCKER_CERT_PATH').\DIRECTORY_SEPARATOR.'key.pem'; $stream_context = [ 'cafile' => $cafile, @@ -60,8 +163,8 @@ public static function createFromEnv(PluginClientFactory $pluginClientFactory = 'local_pk' => $keyfile, ]; - if (\getenv('DOCKER_PEER_NAME')) { - $stream_context['peer_name'] = \getenv('DOCKER_PEER_NAME'); + if (getenv('DOCKER_PEER_NAME')) { + $stream_context['peer_name'] = getenv('DOCKER_PEER_NAME'); } $options['ssl'] = true; diff --git a/src/Endpoint/ContainerAttach.php b/src/Endpoint/ContainerAttach.php index a2d180e93..27f909fae 100644 --- a/src/Endpoint/ContainerAttach.php +++ b/src/Endpoint/ContainerAttach.php @@ -6,27 +6,38 @@ use Docker\API\Endpoint\ContainerAttach as BaseEndpoint; use Docker\Stream\DockerRawStream; -use Jane\OpenApiRuntime\Client\Client; -use Jane\OpenApiRuntime\Client\Exception\InvalidFetchModeException; use Psr\Http\Message\ResponseInterface; use Symfony\Component\Serializer\SerializerInterface; class ContainerAttach extends BaseEndpoint { - public function parsePSR7Response(ResponseInterface $response, SerializerInterface $serializer, string $fetchMode = Client::FETCH_OBJECT) + /** @var callable|null Resolves the container's TTY setting for ambiguous raw-stream responses. */ + private $ttyResolver; + + public function __construct(string $id, array $queryParameters = [], array $accept = [], ?callable $ttyResolver = null) + { + parent::__construct($id, $queryParameters, $accept); + $this->ttyResolver = $ttyResolver; + } + + protected function transformResponseBody(ResponseInterface $response, SerializerInterface $serializer, ?string $contentType = null) { - if (Client::FETCH_OBJECT === $fetchMode) { - if (200 === $response->getStatusCode() && DockerRawStream::HEADER === $response->getHeaderLine('Content-Type')) { + // 101 is an upgraded connection; its body is the same output stream. + if (200 === $response->getStatusCode() || 101 === $response->getStatusCode()) { + $mediaType = strtolower(trim(explode(';', $contentType ?? '')[0])); + if (DockerRawStream::MULTIPLEXED_HEADER === $mediaType) { return new DockerRawStream($response->getBody()); } + if (DockerRawStream::HEADER === $mediaType) { + // Docker uses this header for TTY output and for framed non-TTY + // output on plain responses. Keep the historical framed behavior + // when used without a resolver. + $multiplexed = null === $this->ttyResolver || !($this->ttyResolver)(); - return $this->transformResponseBody((string) $response->getBody(), $response->getStatusCode(), $serializer); - } - - if (Client::FETCH_RESPONSE === $fetchMode) { - return $response; + return new DockerRawStream($response->getBody(), $multiplexed); + } } - throw new InvalidFetchModeException(\sprintf('Fetch mode %s is not supported', $fetchMode)); + return parent::transformResponseBody($response, $serializer, $contentType); } } diff --git a/src/Endpoint/ContainerAttachWebsocket.php b/src/Endpoint/ContainerAttachWebsocket.php index fefb3638a..721220c88 100644 --- a/src/Endpoint/ContainerAttachWebsocket.php +++ b/src/Endpoint/ContainerAttachWebsocket.php @@ -6,8 +6,6 @@ use Docker\API\Endpoint\ContainerAttachWebsocket as BaseEndpoint; use Docker\Stream\AttachWebsocketStream; -use Jane\OpenApiRuntime\Client\Client; -use Jane\OpenApiRuntime\Client\Exception\InvalidFetchModeException; use Psr\Http\Message\ResponseInterface; use Symfony\Component\Serializer\SerializerInterface; @@ -15,30 +13,26 @@ class ContainerAttachWebsocket extends BaseEndpoint { public function getExtraHeaders(): array { - return \array_merge(parent::getExtraHeaders(), [ - 'Host' => 'localhost', - 'Origin' => 'php://docker-php', - 'Upgrade' => 'websocket', - 'Connection' => 'Upgrade', - 'Sec-WebSocket-Version' => '13', - 'Sec-WebSocket-Key' => \base64_encode(\uniqid()), - ]); + return array_merge( + parent::getExtraHeaders(), + [ + 'Host' => 'localhost', + 'Origin' => 'php://docker-php', + 'Upgrade' => 'websocket', + 'Connection' => 'Upgrade', + 'Sec-WebSocket-Version' => '13', + // RFC 6455 requires 16 random bytes. + 'Sec-WebSocket-Key' => base64_encode(random_bytes(16)), + ] + ); } - public function parsePSR7Response(ResponseInterface $response, SerializerInterface $serializer, string $fetchMode = Client::FETCH_OBJECT) + protected function transformResponseBody(ResponseInterface $response, SerializerInterface $serializer, ?string $contentType = null) { - if (Client::FETCH_OBJECT === $fetchMode) { - if (101 === $response->getStatusCode()) { - return new AttachWebsocketStream($response->getBody()); - } - - return $this->transformResponseBody((string) $response->getBody(), $response->getStatusCode(), $serializer); - } - - if (Client::FETCH_RESPONSE === $fetchMode) { - return $response; + if (101 === $response->getStatusCode() && 'websocket' === strtolower(trim($response->getHeaderLine('Upgrade')))) { + return new AttachWebsocketStream($response->getBody()); } - throw new InvalidFetchModeException(\sprintf('Fetch mode %s is not supported', $fetchMode)); + return parent::transformResponseBody($response, $serializer, $contentType); } } diff --git a/src/Endpoint/ContainerLogs.php b/src/Endpoint/ContainerLogs.php index 42335752f..4bc6afd23 100644 --- a/src/Endpoint/ContainerLogs.php +++ b/src/Endpoint/ContainerLogs.php @@ -6,27 +6,36 @@ use Docker\API\Endpoint\ContainerLogs as BaseEndpoint; use Docker\Stream\DockerRawStream; -use Jane\OpenApiRuntime\Client\Client; -use Jane\OpenApiRuntime\Client\Exception\InvalidFetchModeException; use Psr\Http\Message\ResponseInterface; use Symfony\Component\Serializer\SerializerInterface; class ContainerLogs extends BaseEndpoint { - public function parsePSR7Response(ResponseInterface $response, SerializerInterface $serializer, string $fetchMode = Client::FETCH_OBJECT) + /** @var callable|null Resolves the container's TTY setting for ambiguous raw-stream responses. */ + private $ttyResolver; + + public function __construct(string $id, array $queryParameters = [], array $accept = [], ?callable $ttyResolver = null) + { + parent::__construct($id, $queryParameters, $accept); + $this->ttyResolver = $ttyResolver; + } + + protected function transformResponseBody(ResponseInterface $response, SerializerInterface $serializer, ?string $contentType = null) { - if (Client::FETCH_OBJECT === $fetchMode) { - if (200 === $response->getStatusCode()) { + if (200 === $response->getStatusCode()) { + $mediaType = strtolower(trim(explode(';', $contentType ?? '')[0])); + if (DockerRawStream::MULTIPLEXED_HEADER === $mediaType) { return new DockerRawStream($response->getBody()); } + if (DockerRawStream::HEADER === $mediaType) { + // Before API 1.42, this header also identifies framed non-TTY logs. + // Keep the historical framed behavior when used without a resolver. + $multiplexed = null === $this->ttyResolver || !($this->ttyResolver)(); - return $this->transformResponseBody((string) $response->getBody(), $response->getStatusCode(), $serializer); - } - - if (Client::FETCH_RESPONSE === $fetchMode) { - return $response; + return new DockerRawStream($response->getBody(), $multiplexed); + } } - throw new InvalidFetchModeException(\sprintf('Fetch mode %s is not supported', $fetchMode)); + return parent::transformResponseBody($response, $serializer, $contentType); } } diff --git a/src/Endpoint/ContainerStats.php b/src/Endpoint/ContainerStats.php new file mode 100644 index 000000000..670035042 --- /dev/null +++ b/src/Endpoint/ContainerStats.php @@ -0,0 +1,24 @@ +getStatusCode() && $this->getQueryOptionsResolver()->resolve($this->queryParameters)['stream']) { + return new StatsStream($response->getBody(), $serializer); + } + + return parent::transformResponseBody($response, $serializer, $contentType); + } +} diff --git a/src/Endpoint/ExecStart.php b/src/Endpoint/ExecStart.php index 48ddd5c8d..5a2c073c6 100644 --- a/src/Endpoint/ExecStart.php +++ b/src/Endpoint/ExecStart.php @@ -5,28 +5,28 @@ namespace Docker\Endpoint; use Docker\API\Endpoint\ExecStart as BaseEndpoint; +use Docker\API\Model\ExecIdStartPostBody; use Docker\Stream\DockerRawStream; -use Jane\OpenApiRuntime\Client\Client; -use Jane\OpenApiRuntime\Client\Exception\InvalidFetchModeException; use Psr\Http\Message\ResponseInterface; use Symfony\Component\Serializer\SerializerInterface; class ExecStart extends BaseEndpoint { - public function parsePSR7Response(ResponseInterface $response, SerializerInterface $serializer, string $fetchMode = Client::FETCH_OBJECT) + protected function transformResponseBody(ResponseInterface $response, SerializerInterface $serializer, ?string $contentType = null) { - if (Client::FETCH_OBJECT === $fetchMode) { - if (200 === $response->getStatusCode() && DockerRawStream::HEADER === $response->getHeaderLine('Content-Type')) { + if (200 === $response->getStatusCode() || 101 === $response->getStatusCode()) { + $mediaType = strtolower(trim(explode(';', $contentType ?? '')[0])); + if (DockerRawStream::MULTIPLEXED_HEADER === $mediaType) { return new DockerRawStream($response->getBody()); } + if (DockerRawStream::HEADER === $mediaType) { + // Non-upgraded and older API responses use this header for both modes. + $tty = $this->body instanceof ExecIdStartPostBody && $this->body->getTty(); - return $this->transformResponseBody((string) $response->getBody(), $response->getStatusCode(), $serializer); - } - - if (Client::FETCH_RESPONSE === $fetchMode) { - return $response; + return new DockerRawStream($response->getBody(), !$tty); + } } - throw new InvalidFetchModeException(\sprintf('Fetch mode %s is not supported', $fetchMode)); + return parent::transformResponseBody($response, $serializer, $contentType); } } diff --git a/src/Endpoint/ImageBuild.php b/src/Endpoint/ImageBuild.php index 65d3353fc..095f14772 100644 --- a/src/Endpoint/ImageBuild.php +++ b/src/Endpoint/ImageBuild.php @@ -7,38 +7,46 @@ use Docker\API\Endpoint\ImageBuild as BaseEndpoint; use Docker\Stream\BuildStream; use Docker\Stream\TarStream; -use Jane\OpenApiRuntime\Client\Client; -use Jane\OpenApiRuntime\Client\Exception\InvalidFetchModeException; +use Nyholm\Psr7\Stream; use Psr\Http\Message\ResponseInterface; +use Symfony\Component\OptionsResolver\Options; +use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Serializer\SerializerInterface; class ImageBuild extends BaseEndpoint { - public function getBody(\Symfony\Component\Serializer\SerializerInterface $serializer, \Http\Message\StreamFactory $streamFactory = null): array + public function getBody(SerializerInterface $serializer, $streamFactory = null): array { $body = $this->body; if (\is_resource($body)) { - $body = new TarStream($body); + $body = new TarStream(Stream::create($body)); } - return [[], $body]; + return [['Content-Type' => ['application/octet-stream']], $body]; } - public function parsePSR7Response(ResponseInterface $response, SerializerInterface $serializer, string $fetchMode = Client::FETCH_OBJECT) + protected function getQueryOptionsResolver(): OptionsResolver { - if (Client::FETCH_OBJECT === $fetchMode) { - if (200 === $response->getStatusCode()) { - return new BuildStream($response->getBody(), $serializer); - } + $optionsResolver = parent::getQueryOptionsResolver(); + // Docker applies each repeated `t` parameter as a separate tag. + $optionsResolver->setAllowedTypes('t', ['string', 'string[]']); + $optionsResolver->setNormalizer('t', static fn (Options $options, $value) => \is_array($value) ? array_values($value) : $value); - return $this->transformResponseBody((string) $response->getBody(), $response->getStatusCode(), $serializer); - } + return $optionsResolver; + } + + protected function getQueryStyles(): array + { + return ['t' => ['style' => 'form', 'explode' => true]] + parent::getQueryStyles(); + } - if (Client::FETCH_RESPONSE === $fetchMode) { - return $response; + protected function transformResponseBody(ResponseInterface $response, SerializerInterface $serializer, ?string $contentType = null) + { + if (200 === $response->getStatusCode()) { + return new BuildStream($response->getBody(), $serializer); } - throw new InvalidFetchModeException(\sprintf('Fetch mode %s is not supported', $fetchMode)); + return parent::transformResponseBody($response, $serializer, $contentType); } } diff --git a/src/Endpoint/ImageCreate.php b/src/Endpoint/ImageCreate.php index 196ba3e5e..3a50da2e9 100644 --- a/src/Endpoint/ImageCreate.php +++ b/src/Endpoint/ImageCreate.php @@ -6,27 +6,17 @@ use Docker\API\Endpoint\ImageCreate as BaseEndpoint; use Docker\Stream\CreateImageStream; -use Jane\OpenApiRuntime\Client\Client; -use Jane\OpenApiRuntime\Client\Exception\InvalidFetchModeException; use Psr\Http\Message\ResponseInterface; use Symfony\Component\Serializer\SerializerInterface; class ImageCreate extends BaseEndpoint { - public function parsePSR7Response(ResponseInterface $response, SerializerInterface $serializer, string $fetchMode = Client::FETCH_OBJECT) + protected function transformResponseBody(ResponseInterface $response, SerializerInterface $serializer, ?string $contentType = null) { - if (Client::FETCH_OBJECT === $fetchMode) { - if (200 === $response->getStatusCode()) { - return new CreateImageStream($response->getBody(), $serializer); - } - - return $this->transformResponseBody((string) $response->getBody(), $response->getStatusCode(), $serializer); - } - - if (Client::FETCH_RESPONSE === $fetchMode) { - return $response; + if (200 === $response->getStatusCode()) { + return new CreateImageStream($response->getBody(), $serializer); } - throw new InvalidFetchModeException(\sprintf('Fetch mode %s is not supported', $fetchMode)); + return parent::transformResponseBody($response, $serializer, $contentType); } } diff --git a/src/Endpoint/ImagePush.php b/src/Endpoint/ImagePush.php index 3d2eabcca..61e165915 100644 --- a/src/Endpoint/ImagePush.php +++ b/src/Endpoint/ImagePush.php @@ -6,8 +6,6 @@ use Docker\API\Endpoint\ImagePush as BaseEndpoint; use Docker\Stream\PushStream; -use Jane\OpenApiRuntime\Client\Client; -use Jane\OpenApiRuntime\Client\Exception\InvalidFetchModeException; use Psr\Http\Message\ResponseInterface; use Symfony\Component\Serializer\SerializerInterface; @@ -15,23 +13,15 @@ class ImagePush extends BaseEndpoint { public function getUri(): string { - return \str_replace(['{name}'], [\urlencode($this->name)], '/images/{name}/push'); + return str_replace(['{name}'], [urlencode($this->name)], '/images/{name}/push'); } - public function parsePSR7Response(ResponseInterface $response, SerializerInterface $serializer, string $fetchMode = Client::FETCH_OBJECT) + protected function transformResponseBody(ResponseInterface $response, SerializerInterface $serializer, ?string $contentType = null) { - if (Client::FETCH_OBJECT === $fetchMode) { - if (200 === $response->getStatusCode()) { - return new PushStream($response->getBody(), $serializer); - } - - return $this->transformResponseBody((string) $response->getBody(), $response->getStatusCode(), $serializer); - } - - if (Client::FETCH_RESPONSE === $fetchMode) { - return $response; + if (200 === $response->getStatusCode()) { + return new PushStream($response->getBody(), $serializer); } - throw new InvalidFetchModeException(\sprintf('Fetch mode %s is not supported', $fetchMode)); + return parent::transformResponseBody($response, $serializer, $contentType); } } diff --git a/src/Endpoint/InteractiveExecStart.php b/src/Endpoint/InteractiveExecStart.php new file mode 100644 index 000000000..55075ff29 --- /dev/null +++ b/src/Endpoint/InteractiveExecStart.php @@ -0,0 +1,19 @@ + ['Upgrade'], + 'Upgrade' => ['tcp'], + ]; + } +} diff --git a/src/Endpoint/SystemEvents.php b/src/Endpoint/SystemEvents.php index 712e67da5..808e4f02d 100644 --- a/src/Endpoint/SystemEvents.php +++ b/src/Endpoint/SystemEvents.php @@ -4,40 +4,31 @@ namespace Docker\Endpoint; -use Amp\Artax\Client as ArtaxClient; use Docker\API\Endpoint\SystemEvents as BaseEndpoint; -use Docker\Client\AmpArtaxStreamEndpoint; -use Docker\Client\AmpArtaxStreamEndpointTrait; -use Docker\Client\ProvideAmpArtaxClientOptions; use Docker\Stream\EventStream; -use Jane\OpenApiRuntime\Client\Client; -use Jane\OpenApiRuntime\Client\Exception\InvalidFetchModeException; use Psr\Http\Message\ResponseInterface; use Symfony\Component\Serializer\SerializerInterface; -class SystemEvents extends BaseEndpoint implements ProvideAmpArtaxClientOptions, AmpArtaxStreamEndpoint +class SystemEvents extends BaseEndpoint { - use AmpArtaxStreamEndpointTrait; - - public function getAmpArtaxClientOptions(): array + /** + * @param array $accept Accept header values; API 1.52 added this parameter + */ + public function __construct(array $queryParameters = [], array $accept = []) { - return [ArtaxClient::OP_TRANSFER_TIMEOUT => 0]; + parent::__construct($queryParameters); + // From API 1.52 the generated endpoint stores the Accept values here. + if (property_exists($this, 'accept')) { + $this->accept = $accept; + } } - public function parsePSR7Response(ResponseInterface $response, SerializerInterface $serializer, string $fetchMode = Client::FETCH_OBJECT) + protected function transformResponseBody(ResponseInterface $response, SerializerInterface $serializer, ?string $contentType = null) { - if (Client::FETCH_OBJECT === $fetchMode) { - if (200 === $response->getStatusCode()) { - return new EventStream($response->getBody(), $serializer); - } - - return $this->transformResponseBody((string) $response->getBody(), $response->getStatusCode(), $serializer); - } - - if (Client::FETCH_RESPONSE === $fetchMode) { - return $response; + if (200 === $response->getStatusCode()) { + return new EventStream($response->getBody(), $serializer); } - throw new InvalidFetchModeException(\sprintf('Fetch mode %s is not supported', $fetchMode)); + return parent::transformResponseBody($response, $serializer, $contentType); } } diff --git a/src/Exception/BadRequestException.php b/src/Exception/BadRequestException.php new file mode 100644 index 000000000..ee0353ac0 --- /dev/null +++ b/src/Exception/BadRequestException.php @@ -0,0 +1,20 @@ +response; + } +} diff --git a/src/Exception/InteractiveExecTimeoutException.php b/src/Exception/InteractiveExecTimeoutException.php new file mode 100644 index 000000000..d433bff98 --- /dev/null +++ b/src/Exception/InteractiveExecTimeoutException.php @@ -0,0 +1,9 @@ +getStatusCode(); + parent::__construct( + \sprintf('Docker returned HTTP %d for %s %s: %s', $status, $method, $path, $errorMessage), + $status + ); + } + + /** + * Create the client or server error exception for an unhandled response. + * + * The response body must be seekable; it is rewound after reading Docker's + * error message. + */ + public static function fromResponse(string $method, string $path, ResponseInterface $response): self + { + $body = $response->getBody(); + $body->rewind(); + $raw = $body->getContents(); + $body->rewind(); + + $decoded = json_decode($raw, true); + $message = \is_array($decoded) && \is_string($decoded['message'] ?? null) ? $decoded['message'] : trim($raw); + if ('' === $message) { + $message = $response->getReasonPhrase() ?: 'no error message'; + } + if (\strlen($message) > 500) { + $message = substr($message, 0, 500).'...'; + } + + return $response->getStatusCode() >= 500 + ? new UnexpectedServerErrorException($method, $path, $message, $response) + : new UnexpectedClientErrorException($method, $path, $message, $response); + } + + public function getStatusCode(): int + { + return $this->response->getStatusCode(); + } + + /** Docker's error message, or the response body when it is not JSON. */ + public function getErrorMessage(): string + { + return $this->errorMessage; + } + + public function getMethod(): string + { + return $this->method; + } + + /** Request path, without the API version prefix or query string. */ + public function getPath(): string + { + return $this->path; + } + + public function getResponse(): ResponseInterface + { + return $this->response; + } +} diff --git a/src/Http/ApiVersionNegotiationPlugin.php b/src/Http/ApiVersionNegotiationPlugin.php new file mode 100644 index 000000000..fd3280446 --- /dev/null +++ b/src/Http/ApiVersionNegotiationPlugin.php @@ -0,0 +1,60 @@ +version; + } + + public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise + { + $version = $this->version ?? $this->negotiate($next); + + return (new AddPathPlugin($this->uriFactory->createUri('/v'.$version)))->handleRequest($request, $next, $first); + } + + private function negotiate(callable $next): string + { + // A connection error propagates, so an unreachable daemon is not tried + // twice. An error response without the header keeps the client version. + $response = $next($this->requestFactory->createRequest('GET', '/_ping'))->wait(); + $daemonVersion = trim($response->getHeaderLine('API-Version')); + $response->getBody()->close(); + + if (!preg_match('/^[0-9]+\.[0-9]+$/D', $daemonVersion)) { + return $this->version = $this->clientVersion; + } + + return $this->version = version_compare($daemonVersion, $this->clientVersion, '<') ? $daemonVersion : $this->clientVersion; + } +} diff --git a/src/Http/InteractiveHttpClient.php b/src/Http/InteractiveHttpClient.php new file mode 100644 index 000000000..63a00e471 --- /dev/null +++ b/src/Http/InteractiveHttpClient.php @@ -0,0 +1,27 @@ +client->sendRequest($request); + } +} diff --git a/src/Http/StreamingDecoderPlugin.php b/src/Http/StreamingDecoderPlugin.php new file mode 100644 index 000000000..85ef5ab80 --- /dev/null +++ b/src/Http/StreamingDecoderPlugin.php @@ -0,0 +1,40 @@ +decoder = new DecoderPlugin($config); + } + + public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise + { + return $this->decoder->handleRequest($request, static function (RequestInterface $request) use ($next): Promise { + return $next($request)->then(static function (ResponseInterface $response): ResponseInterface { + if ($response->getBody() instanceof SocketStream) { + $response = $response->withBody(new SocketReadStream($response->getBody())); + } + if ('chunked' === strtolower(trim($response->getHeaderLine('Transfer-Encoding')))) { + return $response->withBody(new DechunkStream($response->getBody()))->withoutHeader('Transfer-Encoding'); + } + + return $response; + }); + }, $first); + } +} diff --git a/src/Serializer/LargeIntegerJsonDecode.php b/src/Serializer/LargeIntegerJsonDecode.php new file mode 100644 index 000000000..1a542b069 --- /dev/null +++ b/src/Serializer/LargeIntegerJsonDecode.php @@ -0,0 +1,43 @@ += (float) \PHP_INT_MAX ? \PHP_INT_MAX : $value; + } + if (\is_array($value)) { + foreach ($value as $key => $item) { + $value[$key] = self::clamp($item); + } + } elseif ($value instanceof \stdClass) { + foreach (get_object_vars($value) as $key => $item) { + $value->{$key} = self::clamp($item); + } + } + + return $value; + } +} diff --git a/src/Stream/ArtaxCallbackStream.php b/src/Stream/ArtaxCallbackStream.php deleted file mode 100644 index f85d5219e..000000000 --- a/src/Stream/ArtaxCallbackStream.php +++ /dev/null @@ -1,78 +0,0 @@ -stream = $stream; - $this->cancellationTokenSource = $cancellationTokenSource; - $this->chunkTransformer = $chunkTransformer; - } - - /** - * Called when there is a new frame from the stream. - * - * @param callable $onNewFrame - */ - public function onFrame(callable $onNewFrame): void - { - $this->onNewFrameCallables[] = $onNewFrame; - } - - /** - * Consume stream chunks. - * - * @return Promise - */ - public function listen(): Promise - { - return call(function () { - while (null !== ($chunk = yield $this->stream->read())) { - foreach ($this->onNewFrameCallables as $newFrameCallable) { - $newFrameCallable($this->transformChunk($chunk)); - } - } - }); - } - - /** - * Stop consuming stream chunks. - */ - public function cancel(): void - { - $this->cancellationTokenSource->cancel(); - } - - /** - * Transform stream chunks if required. - * - * @param string $chunk - * - * @return mixed The raw chunk or the transformed chunk - */ - private function transformChunk(string $chunk) - { - if (null === $this->chunkTransformer) { - return $chunk; - } - - return \call_user_func($this->chunkTransformer, $chunk); - } -} diff --git a/src/Stream/AttachWebsocketStream.php b/src/Stream/AttachWebsocketStream.php index 402e417ca..34bb75564 100644 --- a/src/Stream/AttachWebsocketStream.php +++ b/src/Stream/AttachWebsocketStream.php @@ -15,6 +15,11 @@ */ class AttachWebsocketStream { + private const OPCODE_BINARY = 0x2; + private const OPCODE_CLOSE = 0x8; + private const OPCODE_PING = 0x9; + private const OPCODE_PONG = 0xA; + /** @var resource The underlying socket */ private $socket; @@ -24,157 +29,203 @@ public function __construct(StreamInterface $stream) } /** - * Send input to the container. + * Send input to the container as one binary frame. * * @param string $data Data to send */ public function write($data): void { - $rand = \random_int(0, 28); - $frame = [ - 'fin' => 1, - 'rsv1' => 0, - 'rsv2' => 0, - 'rsv3' => 0, - 'opcode' => 1, // We always send text - 'mask' => 1, - 'len' => \strlen($data), - 'mask_key' => \substr(\md5(\uniqid()), $rand, 4), - 'data' => $data, - ]; - - if (1 === $frame['mask']) { - for ($i = 0; $i < $frame['len']; ++$i) { - $frame['data'][$i] - = \chr(\ord($frame['data'][$i]) ^ \ord($frame['mask_key'][$i % 4])); - } - } - - if ($frame['len'] > 2 ** 16) { - $len = 127; - } elseif ($frame['len'] > 125) { - $len = 126; - } else { - $len = $frame['len']; + if (!\is_resource($this->socket)) { + throw new \RuntimeException('The WebSocket stream is closed.'); } - $firstByte = ($frame['fin'] << 7) | (($frame['rsv1'] << 7) >> 1) | (($frame['rsv2'] << 7) >> 2) | (($frame['rsv3'] << 7) >> 3) | (($frame['opcode'] << 4) >> 4); - $secondByte = ($frame['mask'] << 7) | (($len << 1) >> 1); - - $this->socketWrite(\chr($firstByte)); - $this->socketWrite(\chr($secondByte)); + $this->sendFrame(self::OPCODE_BINARY, (string) $data); + } - if (126 === $len) { - $this->socketWrite(\pack('n', $frame['len'])); - } elseif (127 === $len) { - $higher = $frame['len'] >> 32; - $lower = ($frame['len'] << 32) >> 32; - $this->socketWrite(\pack('N', $higher)); - $this->socketWrite(\pack('N', $lower)); + /** + * Send a close frame and close the connection. + * + * Later read() calls return null. Calling close() again does nothing. + */ + public function close(): void + { + if (!\is_resource($this->socket)) { + return; } - if (1 === $frame['mask']) { - $this->socketWrite($frame['mask_key']); + try { + // A close frame without a status code (RFC 6455 section 5.5.1). The + // daemon may already have closed its side, so a failed write is ignored. + $this->sendFrame(self::OPCODE_CLOSE, ''); + } catch (\RuntimeException) { } - - $this->socketWrite($frame['data']); + fclose($this->socket); } /** - * Block until it receive a frame from websocket or return null if no more connexion. + * Wait for the next data frame. + * + * Ping frames are answered with a pong and a close frame closes the stream; + * neither is returned. Docker sends output as it is written, so a frame is a + * chunk of output rather than a line or a whole message. * * @param int $waitTime Time to wait in seconds before return false * @param int $waitMicroTime Time to wait in microseconds before return false * @param bool $getFrame Whether to return the frame of websocket or only the data * - * @return null|false|string|array Null for socket not available, false for no message, string for the last message and the frame array if $getFrame is set to true + * @return false|string|array|null Null once the stream is closed, false if no frame arrived in time, the frame data, or the frame array if $getFrame is set to true */ public function read($waitTime = 0, $waitMicroTime = 200000, $getFrame = false) { - if (!\is_resource($this->socket) || \feof($this->socket)) { - return null; - } + while (true) { + if (!\is_resource($this->socket) || feof($this->socket)) { + return null; + } + + $read = [$this->socket]; + $write = null; + $expect = null; + $selected = @stream_select($read, $write, $expect, $waitTime, $waitMicroTime); + if (false === $selected) { + throw new \RuntimeException('Cannot wait for the WebSocket stream.'); + } + if (0 === $selected) { + return false; + } + + $frame = $this->readFrame(); + if (null === $frame) { + // The daemon closed the connection before sending a whole frame. + fclose($this->socket); + + return null; + } - $read = [$this->socket]; - $write = null; - $expect = null; + if (self::OPCODE_CLOSE === $frame['opcode']) { + $this->close(); - if (0 === \stream_select($read, $write, $expect, $waitTime, $waitMicroTime)) { - return false; + return null; + } + if (self::OPCODE_PING === $frame['opcode']) { + $this->sendFrame(self::OPCODE_PONG, $frame['data']); + continue; + } + if (self::OPCODE_PONG === $frame['opcode']) { + continue; + } + + return $getFrame ? $frame : $frame['data']; } + } - $firstByte = $this->socketRead(1); - $frame = []; - $firstByte = \ord($firstByte); - $secondByte = \ord($this->socketRead(1)); - - // First byte decoding - $frame['fin'] = ($firstByte & 128) >> 7; - $frame['rsv1'] = ($firstByte & 64) >> 6; - $frame['rsv2'] = ($firstByte & 32) >> 5; - $frame['rsv3'] = ($firstByte & 16) >> 4; - $frame['opcode'] = ($firstByte & 15); - - // Second byte decoding - $frame['mask'] = ($secondByte & 128) >> 7; - $frame['len'] = ($secondByte & 127); - - // Get length of the frame - if (126 === $frame['len']) { - $frame['len'] = \unpack('n', $this->socketRead(2))[1]; - } elseif (127 === $frame['len']) { - list($higher, $lower) = \array_values(\unpack('N2', $this->socketRead(8))); - $frame['len'] = ($higher << 32) | $lower; + /** + * Read one frame, or return null when the connection ends first. + */ + private function readFrame(): ?array + { + $header = $this->socketRead(2); + if (2 !== \strlen($header)) { + return null; + } + $firstByte = \ord($header[0]); + $secondByte = \ord($header[1]); + + $frame = [ + 'fin' => ($firstByte & 128) >> 7, + 'rsv1' => ($firstByte & 64) >> 6, + 'rsv2' => ($firstByte & 32) >> 5, + 'rsv3' => ($firstByte & 16) >> 4, + 'opcode' => $firstByte & 15, + 'mask' => ($secondByte & 128) >> 7, + 'len' => $secondByte & 127, + ]; + + if (126 === $frame['len'] || 127 === $frame['len']) { + $size = 126 === $frame['len'] ? 2 : 8; + $length = $this->socketRead($size); + if ($size !== \strlen($length)) { + return null; + } + $frame['len'] = unpack(2 === $size ? 'n' : 'J', $length)[1]; } - // Get the mask key if needed if (1 === $frame['mask']) { $frame['mask_key'] = $this->socketRead(4); + if (4 !== \strlen($frame['mask_key'])) { + return null; + } } $frame['data'] = $this->socketRead($frame['len']); + if ($frame['len'] !== \strlen($frame['data'])) { + return null; + } - // Decode data if needed if (1 === $frame['mask']) { - for ($i = 0; $i < $frame['len']; ++$i) { - $frame['data'][$i] = \chr(\ord($frame['data'][$i]) ^ \ord($frame['mask_key'][$i % 4])); - } + $frame['data'] = $this->mask($frame['data'], $frame['mask_key']); + } + + return $frame; + } + + /** + * Send one masked frame, as clients must (RFC 6455 section 5.3). + */ + private function sendFrame(int $opcode, string $data): void + { + $length = \strlen($data); + // 126 carries a 16-bit length, so anything above 0xFFFF needs the 64-bit form. + if ($length > 0xFFFF) { + $header = \chr(0x80 | 127).pack('J', $length); + } elseif ($length > 125) { + $header = \chr(0x80 | 126).pack('n', $length); + } else { + $header = \chr(0x80 | $length); } + $maskKey = random_bytes(4); - if ($getFrame) { - return $frame; + $this->socketWrite(\chr(0x80 | $opcode).$header.$maskKey.$this->mask($data, $maskKey)); + } + + private function mask(string $data, string $maskKey): string + { + if ('' === $data) { + return ''; } - return (string) $frame['data']; + return $data ^ str_repeat($maskKey, intdiv(\strlen($data), 4) + 1); } /** - * Force to have something of the expected size (block). - * - * @param $length - * - * @return string + * Read exactly $length bytes, or fewer if the connection ends first. */ - private function socketRead($length) + private function socketRead(int $length): string { $read = ''; - - do { - $read .= \fread($this->socket, $length - \strlen($read)); - } while (\strlen($read) < $length && !\feof($this->socket)); + // Empty frames carry no payload; fread() rejects a zero length. + while (\strlen($read) < $length && !feof($this->socket)) { + $chunk = @fread($this->socket, $length - \strlen($read)); + // A stalled read returns false or '' depending on the PHP version. + if (stream_get_meta_data($this->socket)['timed_out']) { + throw new \RuntimeException('Timed out reading a WebSocket frame.'); + } + if (false === $chunk) { + throw new \RuntimeException('Cannot read from the WebSocket stream.'); + } + $read .= $chunk; + } return $read; } - /** - * Write to the socket. - * - * @param $data - * - * @return int - */ - private function socketWrite($data) + private function socketWrite(string $data): void { - return \fwrite($this->socket, $data); + while ('' !== $data) { + $written = @fwrite($this->socket, $data); + if (false === $written || 0 === $written) { + throw new \RuntimeException('Cannot write to the WebSocket stream.'); + } + $data = (string) substr($data, $written); + } } } diff --git a/src/Stream/BuildStream.php b/src/Stream/BuildStream.php index b6ba9e705..34f32ac41 100644 --- a/src/Stream/BuildStream.php +++ b/src/Stream/BuildStream.php @@ -12,7 +12,7 @@ class BuildStream extends MultiJsonStream { /** - * [@inheritdoc}. + * {@inheritdoc}. */ protected function getDecodeClass() { diff --git a/src/Stream/CallbackStream.php b/src/Stream/CallbackStream.php index 62b746130..320b63359 100644 --- a/src/Stream/CallbackStream.php +++ b/src/Stream/CallbackStream.php @@ -12,6 +12,8 @@ abstract class CallbackStream private $onNewFrameCallables = []; + private bool $stopped = false; + public function __construct(StreamInterface $stream) { $this->stream = $stream; @@ -19,8 +21,6 @@ public function __construct(StreamInterface $stream) /** * Called when there is a new frame from the stream. - * - * @param callable $onNewFrame */ public function onFrame(callable $onNewFrame): void { @@ -29,8 +29,6 @@ public function onFrame(callable $onNewFrame): void /** * Read a frame in the stream. - * - * @return mixed */ abstract protected function readFrame(); @@ -39,7 +37,7 @@ abstract protected function readFrame(); */ public function wait(): void { - while (!$this->stream->eof()) { + while (!$this->stopped && !$this->stream->eof()) { $frame = $this->readFrame(); if (null !== $frame) { @@ -54,6 +52,23 @@ public function wait(): void } } + /** + * Stop reading and close the response body. + * + * Called from a frame callback, wait() returns once the remaining callbacks + * for that frame have run. Closing a build or pull connection can cancel + * the daemon operation. + */ + public function stop(): void + { + if ($this->stopped) { + return; + } + + $this->stopped = true; + $this->stream->close(); + } + public function closeAndRead(): void { $this->stream->close(); diff --git a/src/Stream/CreateImageStream.php b/src/Stream/CreateImageStream.php index f6cb92ca9..8d5aea7c6 100644 --- a/src/Stream/CreateImageStream.php +++ b/src/Stream/CreateImageStream.php @@ -12,7 +12,7 @@ class CreateImageStream extends MultiJsonStream { /** - * [@inheritdoc}. + * {@inheritdoc}. */ protected function getDecodeClass() { diff --git a/src/Stream/DechunkStream.php b/src/Stream/DechunkStream.php new file mode 100644 index 000000000..b6705e47d --- /dev/null +++ b/src/Stream/DechunkStream.php @@ -0,0 +1,30 @@ +buffer && !$this->stream->eof()) { + $this->fill(); + } + + $output = substr($this->buffer, 0, $length); + $this->buffer = substr($this->buffer, \strlen($output)); + + return $output; + } +} diff --git a/src/Stream/DockerRawStream.php b/src/Stream/DockerRawStream.php index 5f71d629c..ac8f57fcd 100644 --- a/src/Stream/DockerRawStream.php +++ b/src/Stream/DockerRawStream.php @@ -9,10 +9,13 @@ class DockerRawStream { public const HEADER = 'application/vnd.docker.raw-stream'; + public const MULTIPLEXED_HEADER = 'application/vnd.docker.multiplexed-stream'; /** @var StreamInterface Stream for the response */ protected $stream; + private bool $multiplexed; + /** @var callable[] A list of callable to call when there is a stdin output */ protected $onStdinCallables = []; @@ -22,15 +25,14 @@ class DockerRawStream /** @var callable[] A list of callable to call when there is a stderr output */ protected $onStderrCallables = []; - public function __construct(StreamInterface $stream) + public function __construct(StreamInterface $stream, bool $multiplexed = true) { $this->stream = $stream; + $this->multiplexed = $multiplexed; } /** * Add a callable to read stdin. - * - * @param callable $callback */ public function onStdin(callable $callback): void { @@ -39,8 +41,6 @@ public function onStdin(callable $callback): void /** * Add a callable to read stdout. - * - * @param callable $callback */ public function onStdout(callable $callback): void { @@ -49,8 +49,6 @@ public function onStdout(callable $callback): void /** * Add a callable to read stderr. - * - * @param callable $callback */ public function onStderr(callable $callback): void { @@ -62,13 +60,24 @@ public function onStderr(callable $callback): void */ protected function readFrame(): void { + if (!$this->multiplexed) { + $output = $this->stream->read(8192); + if ('' !== $output) { + foreach ($this->onStdoutCallables as $callback) { + $callback($output); + } + } + + return; + } + $header = $this->forceRead(8); if (\strlen($header) < 8) { return; } - $decoded = \unpack('C1type/C3/N1size', $header); + $decoded = unpack('C1type/C3/N1size', $header); $output = $this->forceRead($decoded['size']); $callbackList = []; @@ -92,12 +101,14 @@ protected function readFrame(): void /** * Force to have something of the expected size (block). * - * @param $length - * * @return string */ private function forceRead($length) { + if (0 === $length) { + return ''; + } + $read = ''; do { diff --git a/src/Stream/EventStream.php b/src/Stream/EventStream.php index 0ba9df6f7..1c18a8050 100644 --- a/src/Stream/EventStream.php +++ b/src/Stream/EventStream.php @@ -12,10 +12,10 @@ class EventStream extends MultiJsonStream { /** - * [@inheritdoc}. + * {@inheritdoc}. */ protected function getDecodeClass() { - return 'EventsGetResponse200'; + return 'EventMessage'; } } diff --git a/src/Stream/FrameError.php b/src/Stream/FrameError.php new file mode 100644 index 000000000..9b70b3dab --- /dev/null +++ b/src/Stream/FrameError.php @@ -0,0 +1,36 @@ +getErrorDetail()?->getMessage(); + if (\is_string($message) && '' !== $message) { + return $message; + } + } + if (method_exists($frame, 'getError')) { + $message = $frame->getError(); + if (\is_string($message) && '' !== $message) { + return $message; + } + } + + return null; + } +} diff --git a/src/Stream/InteractiveExecStream.php b/src/Stream/InteractiveExecStream.php new file mode 100644 index 000000000..d11d23186 --- /dev/null +++ b/src/Stream/InteractiveExecStream.php @@ -0,0 +1,255 @@ + 86400000)) { + throw new \InvalidArgumentException('Interactive exec timeout must be between 1 and 86400000 milliseconds.'); + } + if (!stream_set_blocking($socket, false)) { + throw new \RuntimeException('Cannot make the interactive exec socket nonblocking.'); + } + $this->socket = $socket; + $this->deadline = null === $timeoutMs ? null : hrtime(true) + $timeoutMs * 1000000; + } + + public function onStdout(callable $callback): void + { + $this->stdout[] = $callback; + } + + public function onStderr(callable $callback): void + { + $this->stderr[] = $callback; + } + + /** + * Attempt a bounded write. Retry the unsent suffix after polling. + * Returns zero on backpressure; it does not queue or retain stdin. + */ + public function writeStdin(string $data): int + { + $this->checkDeadline(); + $this->requireOpen(); + if ($this->stdinClosed) { + throw new \LogicException('Interactive exec stdin is closed.'); + } + if ('' === $data) { + return 0; + } + $written = @fwrite($this->socket, substr($data, 0, 16384)); + if (false === $written) { + $this->close(); + throw new \RuntimeException('Cannot write interactive exec stdin.'); + } + + return $written; + } + + /** Send EOF to stdin, while keeping stdout and stderr readable. */ + public function closeStdin(): void + { + $this->checkDeadline(); + $this->requireOpen(); + if (!$this->multiplexed) { + throw new \LogicException('TTY stdin cannot be half-closed safely; use terminal input or wait for the command to exit.'); + } + if (!$this->stdinClosed) { + if (!@stream_socket_shutdown($this->socket, \STREAM_SHUT_WR)) { + $this->close(); + throw new \RuntimeException('Cannot close interactive exec stdin.'); + } + $this->stdinClosed = true; + } + } + + /** + * Read at most 16 KiB, waiting at most timeoutMs for data. True means the + * session remains open (possibly idle); false means a clean output EOF. + * Callbacks receive chunks, not necessarily whole Docker frames or lines. + */ + public function poll(int $timeoutMs = 0): bool + { + if ($timeoutMs < 0 || $timeoutMs > 60000) { + throw new \InvalidArgumentException('Poll timeout must be between 0 and 60000 milliseconds.'); + } + if ($this->finished) { + return false; + } + $this->checkDeadline(); + $this->requireOpen(); + + try { + // Try the nonblocking read first: TLS and PHP may already have + // buffered bytes even when the underlying descriptor is not ready. + $data = @fread($this->socket, 16384); + if (false === $data) { + throw new \RuntimeException('Cannot read interactive exec output.'); + } + if ('' === $data && !feof($this->socket)) { + $waitNs = $timeoutMs * 1000000; + if (null !== $this->deadline) { + $waitNs = min($waitNs, max(0, $this->deadline - hrtime(true))); + } + $read = [$this->socket]; + $write = $except = []; + $selected = @stream_select($read, $write, $except, intdiv($waitNs, 1000000000), intdiv($waitNs % 1000000000, 1000)); + $this->checkDeadline(); + if (false === $selected) { + throw new \RuntimeException('Cannot poll interactive exec output.'); + } + if (0 === $selected) { + return true; + } + $data = @fread($this->socket, 16384); + if (false === $data) { + throw new \RuntimeException('Cannot read interactive exec output.'); + } + } + $this->checkDeadline(); + if ('' !== $data) { + $this->dispatch($data); + } + $this->requireOpen(); + if (feof($this->socket)) { + if ('' !== $this->header || $this->remaining > 0) { + throw new \RuntimeException('Docker closed an incomplete exec frame.'); + } + $this->finished = true; + $this->close(); + } + + return !$this->finished; + } catch (\Throwable $error) { + $this->close(); + throw $error; + } + } + + /** The tick runs even when the command produces no output. */ + public function wait(?callable $tick = null, int $pollIntervalMs = 100): void + { + try { + while (!$this->finished) { + if (null !== $tick) { + $tick(); + } + $this->poll($pollIntervalMs); + } + } catch (\Throwable $error) { + $this->close(); + throw $error; + } + } + + public function isFinished(): bool + { + return $this->finished; + } + + /** Cancel local I/O only; the in-container process may still be running. */ + public function close(): void + { + if (\is_resource($this->socket)) { + fclose($this->socket); + } + $this->socket = null; + $this->header = ''; + $this->stdout = $this->stderr = []; + } + + public function __destruct() + { + $this->close(); + } + + private function requireOpen(): void + { + if (!\is_resource($this->socket)) { + throw new \LogicException('Interactive exec session is closed.'); + } + } + + private function checkDeadline(): void + { + if (null !== $this->deadline && hrtime(true) >= $this->deadline) { + $this->close(); + throw new InteractiveExecTimeoutException('Interactive exec exceeded its streaming deadline.'); + } + } + + private function dispatch(string $data): void + { + if (!$this->multiplexed) { + foreach ($this->stdout as $callback) { + $callback($data); + } + + return; + } + $offset = 0; + $length = \strlen($data); + while ($offset < $length) { + if (0 === $this->remaining) { + $take = min(8 - \strlen($this->header), $length - $offset); + $this->header .= substr($data, $offset, $take); + $offset += $take; + if (8 !== \strlen($this->header)) { + return; + } + $frame = unpack('Cchannel/C3padding/Nsize', $this->header); + if ($frame['channel'] > 2 || "\0\0\0" !== substr($this->header, 1, 3)) { + throw new \RuntimeException('Docker returned an invalid exec frame.'); + } + $this->channel = $frame['channel']; + $this->remaining = $frame['size']; + $this->header = ''; + if (0 === $this->remaining) { + continue; + } + } + $take = min($this->remaining, $length - $offset); + if (0 === $take) { + return; + } + $output = substr($data, $offset, $take); + $offset += $take; + $this->remaining -= $take; + foreach (2 === $this->channel ? $this->stderr : $this->stdout as $callback) { + $callback($output); + } + } + } +} diff --git a/src/Stream/MultiJsonStream.php b/src/Stream/MultiJsonStream.php index 0973f98a5..315af9568 100644 --- a/src/Stream/MultiJsonStream.php +++ b/src/Stream/MultiJsonStream.php @@ -12,6 +12,8 @@ */ abstract class MultiJsonStream extends CallbackStream { + use ReadsJsonDocuments; + /** @var SerializerInterface Serializer to decode incoming json object */ private $serializer; @@ -22,51 +24,10 @@ public function __construct(StreamInterface $stream, SerializerInterface $serial $this->serializer = $serializer; } - /** - * {@inheritdoc} - */ protected function readFrame() { - $jsonFrameEnd = false; - $lastJsonChar = ''; - $inquote = false; - $jsonFrame = ''; - $level = 0; - - // This is a - while (!$jsonFrameEnd && !$this->stream->eof()) { - $jsonChar = $this->stream->read(1); - - if ('"' === $jsonChar && '\\' !== $lastJsonChar) { - $inquote = !$inquote; - } - - // We ignore white space when it is not part of a quoted string. - if (!$inquote && \in_array($jsonChar, [' ', "\r", "\n", "\t"], true)) { - continue; - } - - if (!$inquote && \in_array($jsonChar, ['{', '['], true)) { - ++$level; - } - - if (!$inquote && \in_array($jsonChar, ['}', ']'], true)) { - --$level; - - if (0 === $level) { - $jsonFrameEnd = true; - $jsonFrame .= $jsonChar; - $lastJsonChar = ''; - continue; - } - } - - $jsonFrame .= $jsonChar; - $lastJsonChar = $jsonChar; - } - - // Invalid last json, or timeout, or connection close before receiving - if (!$jsonFrameEnd) { + $jsonFrame = $this->readJsonDocument(); + if (null === $jsonFrame) { return null; } diff --git a/src/Stream/PushStream.php b/src/Stream/PushStream.php index c40cb6688..4b7242db9 100644 --- a/src/Stream/PushStream.php +++ b/src/Stream/PushStream.php @@ -12,7 +12,7 @@ class PushStream extends MultiJsonStream { /** - * [@inheritdoc}. + * {@inheritdoc}. */ protected function getDecodeClass() { diff --git a/src/Stream/ReadsJsonDocuments.php b/src/Stream/ReadsJsonDocuments.php new file mode 100644 index 000000000..a3411f84a --- /dev/null +++ b/src/Stream/ReadsJsonDocuments.php @@ -0,0 +1,63 @@ +stream. + * + * Returns null when the body ends before a document is complete. + */ + protected function readJsonDocument(): ?string + { + $jsonFrameEnd = false; + $lastJsonChar = ''; + $inquote = false; + $jsonFrame = ''; + $level = 0; + + while (!$jsonFrameEnd && !$this->stream->eof()) { + $jsonChar = $this->stream->read(1); + + if ('"' === $jsonChar && '\\' !== $lastJsonChar) { + $inquote = !$inquote; + } + + // We ignore white space when it is not part of a quoted string. + if (!$inquote && \in_array($jsonChar, [' ', "\r", "\n", "\t"], true)) { + continue; + } + + if (!$inquote && \in_array($jsonChar, ['{', '['], true)) { + ++$level; + } + + if (!$inquote && \in_array($jsonChar, ['}', ']'], true)) { + --$level; + + if (0 === $level) { + $jsonFrameEnd = true; + $jsonFrame .= $jsonChar; + $lastJsonChar = ''; + continue; + } + } + + $jsonFrame .= $jsonChar; + $lastJsonChar = $jsonChar; + } + + // Invalid last json, or timeout, or connection close before receiving + if (!$jsonFrameEnd) { + return null; + } + + return $jsonFrame; + } +} diff --git a/src/Stream/SocketReadStream.php b/src/Stream/SocketReadStream.php new file mode 100644 index 000000000..d0df0da48 --- /dev/null +++ b/src/Stream/SocketReadStream.php @@ -0,0 +1,31 @@ +stream = $stream; + } + + public function read(int $length): string + { + $buffered = $this->stream->getMetadata('unread_bytes'); + if (\is_int($buffered) && $buffered > 0 && $length > 0) { + $length = min($length, $buffered); + } + + return $this->stream->read($length); + } +} diff --git a/src/Stream/StatsStream.php b/src/Stream/StatsStream.php new file mode 100644 index 000000000..a326ef564 --- /dev/null +++ b/src/Stream/StatsStream.php @@ -0,0 +1,41 @@ + false`: a ContainerStatsResponse + * model from API 1.48, or a decoded \stdClass for earlier API versions. + */ +class StatsStream extends CallbackStream +{ + use ReadsJsonDocuments; + + private const MODEL = 'Docker\\API\\Model\\ContainerStatsResponse'; + + public function __construct(StreamInterface $stream, private ?SerializerInterface $serializer = null) + { + parent::__construct($stream); + } + + protected function readFrame() + { + $jsonFrame = $this->readJsonDocument(); + if (null === $jsonFrame) { + return null; + } + + if (null !== $this->serializer && class_exists(self::MODEL)) { + return $this->serializer->deserialize($jsonFrame, self::MODEL, 'json'); + } + + return json_decode($jsonFrame, false, 512, \JSON_THROW_ON_ERROR); + } +} diff --git a/src/Stream/TarStream.php b/src/Stream/TarStream.php index ee0a17519..f14823c89 100644 --- a/src/Stream/TarStream.php +++ b/src/Stream/TarStream.php @@ -4,18 +4,92 @@ namespace Docker\Stream; -use GuzzleHttp\Psr7\Stream; +use Psr\Http\Message\StreamInterface; /** * This class avoid a bug in PHP where fstat return a size of 0 for process stream. */ -class TarStream extends Stream +class TarStream implements StreamInterface { - /** - * {@inheritdoc} - */ - public function getSize() + protected $stream; + + public function __construct(StreamInterface $stream) + { + $this->stream = $stream; + } + + public function __toString() + { + return $this->stream->__toString(); + } + + public function close(): void + { + $this->stream->close(); + } + + public function detach() + { + return $this->stream->detach(); + } + + public function getSize(): ?int { return null; } + + public function tell(): int + { + return $this->stream->tell(); + } + + public function eof(): bool + { + return $this->stream->eof(); + } + + public function isSeekable(): bool + { + return $this->stream->isSeekable(); + } + + public function seek($offset, $whence = \SEEK_SET): void + { + $this->stream->seek($offset, $whence); + } + + public function rewind(): void + { + $this->stream->rewind(); + } + + public function isWritable(): bool + { + return $this->stream->isWritable(); + } + + public function write($string): int + { + return $this->stream->write($string); + } + + public function isReadable(): bool + { + return $this->stream->isReadable(); + } + + public function read($length): string + { + return $this->stream->read($length); + } + + public function getContents(): string + { + return $this->stream->getContents(); + } + + public function getMetadata($key = null) + { + return $this->stream->getMetadata($key); + } } diff --git a/tests/Context/ContextBuilderTest.php b/tests/Context/ContextBuilderTest.php index 828faa63f..613964f01 100644 --- a/tests/Context/ContextBuilderTest.php +++ b/tests/Context/ContextBuilderTest.php @@ -61,11 +61,10 @@ public function testWriteTmpFiles(): void $contextBuilder->add('/foo', 'random content'); $context = $contextBuilder->getContext(); - $filename = \preg_replace(<<getDockerfileContent()); + $filename = preg_replace(<<getDockerfileContent()); $this->assertStringEqualsFile($context->getDirectory().'/'.$filename, 'random content'); } @@ -73,53 +72,50 @@ public function testWriteTmpFiles(): void public function testWriteTmpFileFromStream(): void { $contextBuilder = new ContextBuilder(); - $stream = \fopen('php://temp', 'r+'); - $this->assertSame(7, \fwrite($stream, 'test123')); - \rewind($stream); + $stream = fopen('php://temp', 'r+'); + $this->assertSame(7, fwrite($stream, 'test123')); + rewind($stream); $contextBuilder->addStream('/foo', $stream); $context = $contextBuilder->getContext(); - $filename = \preg_replace(<<getDockerfileContent()); + $filename = preg_replace(<<getDockerfileContent()); $this->assertStringEqualsFile($context->getDirectory().'/'.$filename, 'test123'); } public function testWriteTmpFileFromDisk(): void { $contextBuilder = new ContextBuilder(); - $file = \tempnam('', ''); - \file_put_contents($file, 'abc'); + $file = tempnam('', ''); + file_put_contents($file, 'abc'); $this->assertStringEqualsFile($file, 'abc'); $contextBuilder->addFile('/foo', $file); $context = $contextBuilder->getContext(); - $filename = \preg_replace(<<getDockerfileContent()); + $filename = preg_replace(<<getDockerfileContent()); $this->assertStringEqualsFile($context->getDirectory().'/'.$filename, 'abc'); } public function testWriteTmpDirFromDisk(): void { $contextBuilder = new ContextBuilder(); - $dir = \tempnam(\sys_get_temp_dir(), ''); - \unlink($dir); - \mkdir($dir); - \file_put_contents($dir.'/test', 'abc'); + $dir = tempnam(sys_get_temp_dir(), ''); + unlink($dir); + mkdir($dir); + file_put_contents($dir.'/test', 'abc'); $this->assertStringEqualsFile($dir.'/test', 'abc'); $contextBuilder->addFile('/foo', $dir); $context = $contextBuilder->getContext(); - $filename = \preg_replace(<<getDockerfileContent()); + $filename = preg_replace(<<getDockerfileContent()); $this->assertStringEqualsFile($context->getDirectory().'/'.$filename.'/test', 'abc'); } @@ -130,11 +126,12 @@ public function testWritesAddCommands(): void $context = $contextBuilder->getContext(); - $this->assertRegExp(<<getDockerfileContent() + $this->assertMatchesRegularExpression( + <<getDockerfileContent() ); } @@ -145,10 +142,12 @@ public function testWritesRunCommands(): void $context = $contextBuilder->getContext(); - $this->assertStringEqualsFile($context->getDirectory().'/Dockerfile', <<assertStringEqualsFile( + $context->getDirectory().'/Dockerfile', + <<getContext(); - $this->assertStringEqualsFile($context->getDirectory().'/Dockerfile', <<assertStringEqualsFile( + $context->getDirectory().'/Dockerfile', + <<getContext(); - $this->assertStringEqualsFile($context->getDirectory().'/Dockerfile', <<assertStringEqualsFile( + $context->getDirectory().'/Dockerfile', + <<getContext(); - $this->assertStringEqualsFile($context->getDirectory().'/Dockerfile', <<assertStringEqualsFile( + $context->getDirectory().'/Dockerfile', + <<getContext(); - $this->assertStringEqualsFile($context->getDirectory().'/Dockerfile', <<assertStringEqualsFile( + $context->getDirectory().'/Dockerfile', + <<command('changed'); $content = $contextBuilder->getContext()->getDockerfileContent(); - $this->assertNotContains('CMD test123', $content); + $this->assertStringNotContainsString('CMD test123', $content); $this->assertStringEndsWith("\nCMD changed", $content); } @@ -256,7 +263,7 @@ public function testWritesEntrypointCommand(): void $contextBuilder->entrypoint('changed'); $content = $contextBuilder->getContext()->getDockerfileContent(); - $this->assertNotContains('ENTRYPOINT test123', $content); + $this->assertStringNotContainsString('ENTRYPOINT test123', $content); $this->assertStringEndsWith("\nENTRYPOINT changed", $content); } @@ -266,33 +273,32 @@ public function testTar(): void $contextBuilder->setFormat(Context::FORMAT_TAR); $context = $contextBuilder->getContext(); $content = $context->read(); - $this->assertInternalType('string', $content); + $this->assertIsString($content); $this->assertSame($context->toTar(), $content); } public function testTraverseSymlinks(): void { $contextBuilder = new ContextBuilder(); - $dir = \tempnam('', ''); - \unlink($dir); - \mkdir($dir); + $dir = tempnam('', ''); + unlink($dir); + mkdir($dir); $file = $dir.'/test'; - \file_put_contents($file, 'abc'); + file_put_contents($file, 'abc'); $linkFile = $file.'-symlink'; - \symlink($file, $linkFile); + symlink($file, $linkFile); $contextBuilder->addFile('/foo', $dir); $context = $contextBuilder->getContext(); - $filename = \preg_replace(<<getDockerfileContent()); - \unlink($file); + $filename = preg_replace(<<getDockerfileContent()); + unlink($file); $context->setCleanup(false); $this->assertStringEqualsFile($context->getDirectory().'/'.$filename.'/test-symlink', 'abc'); } diff --git a/tests/Context/ContextTest.php b/tests/Context/ContextTest.php index cd2a113f2..19eac608a 100644 --- a/tests/Context/ContextTest.php +++ b/tests/Context/ContextTest.php @@ -13,10 +13,10 @@ class ContextTest extends TestCase { public function testReturnsValidTarContent(): void { - $directory = __DIR__.DIRECTORY_SEPARATOR.'context-test'; + $directory = __DIR__.\DIRECTORY_SEPARATOR.'context-test'; $context = new Context($directory); - $process = new Process('/usr/bin/env tar c .', $directory); + $process = new Process(['/usr/bin/env', 'tar', 'c', '.'], $directory); $process->run(); $this->assertSame(\strlen($process->getOutput()), \strlen($context->toTar())); @@ -24,10 +24,10 @@ public function testReturnsValidTarContent(): void public function testReturnsValidTarStream(): void { - $directory = __DIR__.DIRECTORY_SEPARATOR.'context-test'; + $directory = __DIR__.\DIRECTORY_SEPARATOR.'context-test'; $context = new Context($directory); - $this->assertInternalType('resource', $context->toStream()); + $this->assertIsResource($context->toStream()); } public function testDirectorySetter(): void @@ -38,19 +38,32 @@ public function testDirectorySetter(): void $this->assertSame('def', $context->getDirectory()); } - /** - * @expectedException \Symfony\Component\Process\Exception\ProcessFailedException - */ public function testTarFailed(): void { - $directory = __DIR__.DIRECTORY_SEPARATOR.'context-test'; - $path = \getenv('PATH'); - \putenv('PATH=/'); + $this->expectException(\Symfony\Component\Process\Exception\ProcessFailedException::class); + + $directory = __DIR__.\DIRECTORY_SEPARATOR.'context-test'; + $path = getenv('PATH'); + $serverPath = $_SERVER['PATH'] ?? null; + $environmentPath = $_ENV['PATH'] ?? null; + putenv('PATH=/'); + $_SERVER['PATH'] = '/'; + $_ENV['PATH'] = '/'; $context = new Context($directory); try { $context->toTar(); } finally { - \putenv("PATH=$path"); + putenv(false === $path ? 'PATH' : "PATH=$path"); + if (null === $serverPath) { + unset($_SERVER['PATH']); + } else { + $_SERVER['PATH'] = $serverPath; + } + if (null === $environmentPath) { + unset($_ENV['PATH']); + } else { + $_ENV['PATH'] = $environmentPath; + } } } @@ -62,6 +75,90 @@ public function testRemovesFilesOnDestruct(): void unset($context); - $this->assertFileNotExists($file); + $this->assertFileDoesNotExist($file); + } + + public function testAppliesDockerignoreByDefault(): void + { + $directory = $this->contextWithDockerignore(); + $context = new Context($directory); + $tar = $context->toTar(); + $stream = stream_get_contents($context->toStream()); + + $expected = ['./.dockerignore', './Dockerfile', './app.php', './docs', './docs/README.md']; + $this->assertSame($expected, $this->tarEntries($tar)); + $this->assertSame($expected, $this->tarEntries($stream)); + } + + public function testDockerignoreCanBeDisabled(): void + { + $directory = $this->contextWithDockerignore(); + $deprecations = $this->captureDeprecations(static function () use ($directory, &$tar): void { + $tar = (new Context($directory))->applyDockerignore(false)->toTar(); + }); + + $this->assertContains('./secret.txt', $this->tarEntries($tar)); + $this->assertSame([], $deprecations); + } + + public function testNoDeprecationWithoutDockerignore(): void + { + $deprecations = $this->captureDeprecations(static function (): void { + (new Context(__DIR__.\DIRECTORY_SEPARATOR.'context-test'))->toTar(); + }); + + $this->assertSame([], $deprecations); + } + + private function contextWithDockerignore(): string + { + $directory = sys_get_temp_dir().'/docker-context-'.bin2hex(random_bytes(4)); + foreach (['Dockerfile', 'app.php', 'secret.txt', 'docs/README.md', 'docs/guide.md'] as $file) { + @mkdir(\dirname($directory.'/'.$file), 0777, true); + file_put_contents($directory.'/'.$file, $file); + } + file_put_contents($directory.'/.dockerignore', "secret.txt\ndocs/*\n!docs/README.md\n"); + $this->directories[] = $directory; + + return $directory; + } + + private array $directories = []; + + protected function tearDown(): void + { + foreach ($this->directories as $directory) { + (new \Symfony\Component\Filesystem\Filesystem())->remove($directory); + } + } + + /** @return list */ + private function tarEntries(string $tar): array + { + $process = new Process(['/usr/bin/env', 'tar', '-t']); + $process->setInput($tar); + $process->mustRun(); + $entries = array_map(static fn (string $entry): string => rtrim($entry, '/'), explode("\n", trim($process->getOutput()))); + sort($entries); + + return $entries; + } + + /** @return list */ + private function captureDeprecations(callable $callback): array + { + $deprecations = []; + set_error_handler(static function (int $level, string $message) use (&$deprecations): bool { + $deprecations[] = $message; + + return true; + }, \E_USER_DEPRECATED); + try { + $callback(); + } finally { + restore_error_handler(); + } + + return $deprecations; } } diff --git a/tests/Context/DockerignoreTest.php b/tests/Context/DockerignoreTest.php new file mode 100644 index 000000000..b471818cf --- /dev/null +++ b/tests/Context/DockerignoreTest.php @@ -0,0 +1,67 @@ + ['*/temp*', ['a/temporary.txt' => true, 'a/temp' => true, 'a/temp/file' => true, 'temp.txt' => false, 'a/b/temp' => false]]; + yield 'two level wildcard' => ['*/*/temp*', ['a/b/temp1' => true, 'a/temp1' => false]]; + yield 'single character' => ['temp?', ['temp1' => true, 'temp12' => false, 'a/temp1' => false]]; + yield 'any depth' => ['**/*.go', ['main.go' => true, 'a/b/c.go' => true, 'a/b/c.gox' => false]]; + yield 'exception' => ["*.md\n!README*.md", ['CHANGES.md' => true, 'README.md' => false, 'README-x.md' => false]]; + yield 'last match wins' => ["*.md\n!README*.md\nREADME-secret.md", ['README.md' => false, 'README-secret.md' => true]]; + yield 'directory and contents' => ['node_modules', ['node_modules' => true, 'node_modules/a/b.js' => true, 'src/node_modules' => false]]; + yield 'leading slash and cleaning' => ["/build/\n./dist/../out", ['build' => true, 'build/x' => true, 'out/y' => true, 'dist' => false]]; + yield 'exception inside excluded directory' => ["docs\n!docs/README.md", ['docs' => true, 'docs/guide.md' => true, 'docs/README.md' => false]]; + yield 'trailing double star keeps the directory' => ['logs/**', ['logs' => false, 'logs/a' => true, 'logs/a/b' => true]]; + yield 'character class' => ["[ab].txt\n[^c]?.log", ['a.txt' => true, 'c.txt' => false, 'd1.log' => true, 'c1.log' => false]]; + yield 'comments and whitespace' => ["# secret\n secret \n\n", ['secret' => true, '# secret' => false]]; + yield 'escaped characters' => ["\\#hash\nfile\\*", ['#hash' => true, 'file*' => true, 'filex' => false]]; + yield 'regex characters are literal' => ['a.b+(c)', ['a.b+(c)' => true, 'axb+(c)' => false]]; + yield 'build files are always kept' => ['*', ['Dockerfile' => false, '.dockerignore' => false, 'src' => true]]; + } + + #[DataProvider('patternProvider')] + public function testMatchesLikeDocker(string $content, array $expected): void + { + $dockerignore = new Dockerignore($content); + + foreach ($expected as $path => $excluded) { + $this->assertSame($excluded, $dockerignore->excludes((string) $path), $path); + } + } + + public function testListsIncludedPaths(): void + { + $directory = sys_get_temp_dir().'/docker-ignore-'.bin2hex(random_bytes(4)); + foreach (['Dockerfile', 'app.php', 'docs/README.md', 'docs/guide.md', 'node_modules/x/y.js', 'empty/.keep'] as $file) { + @mkdir(\dirname($directory.'/'.$file), 0777, true); + touch($directory.'/'.$file); + } + file_put_contents($directory.'/.dockerignore', "node_modules\ndocs\n!docs/README.md\nempty/.keep\n"); + + try { + $paths = Dockerignore::fromFile($directory.'/.dockerignore')->paths($directory); + } finally { + exec('rm -rf '.escapeshellarg($directory)); + } + + $this->assertSame(['.dockerignore', 'Dockerfile', 'app.php', 'docs/README.md', 'empty'], $paths); + } + + public function testRejectsInvalidPattern(): void + { + $this->expectException(\InvalidArgumentException::class); + + new Dockerignore('[abc'); + } +} diff --git a/tests/DockerAsyncTest.php b/tests/DockerAsyncTest.php deleted file mode 100644 index 29b2f3bf1..000000000 --- a/tests/DockerAsyncTest.php +++ /dev/null @@ -1,86 +0,0 @@ -assertInstanceOf(DockerAsync::class, DockerAsync::create()); - } - - public function testAsync(): void - { - Loop::run(function () { - $docker = DockerAsync::create(); - - $containerConfig = new ContainersCreatePostBody(); - $containerConfig->setImage('busybox:latest'); - $containerConfig->setCmd(['echo', '-n', 'output']); - $containerConfig->setAttachStdout(true); - $containerConfig->setLabels(new \ArrayObject(['docker-php-test' => 'true'])); - - $response = yield $docker->imageCreate('', [ - 'fromImage' => 'busybox:latest', - ], [], DockerAsync::FETCH_RESPONSE); - - yield $response->getBody(); - - $containerCreate = yield $docker->containerCreate($containerConfig); - $containerStart = yield $docker->containerStart($containerCreate->getId()); - $containerInfo = yield $docker->containerInspect($containerCreate->getId()); - - $this->assertSame($containerCreate->getId(), $containerInfo->getId()); - }); - } - - public function testSystemEventsAllowTheConsumptionOfDockerEvents(): void - { - $matchedEvents = []; - - Loop::run(function () use (&$matchedEvents) { - $docker = DockerAsync::create(); - - /** @var ArtaxCallbackStream $events */ - $events = yield $docker->systemEvents([ - 'filters' => \json_encode( - [ - 'type' => ['container'], - 'action' => ['create'], - ] - ), - ]); - $events->onFrame(function ($event) use (&$matchedEvents): void { - if (\is_object($event) - && $event instanceof EventsGetResponse200 - && 'create' === $event->getAction() - && 'container' === $event->getType() - ) { - $matchedEvents[] = $event; - } - }); - - $events->listen(); - - $containerConfig = new ContainersCreatePostBody(); - $containerConfig->setImage('busybox:latest'); - $containerConfig->setCmd(['echo', '-n', 'output']); - - yield $docker->containerCreate($containerConfig); - - Loop::delay(1000, function (): void { - Loop::stop(); - }); - }); - - $this->assertCount(1, $matchedEvents); - } -} diff --git a/tests/DockerClientFactoryTest.php b/tests/DockerClientFactoryTest.php index 286419d43..767a06eca 100644 --- a/tests/DockerClientFactoryTest.php +++ b/tests/DockerClientFactoryTest.php @@ -5,45 +5,188 @@ namespace Docker\Tests; use Docker\DockerClientFactory; -use Http\Client\HttpClient; +use Docker\Http\ApiVersionNegotiationPlugin; +use Http\Client\Common\Plugin\AddPathPlugin; +use Http\Client\Common\PluginClient; +use Http\Client\Common\PluginClientFactory; +use Http\Client\Socket\Client; +use PHPUnit\Framework\Attributes\DataProvider; +use Psr\Http\Client\ClientInterface; class DockerClientFactoryTest extends TestCase { + private array $environment = []; + + protected function setUp(): void + { + parent::setUp(); + foreach (['DOCKER_HOST', 'DOCKER_API_VERSION', 'DOCKER_TLS_VERIFY', 'DOCKER_CERT_PATH', 'DOCKER_PEER_NAME'] as $name) { + $this->environment[$name] = getenv($name); + putenv($name); + } + } + protected function tearDown(): void { parent::tearDown(); - \putenv('DOCKER_TLS_VERIFY'); + PluginClientFactory::setFactory(static function ($client, array $plugins, array $options): PluginClient { + unset($options['client_name']); + + return new PluginClient($client, $plugins, $options); + }); + foreach ($this->environment as $name => $value) { + putenv(false === $value ? $name : $name.'='.$value); + } } public function testStaticConstructor(): void { - $this->assertInstanceOf(HttpClient::class, DockerClientFactory::create()); + $this->assertInstanceOf(ClientInterface::class, DockerClientFactory::create()); + } + + public static function socketAddresses(): array + { + return [ + 'Unix socket' => ['unix:///var/run/docker.sock', 'unix:///var/run/docker.sock', 'http://localhost', null], + 'TCP socket' => ['tcp://docker.test:2375', 'tcp://docker.test:2375', 'http://docker.test:2375', null], + 'HTTP URL' => ['http://docker.test:2375', 'tcp://docker.test:2375', 'http://docker.test:2375', null], + 'HTTPS URL' => ['https://docker.test:2376', 'tcp://docker.test:2376', 'https://docker.test:2376', true], + 'Default HTTP port' => ['http://docker.test', 'tcp://docker.test:80', 'http://docker.test', null], + 'Default HTTPS port' => ['https://docker.test', 'tcp://docker.test:443', 'https://docker.test', true], + 'Explicit default HTTPS port' => ['https://docker.test:443', 'tcp://docker.test:443', 'https://docker.test', true], + 'IPv6 HTTP' => ['http://[::1]:2375', 'tcp://[::1]:2375', 'http://[::1]:2375', null], + 'IPv6 HTTPS' => ['https://[::1]', 'tcp://[::1]:443', 'https://[::1]', true], + 'Uppercase HTTPS scheme' => ['HTTPS://docker.test:2376', 'tcp://docker.test:2376', 'https://docker.test:2376', true], + ]; + } + + #[DataProvider('socketAddresses')] + public function testSocketAddressAndRequestUri(string $address, string $socket, string $host, ?bool $ssl): void + { + $config = []; + $uri = null; + PluginClientFactory::setFactory(static function (Client $client, array $plugins, array $options) use (&$config, &$uri): PluginClient { + $config = (new \ReflectionProperty($client, 'config'))->getValue($client); + foreach ($plugins as $plugin) { + if ($plugin instanceof \Http\Client\Common\Plugin\AddHostPlugin) { + $uri = (new \ReflectionProperty($plugin, 'host'))->getValue($plugin); + } + } + unset($options['client_name']); + + return new PluginClient($client, $plugins, $options); + }); + + DockerClientFactory::create(['remote_socket' => $address]); + + $this->assertSame($socket, $config['remote_socket']); + $this->assertSame($ssl, $config['ssl']); + $this->assertSame($host, (string) $uri); + } + + public function testNegotiatesWithoutAnExplicitVersion(): void + { + $plugins = $this->createdPlugins(); + + $this->assertCount(1, array_filter($plugins, static fn (object $plugin): bool => $plugin instanceof ApiVersionNegotiationPlugin)); + $this->assertCount(0, array_filter($plugins, static fn (object $plugin): bool => $plugin instanceof AddPathPlugin)); + } + + public function testDefaultApiVersionMatchesGeneratedClient(): void + { + $specification = (new \ReflectionClass(\Docker\API\Client::class))->getFileName(); + $this->assertMatchesRegularExpression('#^1\.[0-9]+$#', DockerClientFactory::defaultApiVersion()); + $this->assertStringContainsString("createUri('/v".DockerClientFactory::defaultApiVersion()."')", file_get_contents($specification)); + } + + public function testApiVersionFromEnvironment(): void + { + putenv('DOCKER_API_VERSION=v1.52'); + + $this->assertSame('/v1.52', $this->getApiPath()); + } + + public function testApiVersionWithLeadingSlash(): void + { + putenv('DOCKER_API_VERSION=/v1.52'); + + $this->assertSame('/v1.52', $this->getApiPath()); + } + + public function testApiVersionWithoutVersionPrefix(): void + { + putenv('DOCKER_API_VERSION=1.52'); + + $this->assertSame('/v1.52', $this->getApiPath()); + } + + public static function explicitApiVersions(): array + { + return [['1.45'], ['v1.45'], ['/v1.45'], ['/1.45']]; + } + + #[DataProvider('explicitApiVersions')] + public function testExplicitApiVersionOverridesEnvironment(string $version): void + { + putenv('DOCKER_API_VERSION=1.52'); + + $this->assertSame('/v1.45', $this->getApiPath(['api_version' => $version])); + $this->assertSame('1.52', getenv('DOCKER_API_VERSION')); + } + + public static function invalidApiVersions(): array + { + return [[''], [null], [1.45], [145], [false], [[]], ['1'], ['1.45/containers'], ['1.45?x=1'], [' 1.45'], ["1.45\n"]]; + } + + #[DataProvider('invalidApiVersions')] + public function testInvalidExplicitApiVersionIsRejected($version): void + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('api_version must be a Docker API version'); + + DockerClientFactory::create(['api_version' => $version]); + } + + public function testApiVersionIsNotPassedToSocketClient(): void + { + $config = []; + PluginClientFactory::setFactory(static function (Client $client, array $plugins, array $options) use (&$config): PluginClient { + $config = (new \ReflectionProperty($client, 'config'))->getValue($client); + unset($options['client_name']); + + return new PluginClient($client, $plugins, $options); + }); + + DockerClientFactory::create(['api_version' => '1.45', 'timeout' => 30000]); + + $this->assertArrayNotHasKey('api_version', $config); + $this->assertSame(30000, $config['timeout']); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Connection to docker has been set to use TLS, but no PATH is defined for certificate in DOCKER_CERT_PATH docker environment variable - */ public function testCreateFromEnvWithoutCertPath(): void { - \putenv('DOCKER_TLS_VERIFY=1'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Connection to docker has been set to use TLS, but no PATH is defined for certificate in DOCKER_CERT_PATH docker environment variable'); + + putenv('DOCKER_TLS_VERIFY=1'); DockerClientFactory::createFromEnv(); } public function testCreateCustomCa(): void { - \putenv('DOCKER_TLS_VERIFY=1'); - \putenv('DOCKER_CERT_PATH=/tmp'); + putenv('DOCKER_TLS_VERIFY=1'); + putenv('DOCKER_CERT_PATH=/tmp'); - $count = \count(\get_resources('stream-context')); + $count = \count(get_resources('stream-context')); $client = DockerClientFactory::createFromEnv(); - $this->assertInstanceOf(HttpClient::class, $client); + $this->assertInstanceOf(ClientInterface::class, $client); - $contexts = \get_resources('stream-context'); + $contexts = get_resources('stream-context'); $this->assertCount($count + 1, $contexts); // Get the last stream context. - $context = \stream_context_get_options(\end($contexts)); + $context = stream_context_get_options(end($contexts)); $this->assertSame('/tmp/ca.pem', $context['ssl']['cafile']); $this->assertSame('/tmp/cert.pem', $context['ssl']['local_cert']); $this->assertSame('/tmp/key.pem', $context['ssl']['local_pk']); @@ -51,22 +194,50 @@ public function testCreateCustomCa(): void public function testCreateCustomPeerName(): void { - \putenv('DOCKER_TLS_VERIFY=1'); - \putenv('DOCKER_CERT_PATH=/abc'); - \putenv('DOCKER_PEER_NAME=test'); + putenv('DOCKER_TLS_VERIFY=1'); + putenv('DOCKER_CERT_PATH=/abc'); + putenv('DOCKER_PEER_NAME=test'); - $count = \count(\get_resources('stream-context')); + $count = \count(get_resources('stream-context')); $client = DockerClientFactory::createFromEnv(); - $this->assertInstanceOf(HttpClient::class, $client); + $this->assertInstanceOf(ClientInterface::class, $client); - $contexts = \get_resources('stream-context'); + $contexts = get_resources('stream-context'); $this->assertCount($count + 1, $contexts); // Get the last stream context. - $context = \stream_context_get_options(\end($contexts)); + $context = stream_context_get_options(end($contexts)); $this->assertSame('/abc/ca.pem', $context['ssl']['cafile']); $this->assertSame('/abc/cert.pem', $context['ssl']['local_cert']); $this->assertSame('/abc/key.pem', $context['ssl']['local_pk']); $this->assertSame('test', $context['ssl']['peer_name']); } + + private function createdPlugins(array $config = []): array + { + $plugins = []; + PluginClientFactory::setFactory(static function ($client, array $createdPlugins, array $options) use (&$plugins): PluginClient { + $plugins = $createdPlugins; + unset($options['client_name']); + + return new PluginClient($client, $createdPlugins, $options); + }); + + DockerClientFactory::create($config); + + return $plugins; + } + + private function getApiPath(array $config = []): string + { + foreach ($this->createdPlugins($config) as $plugin) { + if ($plugin instanceof AddPathPlugin) { + $uri = (new \ReflectionProperty($plugin, 'uri'))->getValue($plugin); + + return $uri->getPath(); + } + } + + $this->fail('The Docker API path plugin was not configured.'); + } } diff --git a/tests/DockerClientFactoryTransportTest.php b/tests/DockerClientFactoryTransportTest.php new file mode 100644 index 000000000..a75e94a69 --- /dev/null +++ b/tests/DockerClientFactoryTransportTest.php @@ -0,0 +1,170 @@ + ['unix'], + 'TCP socket' => ['tcp'], + 'HTTP URL' => ['http'], + 'HTTPS URL' => ['https'], + ]; + } + + #[DataProvider('transports')] + public function testRealConnection(string $scheme): void + { + $serverConfig = []; + $clientConfig = ['timeout' => 3000]; + if ('https' === $scheme) { + $this->createCertificates(); + $serverConfig['ssl'] = $this->serverTlsOptions(); + $clientConfig['stream_context_options']['ssl']['cafile'] = $this->directory.'/ca.pem'; + } + $address = $this->startServer($serverConfig, 'unix' === $scheme); + $clientConfig['remote_socket'] = $scheme.'://'.$address; + $response = DockerClientFactory::create($clientConfig)->sendRequest(new Request('GET', '/_ping')); + + $this->assertSame(200, $response->getStatusCode()); + $this->assertSame('OK', $response->getBody()->getContents()); + $request = $this->serverResult()['request']; + $this->assertStringStartsWith('GET /v'.DockerClientFactory::defaultApiVersion()."/_ping HTTP/1.1\r\n", $request); + $expectedHost = 'unix' === $scheme ? 'localhost' : $address; + $this->assertStringContainsString('Host: '.$expectedHost."\r\n", $request); + } + + public function testNegotiatesWithAnOlderDaemon(): void + { + $address = $this->startServer(['daemon_api_version' => '1.41']); + + $response = DockerClientFactory::create(['remote_socket' => 'tcp://'.$address, 'timeout' => 3000])->sendRequest(new Request('GET', '/containers/json')); + + $this->assertSame('OK', $response->getBody()->getContents()); + $this->assertStringStartsWith('GET /v1.41/containers/json HTTP/1.1', $this->serverResult()['request']); + } + + public function testHttpUrlFromEnvironment(): void + { + $address = $this->startServer(); + putenv('DOCKER_HOST=http://'.$address); + putenv('DOCKER_API_VERSION=1.52'); + + $response = DockerClientFactory::createFromEnv()->sendRequest(new Request('GET', '/_ping')); + + $this->assertSame('OK', $response->getBody()->getContents()); + $this->assertStringStartsWith('GET /v1.52/_ping HTTP/1.1', $this->serverResult()['request']); + } + + #[DataProvider('transports')] + public function testExplicitApiVersionOnRealConnection(string $scheme): void + { + putenv('DOCKER_API_VERSION=1.52'); + $serverConfig = []; + $clientConfig = ['api_version' => '1.45', 'timeout' => 3000]; + if ('https' === $scheme) { + $this->createCertificates(); + $serverConfig['ssl'] = $this->serverTlsOptions(); + $clientConfig['stream_context_options']['ssl']['cafile'] = $this->directory.'/ca.pem'; + } + $address = $this->startServer($serverConfig, 'unix' === $scheme); + $clientConfig['remote_socket'] = $scheme.'://'.$address; + $response = DockerClientFactory::create($clientConfig)->sendRequest(new Request('GET', '/_ping')); + + $this->assertSame('OK', $response->getBody()->getContents()); + $this->assertStringStartsWith('GET /v1.45/_ping HTTP/1.1', $this->serverResult()['request']); + $this->assertSame('1.52', getenv('DOCKER_API_VERSION')); + } + + public function testHttpsDoesNotAllowPlaintextDowngrade(): void + { + $this->createCertificates(); + $address = $this->startServer(['ssl' => $this->serverTlsOptions()]); + $response = DockerClientFactory::create([ + 'remote_socket' => 'https://'.$address, + 'ssl' => false, + 'timeout' => 3000, + 'stream_context_options' => ['ssl' => ['cafile' => $this->directory.'/ca.pem']], + ])->sendRequest(new Request('GET', '/_ping')); + + $this->assertSame('OK', $response->getBody()->getContents()); + $this->assertNotEmpty($this->serverResult()['request']); + } + + public function testHttpsRejectsUntrustedCertificate(): void + { + $this->createCertificates(); + $address = $this->startServer(['ssl' => $this->serverTlsOptions()]); + $this->expectException(SSLConnectionException::class); + + DockerClientFactory::create([ + 'remote_socket' => 'https://'.$address, + 'timeout' => 3000, + ])->sendRequest(new Request('GET', '/_ping')); + } + + public function testHttpsRejectsWrongPeerName(): void + { + $this->createCertificates(); + $address = $this->startServer(['ssl' => $this->serverTlsOptions()]); + $this->expectException(SSLConnectionException::class); + + DockerClientFactory::create([ + 'remote_socket' => 'https://'.$address, + 'timeout' => 3000, + 'stream_context_options' => ['ssl' => [ + 'cafile' => $this->directory.'/ca.pem', + 'peer_name' => 'not-docker.test', + ]], + ])->sendRequest(new Request('GET', '/_ping')); + } + + public static function tlsTransports(): array + { + return ['TCP with TLS' => ['tcp'], 'HTTPS with client certificates' => ['https']]; + } + + #[DataProvider('tlsTransports')] + public function testTlsEnvironmentWithClientCertificates(string $scheme): void + { + $this->createCertificates(); + $address = $this->startServer(['ssl' => $this->serverTlsOptions() + [ + 'verify_peer' => true, + 'verify_peer_name' => false, + 'cafile' => $this->directory.'/ca.pem', + 'capture_peer_cert' => true, + ]]); + putenv('DOCKER_HOST='.$scheme.'://'.$address); + putenv('DOCKER_TLS_VERIFY=1'); + putenv('DOCKER_CERT_PATH='.$this->directory); + putenv('DOCKER_PEER_NAME=docker.test'); + + $response = DockerClientFactory::createFromEnv()->sendRequest(new Request('GET', '/_ping')); + + $this->assertSame('OK', $response->getBody()->getContents()); + $this->assertSame('docker-client', $this->serverResult()['peer']); + } + + public function testUpgradedResponseRemainsReadable(): void + { + $address = $this->startServer(['upgrade' => true]); + $response = DockerClientFactory::create(['remote_socket' => 'http://'.$address])->sendRequest( + new Request('POST', '/exec/test/start', ['Connection' => 'Upgrade', 'Upgrade' => 'tcp']) + ); + + $this->assertSame(101, $response->getStatusCode()); + $this->assertSame('stream-output', $response->getBody()->getContents()); + $request = $this->serverResult()['request']; + $this->assertStringContainsString("Connection: Upgrade\r\n", $request); + $this->assertStringContainsString("Upgrade: tcp\r\n", $request); + } +} diff --git a/tests/DockerLogsTest.php b/tests/DockerLogsTest.php new file mode 100644 index 000000000..644ad04a7 --- /dev/null +++ b/tests/DockerLogsTest.php @@ -0,0 +1,73 @@ + [DockerRawStream::MULTIPLEXED_HEADER, $framed, false, ['/containers/test/logs']]; + yield 'modern TTY' => [DockerRawStream::HEADER, "hello\n", true, ['/containers/test/logs', '/containers/test/json']]; + yield 'legacy non-TTY' => [DockerRawStream::HEADER, $framed, false, ['/containers/test/logs', '/containers/test/json']]; + } + + /** @dataProvider logsProvider */ + public function testContainerLogs(string $contentType, string $body, bool $tty, array $expectedPaths): void + { + $paths = []; + $httpClient = $this->createMock(ClientInterface::class); + $httpClient->method('sendRequest')->willReturnCallback(static function (RequestInterface $request) use (&$paths, $contentType, $body, $tty): ResponseInterface { + $path = $request->getUri()->getPath(); + if ('/info' === $path) { + return new Response(200, ['Content-Type' => 'application/json'], '{}'); + } + $paths[] = $path; + if ('/containers/test/logs' === $path) { + return new Response(200, ['Content-Type' => $contentType], $body); + } + if ('/containers/test/json' === $path) { + return new Response(200, ['Content-Type' => 'application/json'], json_encode(['Config' => ['Tty' => $tty]], \JSON_THROW_ON_ERROR)); + } + + throw new \LogicException('Unexpected request: '.$path); + }); + $docker = Docker::create($httpClient, [], [], false); + $stream = $docker->containerLogs('test', ['stdout' => true]); + + self::assertInstanceOf(DockerRawStream::class, $stream); + $output = ''; + $stream->onStdout(static function (string $chunk) use (&$output): void { + $output .= $chunk; + }); + $stream->wait(); + + self::assertSame("hello\n", $output); + self::assertSame($expectedPaths, $paths); + } + + public function testRawEndpointStillReturnsUnmodifiedResponse(): void + { + $body = pack('CxxxN', 1, 6)."hello\n"; + $httpClient = $this->createMock(ClientInterface::class); + $httpClient->expects(self::exactly(2))->method('sendRequest')->willReturnOnConsecutiveCalls( + new Response(200, ['Content-Type' => 'application/json'], '{}'), + new Response(200, ['Content-Type' => DockerRawStream::MULTIPLEXED_HEADER], $body) + ); + $docker = Docker::create($httpClient, [], [], false); + $response = $docker->executeRawEndpoint(new ContainerLogs('test', ['stdout' => true])); + + self::assertSame($body, $response->getBody()->getContents()); + } +} diff --git a/tests/DockerTest.php b/tests/DockerTest.php index baba25237..ae8759176 100644 --- a/tests/DockerTest.php +++ b/tests/DockerTest.php @@ -5,6 +5,11 @@ namespace Docker\Tests; use Docker\Docker; +use Docker\Exception\BadRequestException; +use Nyholm\Psr7\Response; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; class DockerTest extends TestCase { @@ -12,4 +17,36 @@ public function testCreate(): void { $this->assertInstanceOf(Docker::class, Docker::create()); } + + public function testCreateForwardsServerPluginOption(): void + { + $httpClient = new class implements ClientInterface { + public ?RequestInterface $request = null; + + public function sendRequest(RequestInterface $request): ResponseInterface + { + $this->request = $request; + + return new Response(200, ['Content-Type' => 'application/json'], '{}'); + } + }; + + $this->assertInstanceOf(Docker::class, Docker::create($httpClient, [], [], false)); + $this->assertSame('/info', $httpClient->request?->getUri()->getPath()); + } + + public function testCreateThrowsConcreteExceptionForInvalidResponse(): void + { + $httpClient = new class implements ClientInterface { + public function sendRequest(RequestInterface $request): ResponseInterface + { + return new Response(200, ['Content-Type' => 'application/json'], 'invalid'); + } + }; + + $this->expectException(BadRequestException::class); + $this->expectExceptionMessage('Failed to decode JSON.'); + + Docker::create($httpClient, [], [], false); + } } diff --git a/tests/DocumentationExamplesTest.php b/tests/DocumentationExamplesTest.php new file mode 100644 index 000000000..ff0019b3a --- /dev/null +++ b/tests/DocumentationExamplesTest.php @@ -0,0 +1,314 @@ +fixtureDirectory = sys_get_temp_dir().'/docker-php-docs-'.bin2hex(random_bytes(12)); + $fs = new Filesystem(); + $fs->mkdir($this->fixtureDirectory.'/build'); + $fs->dumpFile($this->fixtureDirectory.'/build/Dockerfile', "FROM busybox:latest\nCMD echo hello\n"); + $fs->dumpFile($this->fixtureDirectory.'/upload.tar', "upload fixture\0"); + $fs->dumpFile($this->fixtureDirectory.'/saved-image.tar', "image fixture\0"); + } + + protected function tearDown(): void + { + (new Filesystem())->remove($this->fixtureDirectory); + } + + private function client(callable $respond): Docker + { + $record = function (RequestInterface $request) use ($respond): ResponseInterface { + if ('/info' === $request->getUri()->getPath()) { + return new Response(200, ['Content-Type' => 'application/json'], '{}'); + } + $this->requests[] = [ + 'method' => $request->getMethod(), + 'path' => $request->getUri()->getPath(), + 'query' => $request->getUri()->getQuery(), + 'headers' => $request->getHeaders(), + 'body' => $request->getBody()->getContents(), + ]; + + return $respond($request); + }; + $httpClient = new class($record) implements ClientInterface { + public function __construct(private $respond) + { + } + + public function sendRequest(RequestInterface $request): ResponseInterface + { + return ($this->respond)($request); + } + }; + + return Docker::create($httpClient, [], [], false); + } + + private function runExample(string $page, int $index, Docker $client, array $variables = []): string + { + $markdown = file_get_contents(\dirname(__DIR__).'/docs/'.$page.'.mdx'); + preg_match_all('/^```php[^\r\n]*\R(.*?)^```/ms', $markdown, $blocks); + self::assertArrayHasKey($index, $blocks[1]); + // Fragments reuse the imports from the complete example on their page. + preg_match_all('/^use [^;]+;$/m', implode("\n", $blocks[1]), $imports); + $code = preg_replace('/^\s*<\?php\s*/', '', $blocks[1][$index]); + $code = preg_replace('/^use [^;]+;$/m', '', $code); + $code = str_replace("require __DIR__ . '/vendor/autoload.php';", '', $code); + $code = str_replace('$docker = Docker::create();', '$docker = $documentationClient;', $code); + $code = str_replace('getenv(\'DOCKER_REGISTRY_USER\')', "'documentation-user'", $code); + $code = str_replace('getenv(\'DOCKER_REGISTRY_TOKEN\')', "'documentation-token'", $code); + $code = str_replace('__DIR__', var_export($this->fixtureDirectory, true), $code); + self::assertStringNotContainsString('Docker::create(', $code, 'Examples must use the fake transport'); + $code = "namespace {\n".implode("\n", array_unique($imports[0]))."\n".$code."\n}"; + + ob_start(); + try { + (static function (Docker $documentationClient, array $variables, string $code): void { + $docker = $documentationClient; + $username = 'documentation-user'; + $token = 'documentation-token'; + extract($variables, \EXTR_SKIP); + eval($code); + })($client, $variables, $code); + + return ob_get_contents(); + } finally { + ob_end_clean(); + } + } + + public function testContainerConfigurationPreservesNestedJsonShapes(): void + { + $client = $this->client(static fn () => new Response(201, ['Content-Type' => 'application/json'], '{"Id":"created","Warnings":[]}')); + self::assertStringContainsString('Created created', $this->runExample('cookbook/container-config', 0, $client)); + $payload = json_decode($this->requests[0]['body'], false, 512, \JSON_THROW_ON_ERROR); + self::assertInstanceOf(\stdClass::class, $payload->ExposedPorts->{'80/tcp'}); + self::assertSame('8080', $payload->HostConfig->PortBindings->{'80/tcp'}[0]->HostPort); + self::assertSame('127.0.0.1', $payload->HostConfig->PortBindings->{'80/tcp'}[0]->HostIp); + self::assertTrue($payload->HostConfig->Mounts[0]->ReadOnly); + self::assertSame(['EXAMPLE_MODE=development'], $payload->Env); + self::assertSame('POST', $this->requests[0]['method']); + self::assertSame('/containers/create', $this->requests[0]['path']); + } + + public function testPullUsesAnEncodedHeaderAndConsumesProgress(): void + { + $client = $this->client(static fn () => new Response(200, ['Content-Type' => 'application/json'], "{\"status\":\"Pulling\"}\n{\"status\":\"Done\"}\n")); + $output = $this->runExample('guides/registry', 0, $client); + self::assertStringContainsString('Pulling', $output); + self::assertStringContainsString('Done', $output); + $header = $this->requests[0]['headers']['X-Registry-Auth'][0]; + $auth = json_decode(base64_decode(strtr($header, '-_', '+/'), true), true, 512, \JSON_THROW_ON_ERROR); + self::assertSame('documentation-token', $auth['password']); + parse_str($this->requests[0]['query'], $query); + self::assertSame('registry.example.com/team/app', $query['fromImage']); + self::assertSame('example', $query['tag']); + } + + public function testPullReportsAnErrorInsideAnHttp200Stream(): void + { + $client = $this->client(static fn () => new Response(200, ['Content-Type' => 'application/json'], '{"errorDetail":{"message":"pull denied"},"error":"pull denied"}')); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('pull denied'); + $this->runExample('guides/registry', 0, $client); + } + + public function testPushConvertsTheAuthModel(): void + { + $client = $this->client(static fn (RequestInterface $request) => str_ends_with($request->getUri()->getPath(), '/tag') + ? new Response(201) + : new Response(200, ['Content-Type' => 'application/json'], '{"status":"Pushed"}')); + self::assertStringContainsString('Pushed', $this->runExample('guides/registry', 1, $client)); + self::assertCount(2, $this->requests); + $auth = json_decode(base64_decode($this->requests[1]['headers']['X-Registry-Auth'][0], true), true, 512, \JSON_THROW_ON_ERROR); + self::assertSame('documentation-user', $auth['username']); + self::assertSame('registry.example.com', $auth['serveraddress']); + } + + public static function buildExamples(): iterable + { + // Index 1 is the one-line .dockerignore opt-in, which does not build. + yield 'directory context' => [0]; + yield 'query options' => [2]; + yield 'generated context' => [3]; + yield 'private base image' => [4]; + } + + /** @dataProvider buildExamples */ + public function testBuildExamplesSendTarAndReadFrames(int $index): void + { + $client = $this->client(static fn () => new Response(200, ['Content-Type' => 'application/json'], '{"stream":"Built successfully"}')); + self::assertStringContainsString('Built successfully', $this->runExample('cookbook/build-image', $index, $client)); + self::assertSame('/build', $this->requests[0]['path']); + self::assertStringContainsString('Dockerfile', $this->requests[0]['body']); + if (2 === $index) { + parse_str($this->requests[0]['query'], $query); + self::assertSame(['APP_MODE' => 'development'], json_decode($query['buildargs'], true, 512, \JSON_THROW_ON_ERROR)); + self::assertSame('true', $query['pull']); + } + if (4 === $index) { + $config = json_decode(base64_decode($this->requests[0]['headers']['X-Registry-Config'][0], true), true, 512, \JSON_THROW_ON_ERROR); + self::assertSame('documentation-token', $config['registry.example.com']['password']); + } + } + + public function testArchiveDownloadPreservesBinaryBytes(): void + { + $bytes = "archive\0\xff".str_repeat('x', 70000); + $client = $this->client(static fn () => new Response(200, ['Content-Type' => 'application/x-tar'], $bytes)); + $this->runExample('guides/archives', 0, $client); + self::assertSame($bytes, file_get_contents($this->fixtureDirectory.'/container-etc.tar')); + } + + public function testArchiveDownloadChecksStatusBeforeCreatingAFile(): void + { + $client = $this->client(static fn () => new Response(404, ['Content-Type' => 'application/json'], '{"message":"not found"}')); + try { + $this->runExample('guides/archives', 0, $client); + self::fail('Expected the raw HTTP error to be rejected'); + } catch (\RuntimeException $error) { + self::assertStringContainsString('HTTP 404', $error->getMessage()); + self::assertFileDoesNotExist($this->fixtureDirectory.'/container-etc.tar'); + } + } + + public function testArchiveMetadataComesFromTheHeader(): void + { + $client = $this->client(static fn () => new Response(200, ['X-Docker-Container-Path-Stat' => base64_encode('{"name":"etc"}')], '')); + self::assertSame("etc\n", $this->runExample('guides/archives', 1, $client)); + self::assertSame('HEAD', $this->requests[0]['method']); + } + + public function testArchiveUploadStreamsTheInputAndUsesStringOptions(): void + { + $client = $this->client(static fn () => new Response(200)); + $this->runExample('guides/archives', 2, $client); + self::assertSame("upload fixture\0", $this->requests[0]['body']); + self::assertSame('PUT', $this->requests[0]['method']); + parse_str($this->requests[0]['query'], $query); + self::assertSame('true', $query['noOverwriteDirNonDir']); + self::assertSame('/tmp', $query['path']); + } + + public function testImageLoadReadsMultipleProgressDocuments(): void + { + $client = $this->client(static fn () => new Response(200, ['Content-Type' => 'application/json'], "{\"stream\":\"Loaded one\\n\"}\n{\"stream\":\"Loaded two\\n\"}\n")); + self::assertSame("Loaded one\nLoaded two\n", $this->runExample('guides/image-transfer', 0, $client)); + self::assertSame("image fixture\0", $this->requests[0]['body']); + } + + public function testImageLoadDetectsAnErrorInsideHttp200(): void + { + $client = $this->client(static fn () => new Response(200, ['Content-Type' => 'application/json'], '{"errorDetail":{"message":"invalid archive"}}')); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('invalid archive'); + $this->runExample('guides/image-transfer', 0, $client); + } + + public function testEventsUseStringTimestampsAndModelCallbacks(): void + { + $client = $this->client(static fn () => new Response(200, ['Content-Type' => 'application/json'], '{"time":123,"Action":"start","Actor":{"ID":"example"}}')); + self::assertSame("123\tstart\texample\n", $this->runExample('guides/events-and-stats', 0, $client)); + parse_str($this->requests[0]['query'], $query); + self::assertSame(60, (int) $query['until'] - (int) $query['since']); + self::assertSame(['type' => ['container']], json_decode($query['filters'], true, 512, \JSON_THROW_ON_ERROR)); + } + + public function testStatsExplicitlyDisableStreaming(): void + { + if (!class_exists('Docker\\API\\Model\\ContainerStatsResponse')) { + self::markTestSkipped('The stats example uses the model added in API 1.48.'); + } + $client = $this->client(static fn () => new Response(200, ['Content-Type' => 'application/json'], '{"memory_stats":{"usage":1024}}')); + self::assertSame("Memory usage: 1024 bytes\n", $this->runExample('guides/events-and-stats', 1, $client)); + parse_str($this->requests[0]['query'], $query); + self::assertSame('0', $query['stream']); + } + + public function testJsonQueryParametersAreEncodedOnce(): void + { + $client = $this->client(static fn () => new Response(200, ['Content-Type' => 'application/json'], '[]')); + $this->runExample('reference/requests-and-responses', 0, $client); + parse_str($this->requests[0]['query'], $query); + self::assertSame(['label' => ['docker-php-example=true'], 'status' => ['running']], json_decode($query['filters'], true, 512, \JSON_THROW_ON_ERROR)); + } + + public function testBuildReportsDaemonErrorsAfterHttpSuccess(): void + { + $client = $this->client(static fn () => new Response(200, ['Content-Type' => 'application/json'], '{"errorDetail":{"message":"build failed"},"error":"build failed"}')); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('build failed'); + $this->runExample('cookbook/build-image', 0, $client); + } + + public function testLineBufferHandlesSplitLinesAndAnUnterminatedLastLine(): void + { + $frames = pack('CxxxN', 1, 3).'hel'.pack('CxxxN', 1, 7)."lo\nlast"; + $client = $this->client(static fn () => new Response(200, ['Content-Type' => 'application/vnd.docker.multiplexed-stream'], $frames)); + self::assertSame("line: hello\nlast line: last\n", $this->runExample('guides/logs', 2, $client)); + } + + public function testExecCreatesAndStartsWithConsistentTtySettings(): void + { + $client = $this->client(static fn (RequestInterface $request) => str_ends_with($request->getUri()->getPath(), '/exec') + ? new Response(201, ['Content-Type' => 'application/json'], '{"Id":"example-exec"}') + : new Response(101, ['Content-Type' => 'application/vnd.docker.multiplexed-stream'], pack('CxxxN', 1, 6)."hello\n")); + self::assertSame("hello\n", $this->runExample('guides/exec', 0, $client)); + $create = json_decode($this->requests[0]['body'], true, 512, \JSON_THROW_ON_ERROR); + $start = json_decode($this->requests[1]['body'], true, 512, \JSON_THROW_ON_ERROR); + self::assertFalse($create['Tty']); + self::assertFalse($start['Tty']); + self::assertFalse($start['Detach']); + } + + public function testExecChecksTheCommandExitCode(): void + { + $client = $this->client(static fn () => new Response(200, ['Content-Type' => 'application/json'], '{"Running":false,"ExitCode":7}')); + // API 1.48 renamed IdResponse to IDResponse; class names are case-sensitive on Linux. + $model = is_file(\dirname((new \ReflectionClass(\Docker\API\Client::class))->getFileName()).'/Model/IDResponse.php') + ? 'Docker\\API\\Model\\IDResponse' + : 'Docker\\API\\Model\\IdResponse'; + $exec = new $model(); + $exec->setId('example-exec'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('exit status 7'); + $this->runExample('guides/exec', 1, $client, ['exec' => $exec]); + } + + public function testRawResponseExampleChecksTheHttpStatus(): void + { + $client = $this->client(static fn () => new Response(500)); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('HTTP 500'); + $this->runExample('reference/requests-and-responses', 1, $client); + } + + public function testTypedErrorExampleUsesTheDaemonMessage(): void + { + $client = $this->client(static fn () => new Response(404, ['Content-Type' => 'application/json'], '{"message":"example missing"}')); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('example missing'); + $this->runExample('reference/requests-and-responses', 2, $client); + } +} diff --git a/tests/Endpoint/ContainerAttachTest.php b/tests/Endpoint/ContainerAttachTest.php new file mode 100644 index 000000000..4897ef503 --- /dev/null +++ b/tests/Endpoint/ContainerAttachTest.php @@ -0,0 +1,96 @@ + [200, DockerRawStream::HEADER, false, $framed, "hello\n", "oops\n", 1]; + yield 'TTY plain response' => [200, DockerRawStream::HEADER, true, "hello\n", "hello\n", '', 1]; + yield 'non-TTY upgraded response' => [101, DockerRawStream::MULTIPLEXED_HEADER, false, $framed, "hello\n", "oops\n", 0]; + yield 'TTY upgraded response' => [101, DockerRawStream::HEADER, true, "hello\n", "hello\n", '', 1]; + yield 'multiplexed plain response' => [200, DockerRawStream::MULTIPLEXED_HEADER.'; charset=binary', false, $framed, "hello\n", "oops\n", 0]; + } + + #[DataProvider('responseProvider')] + public function testReadsAttachResponse(int $status, string $contentType, bool $tty, string $body, string $stdout, string $stderr, int $inspections): void + { + $calls = 0; + $endpoint = new ContainerAttach('web', ['stream' => true], [], static function () use (&$calls, $tty): bool { + ++$calls; + + return $tty; + }); + $stream = $endpoint->parseResponse(new Response($status, ['Content-Type' => $contentType], $body), $this->createMock(SerializerInterface::class)); + + $this->assertInstanceOf(DockerRawStream::class, $stream); + $output = ['stdout' => '', 'stderr' => '']; + $stream->onStdout(static function (string $chunk) use (&$output): void { + $output['stdout'] .= $chunk; + }); + $stream->onStderr(static function (string $chunk) use (&$output): void { + $output['stderr'] .= $chunk; + }); + $stream->wait(); + + $this->assertSame(['stdout' => $stdout, 'stderr' => $stderr], $output); + $this->assertSame($inspections, $calls); + } + + public function testWithoutResolverKeepsFramedBehavior(): void + { + $stream = (new ContainerAttach('web'))->parseResponse( + new Response(200, ['Content-Type' => DockerRawStream::HEADER], pack('CxxxN', 1, 5).'hello'), + $this->createMock(SerializerInterface::class) + ); + $output = ''; + $stream->onStdout(static function (string $chunk) use (&$output): void { + $output .= $chunk; + }); + $stream->wait(); + + $this->assertSame('hello', $output); + } + + public function testWebsocketUpgradeReturnsWebsocketStream(): void + { + $socket = fopen('php://temp', 'w+'); + $stream = (new ContainerAttachWebsocket('web'))->parseResponse( + new Response(101, ['Upgrade' => 'WebSocket', 'Connection' => 'Upgrade'], $socket), + $this->createMock(SerializerInterface::class) + ); + + $this->assertInstanceOf(AttachWebsocketStream::class, $stream); + } + + public function testWebsocketWithoutUpgradeIsNotWrapped(): void + { + $stream = (new ContainerAttachWebsocket('web'))->parseResponse( + new Response(200, ['Content-Type' => DockerRawStream::HEADER], 'hello'), + $this->createMock(SerializerInterface::class) + ); + + $this->assertNotInstanceOf(AttachWebsocketStream::class, $stream); + } + + public function testWebsocketHandshakeKeyIsSixteenRandomBytes(): void + { + $key = (new ContainerAttachWebsocket('web'))->getExtraHeaders()['Sec-WebSocket-Key']; + + $this->assertSame(16, \strlen(base64_decode($key, true))); + $this->assertNotSame($key, (new ContainerAttachWebsocket('web'))->getExtraHeaders()['Sec-WebSocket-Key']); + } +} diff --git a/tests/Endpoint/ContainerLogsTest.php b/tests/Endpoint/ContainerLogsTest.php new file mode 100644 index 000000000..b2e58767f --- /dev/null +++ b/tests/Endpoint/ContainerLogsTest.php @@ -0,0 +1,85 @@ + [DockerRawStream::MULTIPLEXED_HEADER, $framed, false, 0]; + yield 'media type case and parameters' => ['Application/Vnd.Docker.Multiplexed-Stream; charset=binary', $framed, false, 0]; + yield 'legacy framed raw stream' => [DockerRawStream::HEADER, $framed, false, 1]; + yield 'TTY raw stream' => [DockerRawStream::HEADER, "hello\n", true, 1]; + yield 'TTY media type with parameters' => [DockerRawStream::HEADER.'; charset=utf-8', "hello\n", true, 1]; + } + + /** @dataProvider responseProvider */ + public function testReadsLogResponse(string $contentType, string $body, bool $tty, int $expectedInspections): void + { + $inspections = 0; + $endpoint = new ContainerLogs('test', ['stdout' => true], [], static function () use (&$inspections, $tty): bool { + ++$inspections; + + return $tty; + }); + $serializer = $this->createMock(SerializerInterface::class); + $serializer->expects(self::never())->method('deserialize'); + $response = new Response(200, ['Content-Type' => $contentType], $body); + $stream = $endpoint->parseResponse($response, $serializer); + + self::assertInstanceOf(DockerRawStream::class, $stream); + self::assertSame(0, $response->getBody()->tell(), 'Creating the wrapper must not consume the logs'); + $output = ''; + $stream->onStdout(static function (string $chunk) use (&$output): void { + $output .= $chunk; + }); + $stream->wait(); + + self::assertSame("hello\n", $output); + self::assertSame($expectedInspections, $inspections); + } + + public function testDirectEndpointKeepsLegacyFramedBehavior(): void + { + $endpoint = new ContainerLogs('test', ['stdout' => true]); + $stream = $endpoint->parseResponse( + new Response(200, ['Content-Type' => DockerRawStream::HEADER], pack('CxxxN', 1, 5).'hello'), + $this->createMock(SerializerInterface::class) + ); + $output = ''; + $stream->onStdout(static function (string $chunk) use (&$output): void { + $output .= $chunk; + }); + $stream->wait(); + + self::assertSame('hello', $output); + } + + public function testNotFoundResponseUsesGeneratedException(): void + { + $endpoint = new ContainerLogs('missing', ['stdout' => true], [], static function (): bool { + throw new \LogicException('An error response must not inspect the container'); + }); + + // From API 1.57 the generated exception carries the deserialized error. + $serializer = $this->createMock(SerializerInterface::class); + $serializer->method('deserialize')->willReturnCallback(static fn (mixed $data, string $type): object => new $type()); + + $this->expectException(ContainerLogsNotFoundException::class); + + $endpoint->parseResponse( + new Response(404, ['Content-Type' => 'application/json'], '{"message":"No such container: missing"}'), + $serializer + ); + } +} diff --git a/tests/Endpoint/ContainerStatsTest.php b/tests/Endpoint/ContainerStatsTest.php new file mode 100644 index 000000000..fb42aa437 --- /dev/null +++ b/tests/Endpoint/ContainerStatsTest.php @@ -0,0 +1,82 @@ + 'application/json']; + + public function testStreamsByDefaultWithoutReadingBody(): void + { + $response = new Response(200, self::JSON, "{\"read\":\"t1\"}\n{\"read\":\"t2\"}\n"); + + $stats = (new ContainerStats('web'))->parseResponse($response, $this->createMock(SerializerInterface::class)); + + $this->assertInstanceOf(StatsStream::class, $stats); + $this->assertSame(0, $response->getBody()->tell(), 'Creating the wrapper must not consume samples'); + } + + public function testReturnsOneSampleWhenStreamingIsOff(): void + { + $response = new Response(200, self::JSON, '{"read":"t1","memory_stats":{"usage":1}}'); + + $stats = (new ContainerStats('web', ['stream' => false]))->parseResponse($response, self::serializer()); + + $this->assertSame(1, self::memoryUsage($stats)); + } + + public function testStreamedSamplesMatchTheSingleSampleType(): void + { + $response = new Response(200, self::JSON, '{"read":"t1","memory_stats":{"usage":1}}{"read":"t2","memory_stats":{"usage":2}}'); + $single = (new ContainerStats('web', ['stream' => false]))->parseResponse(new Response(200, self::JSON, '{"read":"t0","memory_stats":{"usage":0}}'), self::serializer()); + $stream = (new ContainerStats('web'))->parseResponse($response, self::serializer()); + $samples = []; + $stream->onFrame(static function (object $sample) use (&$samples): void { + $samples[] = $sample; + }); + $stream->wait(); + + $this->assertSame([1, 2], array_map(self::memoryUsage(...), $samples)); + $this->assertSame($single::class, $samples[0]::class); + // API 1.48 added a generated stats model; earlier versions decode to stdClass. + $this->assertSame(class_exists('Docker\\API\\Model\\ContainerStatsResponse') ? 'Docker\\API\\Model\\ContainerStatsResponse' : \stdClass::class, $single::class); + } + + private static function serializer(): Serializer + { + return new Serializer( + [new ArrayDenormalizer(), new JaneObjectNormalizer()], + [new JsonEncoder(new JsonEncode(), new JsonDecode(['json_decode_associative' => true]))] + ); + } + + private static function memoryUsage(object $sample): int + { + return $sample instanceof \stdClass ? $sample->memory_stats->usage : $sample->getMemoryStats()->getUsage(); + } + + public function testMissingContainerStillThrows(): void + { + $serializer = $this->createMock(SerializerInterface::class); + $serializer->method('deserialize')->willReturn(new ErrorResponse()); + $this->expectException(ContainerStatsNotFoundException::class); + + (new ContainerStats('missing'))->parseResponse(new Response(404, self::JSON, '{"message":"No such container"}'), $serializer); + } +} diff --git a/tests/Endpoint/ExecStartTest.php b/tests/Endpoint/ExecStartTest.php new file mode 100644 index 000000000..c1747f59e --- /dev/null +++ b/tests/Endpoint/ExecStartTest.php @@ -0,0 +1,126 @@ + [200, DockerRawStream::HEADER, false, $framed, "hello\n", "error\n"]; + yield 'legacy upgraded non-TTY' => [101, DockerRawStream::HEADER, false, $framed, "hello\n", "error\n"]; + yield 'multiplexed non-TTY' => [200, DockerRawStream::MULTIPLEXED_HEADER, false, $framed, "hello\n", "error\n"]; + yield 'upgraded multiplexed non-TTY' => [101, DockerRawStream::MULTIPLEXED_HEADER, false, $framed, "hello\n", "error\n"]; + yield 'media type case and parameters' => [101, 'Application/Vnd.Docker.Multiplexed-Stream; charset=binary', false, $framed, "hello\n", "error\n"]; + yield 'TTY' => [200, DockerRawStream::HEADER, true, "hello\n", "hello\n", '']; + yield 'upgraded TTY' => [101, DockerRawStream::HEADER, true, "hello\n", "hello\n", '']; + yield 'TTY media type parameters' => [200, DockerRawStream::HEADER.'; charset=utf-8', true, "hello\n", "hello\n", '']; + yield 'TTY bytes resembling frames' => [200, DockerRawStream::HEADER, true, $framed, $framed, '']; + yield 'empty non-TTY' => [200, DockerRawStream::HEADER, false, '', '', '']; + yield 'empty TTY' => [101, DockerRawStream::HEADER, true, '', '', '']; + yield 'zero-length frame' => [101, DockerRawStream::MULTIPLEXED_HEADER, false, pack('CxxxN', 1, 0).$framed, "hello\n", "error\n"]; + yield 'omitted TTY defaults to framed' => [200, DockerRawStream::HEADER, null, $framed, "hello\n", "error\n"]; + } + + /** @dataProvider responseProvider */ + public function testReadsExecResponse(int $status, string $contentType, ?bool $tty, string $body, string $expectedStdout, string $expectedStderr): void + { + $config = new ExecIdStartPostBody(); + $config->setDetach(false); + if (null !== $tty) { + $config->setTty($tty); + } + $endpoint = new ExecStart('test', $config); + $serializer = $this->createMock(SerializerInterface::class); + $serializer->expects(self::never())->method('deserialize'); + $response = new Response($status, ['Content-Type' => $contentType], $body); + $stream = $endpoint->parseResponse($response, $serializer); + + self::assertInstanceOf(DockerRawStream::class, $stream); + self::assertSame(0, $response->getBody()->tell(), 'Wrapping must not consume the output'); + $stdout = ''; + $stderr = ''; + $stream->onStdout(static function (string $chunk) use (&$stdout): void { + $stdout .= $chunk; + }); + $stream->onStderr(static function (string $chunk) use (&$stderr): void { + $stderr .= $chunk; + }); + $stream->wait(); + + self::assertSame($expectedStdout, $stdout); + self::assertSame($expectedStderr, $stderr); + } + + public function testMissingRequestBodyKeepsFramedDefault(): void + { + $stream = (new ExecStart('test'))->parseResponse( + new Response(200, ['Content-Type' => DockerRawStream::HEADER], pack('CxxxN', 1, 5).'hello'), + $this->createMock(SerializerInterface::class) + ); + $output = ''; + $stream->onStdout(static function (string $chunk) use (&$output): void { + $output .= $chunk; + }); + $stream->wait(); + + self::assertSame('hello', $output); + } + + public static function nonStreamProvider(): iterable + { + yield 'detached' => [200, '', '']; + yield 'not found' => [404, 'application/json', '{"message":"No such exec"}']; + yield 'conflict' => [409, 'application/json', '{"message":"Container is not running"}']; + } + + /** @dataProvider nonStreamProvider */ + public function testNonStreamResponsesKeepGeneratedBehavior(int $status, string $contentType, string $body): void + { + $config = (new ExecIdStartPostBody())->setDetach(true); + // From API 1.57 the generated endpoint deserializes JSON error bodies. + $serializer = $this->createMock(SerializerInterface::class); + $serializer->method('deserialize')->willReturnCallback(static fn (mixed $data, string $type): object => new $type()); + $headers = '' === $contentType ? [] : ['Content-Type' => $contentType]; + $expected = self::outcome(static fn () => (new RawExecStart('test', $config))->parseResponse(new Response($status, $headers, $body), $serializer)); + + self::assertSame($expected, self::outcome(static fn () => (new ExecStart('test', $config))->parseResponse(new Response($status, $headers, $body), $serializer))); + } + + /** @return array{string, mixed} the return value, or the class of the exception thrown */ + private static function outcome(callable $parse): array + { + try { + return ['return', $parse()]; + } catch (\Throwable $exception) { + return ['throw', $exception::class]; + } + } + + public function testRawEndpointPreservesFrameHeaders(): void + { + $body = pack('CxxxN', 1, 6)."hello\n"; + $httpClient = $this->createMock(ClientInterface::class); + $httpClient->expects(self::exactly(2))->method('sendRequest')->willReturnOnConsecutiveCalls( + new Response(200, ['Content-Type' => 'application/json'], '{}'), + new Response(101, ['Content-Type' => DockerRawStream::MULTIPLEXED_HEADER], $body) + ); + $docker = Docker::create($httpClient, [], [], false); + $response = $docker->executeRawEndpoint(new ExecStart('test', (new ExecIdStartPostBody())->setTty(false))); + + self::assertSame(101, $response->getStatusCode()); + self::assertSame($body, $response->getBody()->getContents()); + } +} diff --git a/tests/Endpoint/ImageBuildTest.php b/tests/Endpoint/ImageBuildTest.php new file mode 100644 index 000000000..7d7760e6a --- /dev/null +++ b/tests/Endpoint/ImageBuildTest.php @@ -0,0 +1,38 @@ + ['app:latest', ['t=app%3Alatest']]; + yield 'several tags' => [['app:latest', 'app:1.0'], ['t=app%3Alatest', 't=app%3A1.0']]; + yield 'keyed tags' => [['a' => 'app:latest', 'b' => 'app:1.0'], ['t=app%3Alatest', 't=app%3A1.0']]; + yield 'no tags' => [[], []]; + } + + #[DataProvider('tagProvider')] + public function testRepeatsTagParameter(string|array $tags, array $expected): void + { + $query = (new ImageBuild(null, ['t' => $tags]))->getQueryString(); + $parameters = explode('&', $query); + + $this->assertSame($expected, array_values(array_filter($parameters, static fn (string $pair): bool => str_starts_with($pair, 't=')))); + $this->assertContains('dockerfile=Dockerfile', $parameters); + } + + public function testRejectsNonStringTags(): void + { + $this->expectException(InvalidOptionsException::class); + + (new ImageBuild(null, ['t' => ['app:latest', 1]]))->getQueryString(); + } +} diff --git a/tests/GeneratedNormalizerTest.php b/tests/GeneratedNormalizerTest.php new file mode 100644 index 000000000..2471ad9f2 --- /dev/null +++ b/tests/GeneratedNormalizerTest.php @@ -0,0 +1,115 @@ + true]))] + ); + } + + /** API 1.48 renamed the generated inspect response model. */ + private static function containerInspectModel(): string + { + return class_exists('Docker\\API\\Model\\ContainerInspectResponse') + ? 'Docker\\API\\Model\\ContainerInspectResponse' + : 'Docker\\API\\Model\\ContainersIdJsonGetResponse200'; + } + + public function testRenamedPackagesAreInstalledTogether(): void + { + self::assertTrue(InstalledVersions::isInstalled('docker-php/docker-php')); + self::assertTrue(InstalledVersions::isInstalled('docker-php/docker-php-api')); + self::assertFalse(InstalledVersions::isInstalled('beluga-php/docker-php')); + self::assertFalse(InstalledVersions::isInstalled('beluga-php/docker-php-api')); + foreach ([Docker::class => 'docker-php/docker-php', NetworkSettings::class => 'docker-php/docker-php-api'] as $class => $package) { + $path = realpath(InstalledVersions::getInstallPath($package)); + self::assertStringStartsWith($path.\DIRECTORY_SEPARATOR, (new \ReflectionClass($class))->getFileName()); + } + } + + public static function timestampProvider(): iterable + { + yield 'nanoseconds UTC' => ['2019-12-22T10:59:05.638593300Z', '2019-12-22T10:59:05.638593+00:00']; + yield 'localstack seven fractional digits' => ['2019-12-22T10:59:05.6385933Z', '2019-12-22T10:59:05.638593+00:00']; + yield 'microseconds with offset' => ['2019-12-22T10:59:05.638593+02:00', '2019-12-22T10:59:05.638593+02:00']; + yield 'seconds only' => ['2019-12-22T10:59:05Z', '2019-12-22T10:59:05.000000+00:00']; + } + + /** @dataProvider timestampProvider */ + public function testHealthcheckTimestamp(string $input, string $expected): void + { + $result = $this->serializer()->deserialize(json_encode(['Start' => $input], \JSON_THROW_ON_ERROR), HealthcheckResult::class, 'json'); + self::assertInstanceOf(\DateTimeInterface::class, $result->getStart()); + self::assertSame($expected, $result->getStart()->format('Y-m-d\TH:i:s.uP')); + } + + public function testMissingAndNullHealthcheckTimestamp(): void + { + $serializer = $this->serializer(); + self::assertFalse($serializer->deserialize('{}', HealthcheckResult::class, 'json')->isInitialized('start')); + $result = $serializer->deserialize('{"Start":null}', HealthcheckResult::class, 'json'); + self::assertTrue($result->isInitialized('start')); + self::assertNull($result->getStart()); + } + + public static function emptyObjectProvider(): iterable + { + yield 'array' => [[]]; + yield 'ArrayObject' => [new \ArrayObject()]; + yield 'stdClass' => [new \stdClass()]; + } + + /** @dataProvider emptyObjectProvider */ + public function testEmptyExposedPortsAndVolumesAreObjects(mixed $empty): void + { + $body = new ContainersCreatePostBody(); + $body->setImage('busybox:latest'); + $body->setExposedPorts(['80/tcp' => $empty, '53/udp' => $empty]); + $body->setVolumes(['/data' => $empty]); + $json = json_decode($this->serializer()->serialize($body, 'json'), false, 512, \JSON_THROW_ON_ERROR); + self::assertInstanceOf(\stdClass::class, $json->ExposedPorts->{'80/tcp'}); + self::assertInstanceOf(\stdClass::class, $json->ExposedPorts->{'53/udp'}); + self::assertInstanceOf(\stdClass::class, $json->Volumes->{'/data'}); + } + + public function testNullPortBindingsRoundTripThroughContainerInspect(): void + { + $payload = '{"Id":"example","NetworkSettings":{"Ports":{"80/tcp":[{"HostIp":"127.0.0.1","HostPort":"8080"}],"2377/tcp":null,"53/udp":[]}}}'; + $serializer = $this->serializer(); + $container = $serializer->deserialize($payload, self::containerInspectModel(), 'json'); + $ports = $container->getNetworkSettings()->getPorts(); + self::assertNull($ports['2377/tcp']); + self::assertSame([], $ports['53/udp']); + self::assertInstanceOf(PortBinding::class, $ports['80/tcp'][0]); + self::assertSame('8080', $ports['80/tcp'][0]->getHostPort()); + self::assertSame('127.0.0.1', $ports['80/tcp'][0]->getHostIp()); + self::assertSame(json_decode($payload, true), json_decode($serializer->serialize($container, 'json'), true)); + } + + public function testEmptyPortMapRemainsAnObject(): void + { + $serializer = $this->serializer(); + $settings = $serializer->deserialize('{"Ports":{}}', NetworkSettings::class, 'json'); + self::assertSame('{"Ports":{}}', $serializer->serialize($settings, 'json')); + } +} diff --git a/tests/GuzzleClientTest.php b/tests/GuzzleClientTest.php new file mode 100644 index 000000000..41c1ee291 --- /dev/null +++ b/tests/GuzzleClientTest.php @@ -0,0 +1,278 @@ + ['Guzzle Unix socket', 'unix'], + 'HTTP endpoint' => ['Guzzle Unix socket', 'http'], + 'Private CA' => ['Guzzle HTTPS', 'https'], + 'Mutual TLS' => ['Guzzle HTTPS', 'mutual-tls'], + ]; + } + + #[DataProvider('connectionExamples')] + public function testDocumentationExampleUsesConfiguredConnection(string $example, string $transport): void + { + $serverOptions = ['responses' => [$this->jsonResponse('{}'), $this->jsonResponse('[]')]]; + if ('https' === $transport || 'mutual-tls' === $transport) { + $this->createCertificates(); + $serverOptions['ssl'] = $this->serverTlsOptions(); + } + if ('mutual-tls' === $transport) { + $serverOptions['ssl'] += [ + 'verify_peer' => true, + 'verify_peer_name' => false, + 'cafile' => $this->directory.'/ca.pem', + 'capture_peer_cert' => true, + ]; + } + $address = $this->startServer($serverOptions, 'unix' === $transport); + + // A supplied client must not read the bundled factory's connection settings. + putenv('DOCKER_HOST=unix:///does-not-exist.sock'); + putenv('DOCKER_TLS_VERIFY=1'); + putenv('DOCKER_API_VERSION=v0.0'); + $docker = $this->runDocumentationExample($example, $transport, $address); + + $this->assertSame([], $docker->containerList()); + $this->assertStringStartsWith('GET /v'.DockerClientFactory::defaultApiVersion().'/info HTTP/1.1', $this->serverResult()['request']); + $request = $this->serverResult(1); + $this->assertStringStartsWith('GET /v'.DockerClientFactory::defaultApiVersion().'/containers/json?', $request['request']); + $host = 'unix' === $transport ? 'localhost' : $address; + $this->assertStringContainsString('Host: '.$host."\r\n", $request['request']); + if ('mutual-tls' === $transport) { + $this->assertSame('docker-client', $request['peer']); + } + } + + public function testHttpsRejectsUntrustedCertificate(): void + { + $this->createCertificates(); + $address = $this->startServer(['ssl' => $this->serverTlsOptions()]); + + $this->assertCertificateRejected('https://'.$address); + } + + public function testHttpsRejectsWrongHostname(): void + { + $this->createCertificates('DNS:not-docker.test'); + $address = $this->startServer(['ssl' => $this->serverTlsOptions()]); + + $this->assertCertificateRejected('https://'.$address, ['verify' => $this->directory.'/ca.pem']); + } + + public function testMutualTlsRejectsMissingClientCertificate(): void + { + $this->createCertificates(); + $address = $this->startServer(['ssl' => $this->serverTlsOptions() + [ + 'verify_peer' => true, + 'verify_peer_name' => false, + 'cafile' => $this->directory.'/ca.pem', + ]]); + $this->expectException(GuzzleException::class); + + Docker::create($this->guzzle('https://'.$address, ['verify' => $this->directory.'/ca.pem'])); + } + + public function testRequestBodyReachesDaemon(): void + { + $address = $this->startServer(['responses' => [ + $this->jsonResponse('{}'), + $this->jsonResponse('{"Id":"created","Warnings":[]}', 201), + ]]); + $docker = Docker::create($this->guzzle('http://'.$address)); + $body = new ContainersCreatePostBody(); + $body->setImage('busybox:latest'); + $body->setEnv(['MODE=test']); + + $this->assertSame('created', $docker->containerCreate($body)->getId()); + $request = $this->serverResult(1); + [$method, $uri] = explode(' ', $request['request'], 3); + $this->assertSame('POST', $method); + $this->assertSame('/v'.DockerClientFactory::defaultApiVersion().'/containers/create', parse_url($uri, \PHP_URL_PATH)); + $json = json_decode($request['body'], true, 512, \JSON_THROW_ON_ERROR); + $this->assertSame('busybox:latest', $json['Image']); + $this->assertSame(['MODE=test'], $json['Env']); + } + + public function testApiErrorUsesGeneratedException(): void + { + $address = $this->startServer(['responses' => [ + $this->jsonResponse('{}'), + $this->jsonResponse('{"message":"No such container: missing"}', 404), + ]]); + $docker = Docker::create($this->guzzle('http://'.$address)); + $this->expectException(ContainerInspectNotFoundException::class); + + $docker->containerInspect('missing'); + } + + public function testCompletedLogResponseDecodesStdoutAndStderr(): void + { + $frames = pack('CxxxN', 1, 6)."hello\n".pack('CxxxN', 2, 5)."warn\n"; + $address = $this->startServer(['responses' => [ + $this->jsonResponse('{}'), + ['body_base64' => base64_encode($frames), 'headers' => ['Content-Type' => DockerRawStream::MULTIPLEXED_HEADER]], + ]]); + $docker = Docker::create($this->guzzle('http://'.$address)); + $logs = $docker->containerLogs('test', ['stdout' => true, 'stderr' => true]); + $stdout = ''; + $stderr = ''; + $logs->onStdout(static function (string $chunk) use (&$stdout): void { + $stdout .= $chunk; + }); + $logs->onStderr(static function (string $chunk) use (&$stderr): void { + $stderr .= $chunk; + }); + $logs->wait(); + + $this->assertSame("hello\n", $stdout); + $this->assertSame("warn\n", $stderr); + $this->assertStringContainsString('/v'.DockerClientFactory::defaultApiVersion().'/containers/test/logs?', $this->serverResult(1)['request']); + } + + public function testExplicitCurlHandlerBuffersDespiteStreamOption(): void + { + $address = $this->startServer(['negotiation' => false]); + $client = new PluginClient($this->guzzle('http://'.$address, ['stream' => true])); + $response = $client->sendRequest(new Request('GET', '/_ping')); + + $this->assertTrue($response->getBody()->isSeekable()); + $this->assertSame('php://temp', $response->getBody()->getMetadata('uri')); + $this->assertSame('OK', $response->getBody()->getContents()); + $this->assertStringStartsWith('GET /_ping HTTP/1.1', $this->serverResult()['request']); + } + + public function testDefaultStreamingHandlerReadsIncrementally(): void + { + if (!\ini_get('allow_url_fopen')) { + $this->markTestSkipped('The default PHP stream handler requires allow_url_fopen.'); + } + $address = $this->startServer(['negotiation' => false]); + $client = new PluginClient(new GuzzleClient([ + 'base_uri' => 'http://'.$address, + 'stream' => true, + 'proxy' => '', + 'timeout' => 3, + ])); + $response = $client->sendRequest(new Request('GET', '/_ping')); + + $this->assertFalse($response->getBody()->isSeekable()); + $this->assertSame('http', $response->getBody()->getMetadata('wrapper_type')); + $this->assertSame('OK', $response->getBody()->getContents()); + $this->assertStringContainsString('Host: '.$address."\r\n", $this->serverResult()['request']); + } + + public function testDefaultStreamingHandlerDoesNotUseCurlSocketOption(): void + { + if (!\ini_get('allow_url_fopen')) { + $this->markTestSkipped('The default PHP stream handler requires allow_url_fopen.'); + } + $options = [ + 'stream' => true, + 'curl' => [\CURLOPT_UNIX_SOCKET_PATH => $this->directory.'/does-not-exist.sock'], + 'proxy' => '', + 'timeout' => 3, + ]; + + if (ClientInterface::MAJOR_VERSION >= 8) { + // Guzzle 8 rejects cURL-only options on the stream handler. + $client = new PluginClient(new GuzzleClient($options + ['base_uri' => 'http://localhost'])); + $this->expectException(GuzzleInvalidArgumentException::class); + $client->sendRequest(new Request('GET', '/_ping')); + + return; + } + + // Guzzle 7 ignores them and connects to base_uri instead of the socket. + $address = $this->startServer(['negotiation' => false]); + $client = new PluginClient(new GuzzleClient($options + ['base_uri' => 'http://'.$address])); + $response = $client->sendRequest(new Request('GET', '/_ping')); + + $this->assertSame('OK', $response->getBody()->getContents()); + $this->assertStringContainsString('Host: '.$address."\r\n", $this->serverResult()['request']); + } + + private function guzzle(string $url, array $options = []): GuzzleClient + { + return new GuzzleClient($options + [ + 'base_uri' => $url, + 'handler' => HandlerStack::create(new CurlHandler()), + 'proxy' => '', + 'timeout' => 3, + ]); + } + + private function jsonResponse(string $body, int $status = 200): array + { + return ['status' => $status, 'body' => $body, 'headers' => ['Content-Type' => 'application/json']]; + } + + private function assertCertificateRejected(string $url, array $options = []): void + { + // Guzzle 8 removed the exception handler context; transfer stats report the cURL errno in both majors. + $errno = null; + $client = $this->guzzle($url, $options + [ + 'on_stats' => static function (TransferStats $stats) use (&$errno): void { + $errno = $stats->getHandlerErrorData(); + }, + ]); + + try { + Docker::create($client); + $this->fail('The server certificate should have been rejected.'); + } catch (GuzzleException) { + $this->assertSame(\CURLE_SSL_CACERT, $errno); + } + } + + private function runDocumentationExample(string $title, string $transport, string $address): Docker + { + $markdown = file_get_contents(\dirname(__DIR__).'/docs/guides/guzzle.mdx'); + preg_match_all('/^```php ([^\r\n]+)\R(.*?)^```/ms', $markdown, $blocks); + $examples = array_combine($blocks[1], $blocks[2]); + $this->assertArrayHasKey($title, $examples); + $code = preg_replace('/^\s*<\?php\s*/', '', $examples[$title]); + $code = str_replace("require __DIR__ . '/vendor/autoload.php';", '', $code); + // Exercise the HTTP and CA-only variations described below the examples. + if ('http' === $transport) { + $code = preg_replace("/ 'curl' => \\[\\R.*? \\],\\R/s", '', $code); + $code = str_replace("'http://localhost'", "'http://docker.example.com:2375'", $code); + } + if ('https' === $transport) { + $code = preg_replace("/^ '(cert|ssl_key)' => [^\\r\\n]+\\R/m", '', $code); + } + $code = strtr($code, [ + '/run/custom/docker.sock' => $address, + 'http://docker.example.com:2375' => 'http://'.$address, + 'https://docker.example.com:2376' => 'https://'.$address, + '/path/to/ca.pem' => $this->directory.'/ca.pem', + '/path/to/cert.pem' => $this->directory.'/cert.pem', + '/path/to/key.pem' => $this->directory.'/key.pem', + ]); + + return (static fn (string $code): Docker => eval("namespace {\n".$code."\nreturn \$docker;\n}"))($code); + } +} diff --git a/tests/Http/ApiVersionNegotiationPluginTest.php b/tests/Http/ApiVersionNegotiationPluginTest.php new file mode 100644 index 000000000..120638f3a --- /dev/null +++ b/tests/Http/ApiVersionNegotiationPluginTest.php @@ -0,0 +1,94 @@ + [new Response(200, ['API-Version' => '1.43'], 'OK'), '/v1.43/containers/json']; + yield 'newer daemon' => [new Response(200, ['API-Version' => '1.60'], 'OK'), '/v1.56/containers/json']; + yield 'same version' => [new Response(200, ['API-Version' => '1.56'], 'OK'), '/v1.56/containers/json']; + yield 'no version header' => [new Response(200, [], 'OK'), '/v1.56/containers/json']; + yield 'invalid version header' => [new Response(200, ['API-Version' => 'latest'], 'OK'), '/v1.56/containers/json']; + yield 'ping rejected' => [new Response(403, [], 'Forbidden'), '/v1.56/containers/json']; + } + + #[DataProvider('versionProvider')] + public function testUsesTheLowerVersionAndPingsOnce(ResponseInterface $ping, string $expectedPath): void + { + $transport = $this->transport(static fn (RequestInterface $request): ResponseInterface => '/_ping' === $request->getUri()->getPath() ? $ping : new Response(200, [], '[]')); + $client = $this->client($transport); + + $client->sendRequest(new Request('GET', '/containers/json')); + $client->sendRequest(new Request('GET', '/containers/json')); + + $this->assertSame(['/_ping', $expectedPath, $expectedPath], $transport->paths); + } + + public function testConnectionErrorsPropagateAndAreNotRemembered(): void + { + $failures = 1; + $transport = $this->transport(static function (RequestInterface $request) use (&$failures): ResponseInterface { + if ($failures-- > 0) { + throw new class('Connection refused', 0) extends \RuntimeException implements NetworkExceptionInterface { + public function getRequest(): RequestInterface + { + return new Request('GET', '/_ping'); + } + }; + } + + return '/_ping' === $request->getUri()->getPath() ? new Response(200, ['API-Version' => '1.44'], 'OK') : new Response(200, [], '[]'); + }); + $client = $this->client($transport); + + try { + $client->sendRequest(new Request('GET', '/containers/json')); + $this->fail('The ping connection error should propagate.'); + } catch (NetworkExceptionInterface) { + } + $client->sendRequest(new Request('GET', '/containers/json')); + + $this->assertSame(['/_ping', '/_ping', '/v1.44/containers/json'], $transport->paths); + } + + private function client(ClientInterface $transport): PluginClient + { + $factory = new Psr17Factory(); + + return new PluginClient($transport, [new ApiVersionNegotiationPlugin('1.56', $factory, $factory)]); + } + + private function transport(\Closure $respond): ClientInterface + { + return new class($respond) implements ClientInterface { + public array $paths = []; + + public function __construct(private \Closure $respond) + { + } + + public function sendRequest(RequestInterface $request): ResponseInterface + { + $this->paths[] = $request->getUri()->getPath(); + + return ($this->respond)($request); + } + }; + } +} diff --git a/tests/Http/StreamingDecoderPluginTest.php b/tests/Http/StreamingDecoderPluginTest.php new file mode 100644 index 000000000..95eb59a30 --- /dev/null +++ b/tests/Http/StreamingDecoderPluginTest.php @@ -0,0 +1,108 @@ + new FulfilledPromise($response); + + return (new StreamingDecoderPlugin($config))->handleRequest(new Request('GET', 'http://localhost/_ping'), $next, $next)->wait(); + } + + public static function encodings(): iterable + { + yield 'chunked' => ['chunked']; + yield 'case insensitive' => ['CHUNKED']; + yield 'whitespace' => [' chunked ']; + } + + #[DataProvider('encodings')] + public function testChunkedResponseUsesIncrementalDecoder(string $encoding): void + { + $response = $this->decode(new Response(200, ['Transfer-Encoding' => $encoding], "5\r\nhello\r\n0\r\n\r\n")); + + self::assertInstanceOf(DechunkStream::class, $response->getBody()); + self::assertFalse($response->hasHeader('Transfer-Encoding')); + self::assertSame('hello', $response->getBody()->getContents()); + } + + public static function unencodedResponses(): iterable + { + yield 'ordinary JSON' => [200, ['Content-Type' => 'application/json'], '{"ok":true}']; + yield 'upgraded stream' => [101, ['Connection' => 'Upgrade', 'Upgrade' => 'tcp'], "\x00raw\r\n"]; + yield 'unknown transfer encoding' => [200, ['Transfer-Encoding' => 'custom'], 'unchanged']; + } + + #[DataProvider('unencodedResponses')] + public function testUnencodedResponseIsNotChanged(int $status, array $headers, string $body): void + { + $response = new Response($status, $headers, $body); + + $decoded = $this->decode($response); + self::assertSame($response->getStatusCode(), $decoded->getStatusCode()); + self::assertSame($response->getHeaders(), $decoded->getHeaders()); + self::assertSame($response->getBody(), $decoded->getBody()); + self::assertSame($body, $response->getBody()->getContents()); + } + + public static function compression(): iterable + { + yield 'gzip' => ['gzip', false]; + yield 'chunked gzip' => ['gzip', true]; + yield 'deflate' => ['deflate', false]; + yield 'chunked deflate' => ['deflate', true]; + } + + #[DataProvider('compression')] + public function testRetainsContentDecoding(string $encoding, bool $chunked): void + { + $body = 'compressed response'; + $encoded = 'gzip' === $encoding ? gzencode($body) : gzcompress($body); + $headers = ['Content-Encoding' => $encoding]; + if ($chunked) { + $encoded = dechex(\strlen($encoded))."\r\n".$encoded."\r\n0\r\n\r\n"; + $headers['Transfer-Encoding'] = 'chunked'; + } + $response = $this->decode(new Response(200, $headers, $encoded)); + + self::assertSame($body, $response->getBody()->getContents()); + self::assertFalse($response->hasHeader('Content-Encoding')); + self::assertFalse($response->hasHeader('Transfer-Encoding')); + } + + public function testContentDecodingCanStillBeDisabled(): void + { + $encoded = gzencode('compressed response'); + $response = $this->decode(new Response(200, ['Content-Encoding' => 'gzip', 'Transfer-Encoding' => 'chunked'], dechex(\strlen($encoded))."\r\n".$encoded."\r\n0\r\n\r\n"), ['use_content_encoding' => false]); + + self::assertSame($encoded, $response->getBody()->getContents()); + self::assertSame('gzip', $response->getHeaderLine('Content-Encoding')); + self::assertFalse($response->hasHeader('Transfer-Encoding')); + } + + public function testPreservesRequestEncodingNegotiation(): void + { + $next = static function (RequestInterface $request): FulfilledPromise { + self::assertSame(['gzip', 'deflate'], $request->getHeader('Accept-Encoding')); + self::assertSame(['gzip', 'deflate', 'chunked'], $request->getHeader('TE')); + + return new FulfilledPromise(new Response()); + }; + + (new StreamingDecoderPlugin())->handleRequest(new Request('GET', 'http://localhost/_ping'), $next, $next)->wait(); + } +} diff --git a/tests/HttpClientDocumentationTest.php b/tests/HttpClientDocumentationTest.php new file mode 100644 index 000000000..bb8bf6013 --- /dev/null +++ b/tests/HttpClientDocumentationTest.php @@ -0,0 +1,72 @@ + ['guides/guzzle.mdx', 'Default socket', true]; + yield 'Bundled custom socket' => ['guides/guzzle.mdx', 'Bundled custom socket', false]; + yield 'Custom socket client' => ['reference/streams.mdx', 'Custom socket client', false]; + } + + #[DataProvider('socketExamples')] + public function testDocumentedSocketClientStreamsTtyOutput(string $page, string $title, bool $useEnvironment): void + { + $address = $this->startServer(['responses' => [ + ['body' => '{}', 'headers' => ['Content-Type' => 'application/json']], + [ + 'headers' => ['Transfer-Encoding' => 'chunked', 'Content-Type' => 'application/vnd.docker.raw-stream'], + 'segments_base64' => [ + base64_encode("7\r\nfirst\r\n\r\n"), + base64_encode("6\r\nlast\r\n\r\n0\r\n\r\n"), + ], + 'delay_ms' => 1000, + ], + ]], true); + putenv('DOCKER_HOST=unix://'.($useEnvironment ? $address : '/does-not-exist.sock')); + $docker = $this->runDocumentationExample($page, $title, $address); + $start = new ExecIdStartPostBody(); + $start->setDetach(false); + $start->setTty(true); + $stream = $docker->execStart('test', $start); + $stdout = ''; + $firstCallback = null; + $lastCallback = null; + $stream->onStdout(static function (string $output) use (&$stdout, &$firstCallback, &$lastCallback): void { + $firstCallback ??= hrtime(true); + $lastCallback = hrtime(true); + $stdout .= $output; + }); + $stream->wait(); + + self::assertSame("first\r\nlast\r\n", $stdout); + self::assertNotNull($firstCallback); + self::assertGreaterThan(500_000_000, $lastCallback - $firstCallback, 'Output was buffered until the peer finished.'); + self::assertStringStartsWith('GET /v'.DockerClientFactory::defaultApiVersion().'/info HTTP/1.1', $this->serverResult()['request']); + $request = $this->serverResult(1)['request']; + self::assertStringStartsWith('POST /v'.DockerClientFactory::defaultApiVersion().'/exec/test/start HTTP/1.1', $request); + self::assertStringContainsString('Host: localhost', $request); + } + + private function runDocumentationExample(string $page, string $title, string $address): Docker + { + $markdown = file_get_contents(\dirname(__DIR__).'/docs/'.$page); + preg_match_all('/^```php ([^\r\n]+)\R(.*?)^```/ms', $markdown, $blocks); + $examples = array_combine($blocks[1], $blocks[2]); + self::assertArrayHasKey($title, $examples); + $code = preg_replace('/^\s*<\?php\s*/', '', $examples[$title]); + $code = str_replace("require __DIR__ . '/vendor/autoload.php';", '', $code); + $code = str_replace('/run/custom/docker.sock', $address, $code); + + return (static fn (string $code): Docker => eval("namespace {\n".$code."\nreturn \$docker;\n}"))($code); + } +} diff --git a/tests/InteractiveExecTransportTest.php b/tests/InteractiveExecTransportTest.php new file mode 100644 index 000000000..a4253211c --- /dev/null +++ b/tests/InteractiveExecTransportTest.php @@ -0,0 +1,108 @@ + [$scheme, $tty]; + } + } + } + + #[DataProvider('transports')] + public function testBidirectionalOutputAndHalfClose(string $scheme, bool $tty): void + { + $serverConfig = ['tty' => $tty, 'input_length' => 9 * 16384]; + $config = ['timeout' => 3000, 'api_version' => '1.45']; + if ('https' === $scheme) { + $this->createCertificates(); + $serverConfig['ssl'] = $this->serverTlsOptions(); + $config['stream_context_options']['ssl']['cafile'] = $this->directory.'/ca.pem'; + } + $address = $this->startServer($serverConfig, 'unix' === $scheme, 'interactive-server.php'); + $config['remote_socket'] = $scheme.'://'.$address; + putenv('DOCKER_API_VERSION=1.52'); + $docker = Docker::create(DockerClientFactory::createInteractive($config), [], [], false); + $body = new ExecIdStartPostBody(); + $body->setTty($tty); + $session = $docker->execStartInteractive('test', $body, 5000); + $payload = str_repeat("binary\0\xff\n", 16384); + $stdout = $stderr = ''; + $session->onStdout(static function (string $chunk) use (&$stdout): void { $stdout .= $chunk; }); + $session->onStderr(static function (string $chunk) use (&$stderr): void { $stderr .= $chunk; }); + self::assertTrue($session->poll(100)); + self::assertSame('ready:', $stdout, 'Buffered bytes sent with the HTTP headers were lost.'); + $offset = 0; + while ($offset < \strlen($payload)) { + $offset += $session->writeStdin(substr($payload, $offset)); + $session->poll(1); + } + if (!$tty) { + $session->closeStdin(); + } + $session->wait(); + self::assertSame('ready:'.$payload.':done'.($tty ? 'error' : ''), $stdout); + self::assertSame($tty ? '' : 'error', $stderr); + $request = $this->serverResult(1); + self::assertSame(\strlen($payload), $request['stdin_length']); + self::assertSame(hash('sha256', $payload), $request['stdin_hash']); + self::assertStringStartsWith('POST /v1.45/exec/test/start HTTP/1.1', $request['request']); + self::assertStringContainsString("Upgrade: tcp\r\n", $request['request']); + self::assertSame(['Detach' => false, 'Tty' => $tty], json_decode($request['body'], true)); + self::assertNull($body->getDetach(), 'The caller model was mutated.'); + } + + public function testCustomHttpClientFailsBeforeStartingExec(): void + { + $http = new class() implements \Psr\Http\Client\ClientInterface { + public int $requests = 0; + + public function sendRequest(\Psr\Http\Message\RequestInterface $request): \Psr\Http\Message\ResponseInterface + { + ++$this->requests; + + return new \Nyholm\Psr7\Response(200, ['Content-Type' => 'application/json'], '{}'); + } + }; + $docker = Docker::create($http, [], [], false); + try { + $docker->execStartInteractive('test'); + self::fail('Unsupported transport was accepted.'); + } catch (\LogicException $expected) { + self::assertSame(1, $http->requests); + } + } + + public function testDetachedExecIsRejectedBeforeTheRequest(): void + { + $address = $this->startServer(['responses' => [['body' => '{}']]], true); + $docker = Docker::create(DockerClientFactory::createInteractive(['remote_socket' => 'unix://'.$address]), [], [], false); + $body = new ExecIdStartPostBody(); + $body->setDetach(true); + $this->expectException(\InvalidArgumentException::class); + $docker->execStartInteractive('test', $body); + } + + public function testARegularHttpResponseIsNotTreatedAsAnInteractiveSession(): void + { + $address = $this->startServer(['responses' => [ + ['body' => '{}'], + ['status' => 409, 'body' => '{"message":"fixture conflict"}', 'headers' => ['Content-Type' => 'application/json']], + ]], true); + $docker = Docker::create(DockerClientFactory::createInteractive(['remote_socket' => 'unix://'.$address]), [], [], false); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('HTTP 409'); + $docker->execStartInteractive('test'); + } +} diff --git a/tests/Resource/ContainerResourceTest.php b/tests/Resource/ContainerResourceTest.php index d89f3ada9..48748439f 100644 --- a/tests/Resource/ContainerResourceTest.php +++ b/tests/Resource/ContainerResourceTest.php @@ -6,6 +6,7 @@ use Docker\API\Model\ContainersCreatePostBody; use Docker\Docker; +use Docker\Stream\AttachWebsocketStream; use Docker\Stream\DockerRawStream; use Docker\Tests\TestCase; @@ -24,9 +25,10 @@ private function getManager() */ public static function setUpBeforeClass(): void { + // The pull only runs while its progress stream is read. self::getDocker()->imageCreate('', [ 'fromImage' => 'busybox:latest', - ]); + ])->wait(); } public function testAttach(): void @@ -35,13 +37,16 @@ public function testAttach(): void $containerConfig->setImage('busybox:latest'); $containerConfig->setCmd(['echo', '-n', 'output']); $containerConfig->setAttachStdout(true); - $containerConfig->setLabels(new \ArrayObject(['docker-php-test' => 'true'])); + $containerConfig->setLabels(['docker-php-test' => 'true']); $containerCreateResult = $this->getManager()->containerCreate($containerConfig); - $dockerRawStream = $this->getManager()->containerAttach($containerCreateResult->getId(), [ - 'stream' => true, - 'stdout' => true, - ]); + $dockerRawStream = $this->getManager()->containerAttach( + $containerCreateResult->getId(), + [ + 'stream' => true, + 'stdout' => true, + ] + ); $stdoutFull = ''; $dockerRawStream->onStdout(function ($stdout) use (&$stdoutFull): void { @@ -56,68 +61,130 @@ public function testAttach(): void $this->assertSame('output', $stdoutFull); } + public function testAttachTty(): void + { + $containerConfig = new ContainersCreatePostBody(); + $containerConfig->setImage('busybox:latest'); + $containerConfig->setCmd(['sh', '-c', 'printf stdout; printf stderr >&2']); + $containerConfig->setTty(true); + $containerConfig->setAttachStdout(true); + $containerConfig->setAttachStderr(true); + $containerConfig->setLabels(['docker-php-test' => 'true']); + $id = $this->getManager()->containerCreate($containerConfig)->getId(); + + try { + $stream = $this->getManager()->containerAttach($id, ['stream' => true, 'stdout' => true, 'stderr' => true]); + $output = ''; + $stream->onStdout(static function (string $chunk) use (&$output): void { + $output .= $chunk; + }); + $this->getManager()->containerStart($id); + $this->getManager()->containerWait($id); + $stream->wait(); + + $this->assertSame('stdoutstderr', $output); + } finally { + $this->getManager()->containerDelete($id, ['force' => true]); + } + } + public function testAttachWebsocket(): void { + $operatingSystem = (string) $this->getManager()->systemInfo()->getOperatingSystem(); + if (str_contains($operatingSystem, 'Docker Desktop')) { + $this->markTestSkipped('Docker Desktop\'s socket proxy does not forward WebSocket attach output.'); + } + $containerConfig = new ContainersCreatePostBody(); $containerConfig->setImage('busybox:latest'); $containerConfig->setCmd(['sh']); + $containerConfig->setAttachStdin(true); $containerConfig->setAttachStdout(true); $containerConfig->setAttachStderr(true); - $containerConfig->setAttachStdin(false); $containerConfig->setOpenStdin(true); $containerConfig->setTty(true); - $containerConfig->setLabels(new \ArrayObject(['docker-php-test' => 'true'])); - - $containerCreateResult = $this->getManager()->containerCreate($containerConfig); - $webSocketStream = $this->getManager()->containerAttachWebsocket($containerCreateResult->getId(), [ - 'stream' => true, - 'stdout' => true, - 'stderr' => true, - 'stdin' => true, - ]); - - $this->getManager()->containerStart($containerCreateResult->getId()); - - // Read the bash first line - $webSocketStream->read(); - - // No output after that so it should be false - $this->assertFalse($webSocketStream->read()); - - // Write something to the container - $webSocketStream->write("echo test\n"); - - // Test for echo present (stdin) - $output = ''; - - while (false !== ($data = $webSocketStream->read())) { - $output .= $data; + $containerConfig->setLabels(['docker-php-test' => 'true']); + $id = $this->getManager()->containerCreate($containerConfig)->getId(); + + try { + $webSocketStream = $this->getManager()->containerAttachWebsocket($id, [ + 'stream' => true, + 'stdout' => true, + 'stderr' => true, + 'stdin' => true, + ]); + $this->assertInstanceOf(AttachWebsocketStream::class, $webSocketStream); + $this->getManager()->containerStart($id); + + $webSocketStream->write("echo docker-php-\$((40 + 2))\n"); + $output = ''; + $deadline = microtime(true) + 10; + while (!str_contains($output, 'docker-php-42') && microtime(true) < $deadline) { + $data = $webSocketStream->read(0, 200000); + $this->assertNotNull($data, 'The WebSocket closed before the command output arrived.'); + $output .= (string) $data; + } + $this->assertStringContainsString('docker-php-42', $output); + + $webSocketStream->write("exit\n"); + $deadline = microtime(true) + 10; + while (null !== $webSocketStream->read(0, 200000) && microtime(true) < $deadline) { + } + $this->assertNull($webSocketStream->read(), 'The WebSocket should close when the shell exits.'); + } finally { + $this->getManager()->containerDelete($id, ['force' => true]); } + } - $this->assertContains('echo', $output); - - // Exit the container - $webSocketStream->write("exit\n"); + public static function logsProvider(): iterable + { + yield 'separate stdout and stderr' => [false, 'printf stdout; printf stderr >&2', 'stdout', 'stderr']; + yield 'TTY combines stdout and stderr' => [true, 'printf stdout; printf stderr >&2', 'stdoutstderr', '']; + yield 'empty non-TTY logs' => [false, 'true', '', '']; + yield 'empty TTY logs' => [true, 'true', '', '']; } - public function testLogs(): void + /** @dataProvider logsProvider */ + public function testLogs(bool $tty, string $command, string $expectedStdout, string $expectedStderr): void { $containerConfig = new ContainersCreatePostBody(); $containerConfig->setImage('busybox:latest'); - $containerConfig->setCmd(['echo', '-n', 'output']); + $containerConfig->setCmd(['sh', '-c', $command]); $containerConfig->setAttachStdout(true); - $containerConfig->setLabels(new \ArrayObject(['docker-php-test' => 'true'])); + $containerConfig->setAttachStderr(true); + $containerConfig->setTty($tty); + $containerConfig->setLabels(['docker-php-test' => 'true']); $containerCreateResult = $this->getManager()->containerCreate($containerConfig); - $this->getManager()->containerStart($containerCreateResult->getId()); - $this->getManager()->containerWait($containerCreateResult->getId()); - - $logsStream = $this->getManager()->containerLogs($containerCreateResult->getId(), [ - 'stdout' => true, - 'stderr' => true, - ], Docker::FETCH_OBJECT); - - self::assertInstanceOf(DockerRawStream::class, $logsStream); + try { + $this->getManager()->containerStart($containerCreateResult->getId()); + $this->getManager()->containerWait($containerCreateResult->getId()); + + $logsStream = $this->getManager()->containerLogs( + $containerCreateResult->getId(), + [ + 'stdout' => true, + 'stderr' => true, + ], + Docker::FETCH_OBJECT + ); + + self::assertInstanceOf(DockerRawStream::class, $logsStream); + $stdout = ''; + $stderr = ''; + $logsStream->onStdout(static function (string $output) use (&$stdout): void { + $stdout .= $output; + }); + $logsStream->onStderr(static function (string $output) use (&$stderr): void { + $stderr .= $output; + }); + $logsStream->wait(); + + self::assertSame($expectedStdout, $stdout); + self::assertSame($expectedStderr, $stderr); + } finally { + $this->getManager()->containerDelete($containerCreateResult->getId(), ['force' => true]); + } } } diff --git a/tests/Resource/ExecResourceTest.php b/tests/Resource/ExecResourceTest.php index 65064f2b5..a1c58a9d8 100644 --- a/tests/Resource/ExecResourceTest.php +++ b/tests/Resource/ExecResourceTest.php @@ -8,8 +8,13 @@ use Docker\API\Model\ContainersIdExecPostBody; use Docker\API\Model\ExecIdJsonGetResponse200; use Docker\API\Model\ExecIdStartPostBody; +use Docker\Docker; use Docker\Stream\DockerRawStream; use Docker\Tests\TestCase; +use Http\Client\Common\Plugin; +use Http\Promise\Promise; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; class ExecResourceTest extends TestCase { @@ -21,36 +26,82 @@ private function getManager() return self::getDocker(); } - public function testStartStream(): void + public static function streamProvider(): iterable { - $createContainerResult = $this->createContainer(); - - $execConfig = new ContainersIdExecPostBody(); - $execConfig->setAttachStdout(true); - $execConfig->setAttachStderr(true); - $execConfig->setCmd(['echo', 'output']); - - $execCreateResult = $this->getManager()->containerExec($createContainerResult->getId(), $execConfig); - - $execStartConfig = new ExecIdStartPostBody(); - $execStartConfig->setDetach(false); - $execStartConfig->setTty(false); - - $stream = $this->getManager()->execStart($execCreateResult->getId(), $execStartConfig); - - $this->assertInstanceOf(DockerRawStream::class, $stream); - - $stdoutFull = ''; - $stream->onStdout(function ($stdout) use (&$stdoutFull): void { - $stdoutFull .= $stdout; - }); - $stream->wait(); - - $this->assertSame("output\n", $stdoutFull); + foreach ([false, true] as $upgrade) { + foreach ([false, true] as $tty) { + foreach ([false, true] as $empty) { + yield sprintf('upgrade=%d tty=%d empty=%d', $upgrade, $tty, $empty) => [$upgrade, $tty, $empty]; + } + } + } + } - self::getDocker()->containerKill($createContainerResult->getId(), [ - 'signal' => 'SIGKILL', - ]); + /** @dataProvider streamProvider */ + public function testStartStream(bool $upgrade, bool $tty, bool $empty): void + { + $createContainerResult = $this->createContainer(); + try { + $execConfig = new ContainersIdExecPostBody(); + $execConfig->setAttachStdout(true); + $execConfig->setAttachStderr(true); + $execConfig->setTty($tty); + $execConfig->setCmd($empty ? ['true'] : ['sh', '-c', 'printf stdout; printf stderr >&2']); + + $execCreateResult = $this->getManager()->containerExec($createContainerResult->getId(), $execConfig); + + $execStartConfig = new ExecIdStartPostBody(); + $execStartConfig->setDetach(false); + $execStartConfig->setTty($tty); + $capture = new class($upgrade) implements Plugin { + public ?int $status = null; + + public function __construct(private bool $upgrade) + { + } + + public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise + { + if (!preg_match('#/exec/[^/]+/start$#', $request->getUri()->getPath())) { + return $next($request); + } + if ($this->upgrade) { + $request = $request->withHeader('Connection', 'Upgrade')->withHeader('Upgrade', 'tcp'); + } + + return $next($request)->then(function (ResponseInterface $response): ResponseInterface { + $this->status = $response->getStatusCode(); + + return $response; + }); + } + }; + $docker = Docker::create(null, [$capture]); + + $stream = $docker->execStart($execCreateResult->getId(), $execStartConfig); + + $this->assertSame($upgrade ? 101 : 200, $capture->status); + $this->assertInstanceOf(DockerRawStream::class, $stream); + + $stdoutFull = ''; + $stderrFull = ''; + $stream->onStdout(function ($stdout) use (&$stdoutFull): void { + $stdoutFull .= $stdout; + }); + $stream->onStderr(function ($stderr) use (&$stderrFull): void { + $stderrFull .= $stderr; + }); + $stream->wait(); + + $this->assertSame($empty ? '' : ($tty ? 'stdoutstderr' : 'stdout'), $stdoutFull); + $this->assertSame($empty || $tty ? '' : 'stderr', $stderrFull); + + $execInfo = $this->getManager()->execInspect($execCreateResult->getId()); + $this->assertFalse($execInfo->getRunning()); + $this->assertSame(0, $execInfo->getExitCode()); + } finally { + self::getDocker()->containerDelete($createContainerResult->getId(), ['force' => true]); + } } public function testExecFind(): void diff --git a/tests/Resource/ImageResourceTest.php b/tests/Resource/ImageResourceTest.php index e1c129dd0..bbedf66b3 100644 --- a/tests/Resource/ImageResourceTest.php +++ b/tests/Resource/ImageResourceTest.php @@ -37,7 +37,29 @@ public function testBuild(): void }); $buildStream->wait(); - $this->assertContains('Successfully', $lastMessage); + $this->assertStringContainsString('Successfully', $lastMessage); + } + + public function testBuildAppliesSeveralTags(): void + { + $contextBuilder = new ContextBuilder(); + $contextBuilder->from('busybox:latest'); + $contextBuilder->add('/test', 'test file content'); + $context = $contextBuilder->getContext(); + $tags = ['docker-php-test-tags:one', 'docker-php-test-tags:two']; + + $buildStream = $this->getManager()->imageBuild($context->read(), ['t' => $tags]); + $buildStream->wait(); + + try { + $repoTags = $this->getManager()->imageInspect($tags[0])->getRepoTags(); + sort($repoTags); + $this->assertSame($tags, $repoTags); + } finally { + foreach ($tags as $tag) { + $this->getManager()->imageDelete($tag); + } + } } public function testCreate(): void @@ -57,7 +79,7 @@ public function testCreate(): void }); $createImageStream->wait(); - $this->assertContains('Pulling from library/registry', $firstMessage); + $this->assertStringContainsString('Pulling from library/registry', $firstMessage); } public function testPushStream(): void @@ -86,6 +108,6 @@ public function testPushStream(): void }); $pushImageStream->wait(); - $this->assertContains('repository [localhost:5000/test-image]', $firstMessage); + $this->assertStringContainsString('repository [localhost:5000/test-image]', $firstMessage); } } diff --git a/tests/Resource/InteractiveExecResourceTest.php b/tests/Resource/InteractiveExecResourceTest.php new file mode 100644 index 000000000..3c4be5fbe --- /dev/null +++ b/tests/Resource/InteractiveExecResourceTest.php @@ -0,0 +1,124 @@ +setImage('busybox:latest'); + $container->setCmd(['sleep', '60']); + $created = $docker->containerCreate($container); + try { + $docker->containerStart($created->getId()); + $create = new ContainersIdExecPostBody(); + $create->setAttachStdin(true); + $create->setAttachStdout(true); + $create->setAttachStderr(true); + $create->setTty(true); + $create->setCmd(['sh', '-c', 'read line; printf "ok:%s\\n" "$line"; printf error >&2']); + $exec = $docker->containerExec($created->getId(), $create); + $body = new ExecIdStartPostBody(); + $body->setTty(true); + $session = $docker->execStartInteractive($exec->getId(), $body, 5000); + $output = ''; + $session->onStdout(static function (string $chunk) use (&$output): void { $output .= $chunk; }); + $session->onStderr(static function (): void { self::fail('TTY stderr was separated.'); }); + self::assertSame(6, $session->writeStdin("hello\n")); + // TTY input is a terminal: EOF on the socket can cut off output. + // This command exits after one line, without needing input EOF. + $session->wait(); + self::assertStringContainsString('ok:hello', $output); + self::assertStringContainsString('error', $output); + } finally { + $docker->containerDelete($created->getId(), ['force' => true]); + } + } + + public function testStdinEofAndNonzeroExitAgainstDocker(): void + { + $docker = self::getDocker(); + $container = new ContainersCreatePostBody(); + $container->setImage('busybox:latest'); + $container->setCmd(['sleep', '60']); + $created = $docker->containerCreate($container); + try { + $docker->containerStart($created->getId()); + $create = new ContainersIdExecPostBody(); + $create->setAttachStdin(true); + $create->setAttachStdout(true); + $create->setAttachStderr(true); + $create->setTty(false); + $create->setCmd(['sh', '-c', 'cat; printf error >&2; exit 7']); + $exec = $docker->containerExec($created->getId(), $create); + $body = new ExecIdStartPostBody(); + $body->setTty(false); + $session = $docker->execStartInteractive($exec->getId(), $body, 5000); + $stdout = $stderr = ''; + $session->onStdout(static function (string $chunk) use (&$stdout): void { $stdout .= $chunk; }); + $session->onStderr(static function (string $chunk) use (&$stderr): void { $stderr .= $chunk; }); + $input = str_repeat("binary\0\xff\n", 8192); + $offset = 0; + while ($offset < \strlen($input)) { + $offset += $session->writeStdin(substr($input, $offset)); + $session->poll(1); + } + $session->closeStdin(); + $session->wait(); + self::assertSame($input, $stdout); + self::assertSame('error', $stderr); + $info = $docker->execInspect($exec->getId()); + self::assertFalse($info->getRunning()); + self::assertSame(7, $info->getExitCode()); + } finally { + $docker->containerDelete($created->getId(), ['force' => true]); + } + } + + public function testSilentExecHeartbeatAndContainerTimeout(): void + { + $docker = self::getDocker(); + $container = new ContainersCreatePostBody(); + $container->setImage('busybox:latest'); + $container->setCmd(['sleep', '60']); + $created = $docker->containerCreate($container); + try { + $docker->containerStart($created->getId()); + $create = new ContainersIdExecPostBody(); + $create->setAttachStdout(true); + $create->setAttachStderr(true); + $create->setCmd(['timeout', '-s', 'KILL', '1', 'sleep', '30']); + $exec = $docker->containerExec($created->getId(), $create); + $session = $docker->execStartInteractive($exec->getId(), null, 180); + $ticks = 0; + try { + $session->wait(static function () use (&$ticks): void { ++$ticks; }, 30); + self::fail('The streaming deadline was ignored.'); + } catch (InteractiveExecTimeoutException $expected) { + self::assertGreaterThanOrEqual(3, $ticks); + } + // Disconnecting output is not cancellation. Keep the container-side + // timeout, which terminates only this exec, not the whole container. + self::assertTrue($docker->execInspect($exec->getId())->getRunning()); + $deadline = hrtime(true) + 3000000000; + do { + usleep(50000); + $info = $docker->execInspect($exec->getId()); + } while ($info->getRunning() && hrtime(true) < $deadline); + self::assertFalse($info->getRunning()); + self::assertNotSame(0, $info->getExitCode()); + } finally { + $docker->containerDelete($created->getId(), ['force' => true]); + } + } +} diff --git a/tests/Resource/LiveStreamTest.php b/tests/Resource/LiveStreamTest.php new file mode 100644 index 000000000..2b8bc62ae --- /dev/null +++ b/tests/Resource/LiveStreamTest.php @@ -0,0 +1,123 @@ + [false]; + yield 'TTY output' => [true]; + } + + private function createContainer(bool $tty, array $command): string + { + $config = new ContainersCreatePostBody(); + $config->setImage('busybox:latest'); + $config->setCmd($command); + $config->setTty($tty); + $config->setExposedPorts(['80/tcp' => new \stdClass()]); + $config->setLabels(['docker-php-test' => 'true']); + $id = self::getDocker()->containerCreate($config)->getId(); + self::getDocker()->containerStart($id); + + return $id; + } + + private function assertLiveOutput(DockerRawStream $stream, bool $tty): void + { + $stdout = ''; + $stderr = ''; + $first = null; + $last = null; + $stream->onStdout(static function (string $chunk) use (&$stdout, &$first, &$last): void { + $first ??= hrtime(true); + $last = hrtime(true); + $stdout .= $chunk; + }); + $stream->onStderr(static function (string $chunk) use (&$stderr, &$first, &$last): void { + $first ??= hrtime(true); + $last = hrtime(true); + $stderr .= $chunk; + }); + $stream->wait(); + self::assertSame($tty ? "first\r\nerror\r\nlast\r\nfinal\r\n" : "first\nlast\n", $stdout); + self::assertSame($tty ? '' : "error\nfinal\n", $stderr); + self::assertNotNull($first); + self::assertGreaterThan(500_000_000, $last - $first, 'Callbacks must receive output before the command finishes, not a buffered response.'); + } + + /** @dataProvider ttyProvider */ + public function testFollowLogsDeliversOutputWhileContainerRuns(bool $tty): void + { + $id = $this->createContainer($tty, ['sh', '-c', 'printf "first\n"; printf "error\n" >&2; sleep 2; printf "last\n"; printf "final\n" >&2']); + try { + $stream = self::getDocker()->containerLogs($id, ['stdout' => true, 'stderr' => true, 'follow' => true]); + self::assertInstanceOf(DockerRawStream::class, $stream); + $this->assertLiveOutput($stream, $tty); + self::assertNull(self::getDocker()->containerInspect($id)->getNetworkSettings()->getPorts()['80/tcp']); + } finally { + self::getDocker()->containerDelete($id, ['force' => true]); + } + } + + /** @dataProvider ttyProvider */ + public function testExecDeliversOutputBeforeExit(bool $tty): void + { + $id = $this->createContainer(false, ['sleep', '30']); + try { + $config = new ContainersIdExecPostBody(); + $config->setAttachStdout(true); + $config->setAttachStderr(true); + $config->setTty($tty); + $config->setCmd(['sh', '-c', 'printf "first\n"; printf "error\n" >&2; sleep 2; printf "last\n"; printf "final\n" >&2']); + $exec = self::getDocker()->containerExec($id, $config); + $start = new ExecIdStartPostBody(); + $start->setDetach(false); + $start->setTty($tty); + $stream = self::getDocker()->execStart($exec->getId(), $start); + self::assertInstanceOf(DockerRawStream::class, $stream); + $this->assertLiveOutput($stream, $tty); + $result = self::getDocker()->execInspect($exec->getId()); + self::assertFalse($result->getRunning()); + self::assertSame(0, $result->getExitCode()); + } finally { + self::getDocker()->containerDelete($id, ['force' => true]); + } + } + + public function testContainerStatsStreamsLiveSamples(): void + { + $id = $this->createContainer(false, ['sleep', '30']); + + try { + $stats = self::getDocker()->containerStats($id); + $this->assertInstanceOf(StatsStream::class, $stats); + $reads = []; + $stats->onFrame(static function (object $sample) use ($stats, &$reads): void { + // ContainerStatsResponse from API 1.48; a decoded stdClass before that. + $reads[] = $sample instanceof \stdClass ? $sample->read : $sample->getRead()?->format(\DATE_RFC3339_EXTENDED); + if (2 === \count($reads)) { + $stats->stop(); + } + }); + $started = microtime(true); + $stats->wait(); + + $this->assertCount(2, $reads); + $this->assertNotSame($reads[0], $reads[1]); + $this->assertLessThan(15, microtime(true) - $started, 'stop() should end wait() before the container exits'); + } finally { + self::getDocker()->containerDelete($id, ['force' => true]); + } + } +} diff --git a/tests/Resource/SystemResourceTest.php b/tests/Resource/SystemResourceTest.php index 474f3506e..fb1badf30 100644 --- a/tests/Resource/SystemResourceTest.php +++ b/tests/Resource/SystemResourceTest.php @@ -4,7 +4,7 @@ namespace Docker\Tests\Resource; -use Docker\API\Model\EventsGetResponse200; +use Docker\API\Model\EventMessage; use Docker\Tests\TestCase; class SystemResourceTest extends TestCase @@ -20,8 +20,8 @@ private function getManager() public function testGetEvents(): void { $stream = $this->getManager()->systemEvents([ - 'since' => (string) (\time() - 1), - 'until' => (string) (\time() + 4), + 'since' => (string) (time() - 1), + 'until' => (string) (time() + 4), ]); $lastEvent = null; @@ -36,6 +36,6 @@ public function testGetEvents(): void $stream->wait(); - $this->assertInstanceOf(EventsGetResponse200::class, $lastEvent); + $this->assertInstanceOf(EventMessage::class, $lastEvent); } } diff --git a/tests/Serializer/LargeIntegerJsonDecodeTest.php b/tests/Serializer/LargeIntegerJsonDecodeTest.php new file mode 100644 index 000000000..1374e6cc2 --- /dev/null +++ b/tests/Serializer/LargeIntegerJsonDecodeTest.php @@ -0,0 +1,24 @@ + true]))->decode($json, 'json'); + $object = (new LargeIntegerJsonDecode())->decode($json, 'json'); + + $this->assertSame(['limit' => \PHP_INT_MAX, 'current' => 7, 'ratio' => 0.5, 'items' => [\PHP_INT_MAX, 1], 'name' => '18446744073709551615'], $associative); + $this->assertSame(\PHP_INT_MAX, $object->limit); + $this->assertSame([\PHP_INT_MAX, 1], $object->items); + $this->assertSame(0.5, $object->ratio); + } +} diff --git a/tests/StaticAnalysis/DockerReturnTypes.php b/tests/StaticAnalysis/DockerReturnTypes.php new file mode 100644 index 000000000..04fe52a06 --- /dev/null +++ b/tests/StaticAnalysis/DockerReturnTypes.php @@ -0,0 +1,25 @@ +containerAttach('id')); + assertType('Docker\Stream\AttachWebsocketStream|null', $docker->containerAttachWebsocket('id')); + assertType('Docker\Stream\DockerRawStream|null', $docker->containerLogs('id')); + assertType('Docker\Stream\DockerRawStream|null', $docker->execStart('id')); + assertType('Docker\Stream\BuildStream|null', $docker->imageBuild()); + assertType('Docker\Stream\BuildStream|null', $docker->imageBuild(null, ['t' => ['app:latest', 'app:1.0']])); + assertType('Docker\Stream\CreateImageStream|null', $docker->imageCreate()); + assertType('Docker\Stream\PushStream|null', $docker->imagePush('name')); + assertType('Docker\Stream\EventStream|null', $docker->systemEvents()); + assertType('object|null', $docker->containerStats('id')); + assertType('Psr\Http\Message\ResponseInterface', $docker->containerLogs('id', [], Docker::FETCH_RESPONSE)); +} diff --git a/tests/Stream/AttachWebsocketStreamTest.php b/tests/Stream/AttachWebsocketStreamTest.php new file mode 100644 index 000000000..c94c4fdc0 --- /dev/null +++ b/tests/Stream/AttachWebsocketStreamTest.php @@ -0,0 +1,155 @@ +assertSame('', $stream->read()); + $this->assertSame('hi', $stream->read()); + fclose($server); + } + + public static function payloadLengths(): iterable + { + yield '7-bit length' => [125, "\xFD", '']; + yield '16-bit length' => [126, "\xFE", pack('n', 126)]; + yield 'largest 16-bit length' => [0xFFFF, "\xFE", pack('n', 0xFFFF)]; + yield 'smallest 64-bit length' => [0x10000, "\xFF", pack('J', 0x10000)]; + } + + #[DataProvider('payloadLengths')] + public function testWriteEncodesPayloadLength(int $length, string $lengthByte, string $extendedLength): void + { + $socket = fopen('php://temp', 'w+'); + $stream = new AttachWebsocketStream(Stream::create($socket)); + $data = str_repeat('x', $length); + + $stream->write($data); + + rewind($socket); + $frame = stream_get_contents($socket); + $header = 2 + \strlen($extendedLength); + $this->assertSame("\x82".$lengthByte.$extendedLength, substr($frame, 0, $header)); + $mask = substr($frame, $header, 4); + $payload = substr($frame, $header + 4); + $this->assertSame($length, \strlen($payload)); + $this->assertSame($data, $payload ^ str_repeat($mask, intdiv($length, 4) + 1)); + } + + public function testCloseSendsCloseFrameAndClosesSocket(): void + { + [$client, $server] = stream_socket_pair(\STREAM_PF_UNIX, \STREAM_SOCK_STREAM, \STREAM_IPPROTO_IP); + $stream = new AttachWebsocketStream(Stream::create($client)); + + $stream->close(); + $stream->close(); + + $frame = fread($server, 16); + $this->assertSame("\x88\x80", substr($frame, 0, 2)); + $this->assertSame(6, \strlen($frame)); + $this->assertSame('', fread($server, 1)); + $this->assertTrue(feof($server)); + $this->assertNull($stream->read()); + fclose($server); + } + + public function testCloseIgnoresPeerThatAlreadyClosed(): void + { + [$client, $server] = stream_socket_pair(\STREAM_PF_UNIX, \STREAM_SOCK_STREAM, \STREAM_IPPROTO_IP); + fclose($server); + $stream = new AttachWebsocketStream(Stream::create($client)); + + $stream->close(); + + $this->assertNull($stream->read()); + } + + public function testWriteAfterCloseThrows(): void + { + [$client, $server] = stream_socket_pair(\STREAM_PF_UNIX, \STREAM_SOCK_STREAM, \STREAM_IPPROTO_IP); + $stream = new AttachWebsocketStream(Stream::create($client)); + $stream->close(); + fclose($server); + + $this->expectException(\RuntimeException::class); + $stream->write('exit'); + } + + public function testAnswersPingAndReturnsNextDataFrame(): void + { + [$client, $server] = $this->socketPair(); + fwrite($server, "\x89\x02hi\x82\x02ok"); + $stream = new AttachWebsocketStream(Stream::create($client)); + + $this->assertSame('ok', $stream->read()); + $pong = fread($server, 16); + $this->assertSame("\x8A\x82", substr($pong, 0, 2)); + $this->assertSame('hi', substr($pong, 6) ^ substr($pong, 2, 4)); + } + + public function testCloseFrameRepliesAndEndsStream(): void + { + [$client, $server] = $this->socketPair(); + fwrite($server, "\x88\x02\x03\xe8"); + $stream = new AttachWebsocketStream(Stream::create($client)); + + $this->assertNull($stream->read()); + $this->assertSame("\x88\x80", substr(fread($server, 16), 0, 2)); + $this->assertNull($stream->read()); + } + + public function testReadsSixtyFourBitLength(): void + { + [$client, $server] = $this->socketPair(); + fwrite($server, "\x82\x7F".pack('J', 3).'abc'); + $stream = new AttachWebsocketStream(Stream::create($client)); + + $this->assertSame('abc', $stream->read()); + } + + public function testConnectionEndingMidFrameEndsStream(): void + { + [$client, $server] = $this->socketPair(); + fwrite($server, "\x82\x05ab"); + fclose($server); + $stream = new AttachWebsocketStream(Stream::create($client)); + + $this->assertNull($stream->read()); + $this->assertNull($stream->read()); + } + + public function testStalledFrameTimesOut(): void + { + [$client, $server] = $this->socketPair(); + stream_set_timeout($client, 0, 100000); + fwrite($server, "\x82\x05ab"); + $stream = new AttachWebsocketStream(Stream::create($client)); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Timed out'); + $stream->read(); + } + + /** + * @return array{resource, resource} + */ + private function socketPair(): array + { + return stream_socket_pair(\STREAM_PF_UNIX, \STREAM_SOCK_STREAM, \STREAM_IPPROTO_IP); + } +} diff --git a/tests/Stream/DechunkStreamTest.php b/tests/Stream/DechunkStreamTest.php new file mode 100644 index 000000000..72fc9f9c2 --- /dev/null +++ b/tests/Stream/DechunkStreamTest.php @@ -0,0 +1,83 @@ +createMock(StreamInterface::class); + $source->method('eof')->willReturn(false); + $source->expects(self::once())->method('read')->with(8192)->willReturn("5\r\nhello\r\n"); + + self::assertSame('hello', (new DechunkStream($source))->read(8192)); + } + + public static function bodies(): iterable + { + yield 'empty body' => ["0\r\n\r\n", '', 8192, 8192]; + yield 'one chunk' => ["5\r\nhello\r\n0\r\n\r\n", 'hello', 8192, 8192]; + yield 'short reads' => ["5\r\nhello\r\n5\r\nworld\r\n0\r\n\r\n", 'helloworld', 8192, 3]; + yield 'split headers and payloads' => ["5\r\nhello\r\n5\r\nworld\r\n0\r\n\r\n", 'helloworld', 1, 8192]; + yield 'chunk extensions and trailers' => ["5;foo=bar\r\nhello\r\n0\r\nX-Test: yes\r\n\r\n", 'hello', 2, 3]; + yield 'binary payload' => ["4\r\n\x00\xff\r\n\r\n0\r\n\r\n", "\x00\xff\r\n", 3, 1]; + $large = str_repeat('abc', 10_000); + yield 'larger than the read buffer' => [dechex(\strlen($large))."\r\n".$large."\r\n0\r\n\r\n", $large, 8192, 8192]; + } + + #[DataProvider('bodies')] + public function testDecodesNonSeekableInput(string $body, string $expected, int $sourceReadSize, int $readSize): void + { + $position = 0; + $source = $this->createMock(StreamInterface::class); + $source->method('eof')->willReturnCallback(static function () use (&$position, $body): bool { + return $position >= \strlen($body); + }); + $source->method('read')->willReturnCallback(static function (int $length) use (&$position, $body, $sourceReadSize): string { + $output = substr($body, $position, min($length, $sourceReadSize)); + $position += \strlen($output); + + return $output; + }); + $source->expects(self::never())->method('seek'); + $source->expects(self::never())->method('rewind'); + $source->expects(self::never())->method('getContents'); + $stream = new DechunkStream($source); + $output = ''; + while (!$stream->eof()) { + $chunk = $stream->read($readSize); + self::assertLessThanOrEqual($readSize, \strlen($chunk)); + $output .= $chunk; + } + + self::assertSame($expected, $output); + self::assertSame('', $stream->read($readSize)); + self::assertFalse($stream->isSeekable()); + self::assertNull($stream->getSize()); + } + + public function testZeroLengthReadDoesNotConsumeInput(): void + { + $stream = new DechunkStream(Stream::create("5\r\nhello\r\n0\r\n\r\n")); + + self::assertSame('', $stream->read(0)); + self::assertSame('hello', $stream->getContents()); + } + + public function testNegativeLengthReadIsRejected(): void + { + $source = $this->createMock(StreamInterface::class); + $source->expects(self::never())->method('read'); + $this->expectException(\InvalidArgumentException::class); + + (new DechunkStream($source))->read(-1); + } +} diff --git a/tests/Stream/DockerRawStreamTest.php b/tests/Stream/DockerRawStreamTest.php new file mode 100644 index 000000000..7dfcc3377 --- /dev/null +++ b/tests/Stream/DockerRawStreamTest.php @@ -0,0 +1,67 @@ + [$frames, true, 8192, "hello\nagain\n", "error\n"]; + yield 'one byte per read' => [$frames, true, 1, "hello\nagain\n", "error\n"]; + yield 'split headers and payloads' => [$frames, true, 7, "hello\nagain\n", "error\n"]; + yield 'empty framed stream' => ['', true, 8192, '', '']; + yield 'zero-length frame' => [self::frame(1, '').self::frame(1, 'hello'), true, 8192, 'hello', '']; + yield 'short TTY output' => ["hello\n", false, 8192, "hello\n", '']; + yield 'TTY output across reads' => ["terminal output\r\n", false, 2, "terminal output\r\n", '']; + yield 'empty TTY stream' => ['', false, 8192, '', '']; + yield 'TTY bytes resembling frames' => [$frames, false, 3, $frames, '']; + } + + /** @dataProvider streamProvider */ + public function testReadsNonSeekableStream(string $body, bool $multiplexed, int $chunkSize, string $expectedStdout, string $expectedStderr): void + { + $position = 0; + $source = $this->createMock(StreamInterface::class); + $source->method('eof')->willReturnCallback(static function () use (&$position, $body): bool { + return $position >= \strlen($body); + }); + $source->method('read')->willReturnCallback(static function (int $length) use (&$position, $body, $chunkSize): string { + if ($length <= 0) { + throw new \InvalidArgumentException('Read length must be positive'); + } + $chunk = substr($body, $position, min($length, $chunkSize)); + $position += \strlen($chunk); + + return $chunk; + }); + $source->expects(self::never())->method('seek'); + $source->expects(self::never())->method('rewind'); + $source->expects(self::never())->method('getContents'); + + $stream = new DockerRawStream($source, $multiplexed); + $stdout = ''; + $stderr = ''; + $stream->onStdout(static function (string $output) use (&$stdout): void { + $stdout .= $output; + }); + $stream->onStderr(static function (string $output) use (&$stderr): void { + $stderr .= $output; + }); + $stream->wait(); + + self::assertSame($expectedStdout, $stdout); + self::assertSame($expectedStderr, $stderr); + } + + private static function frame(int $type, string $output): string + { + return pack('CxxxN', $type, \strlen($output)).$output; + } +} diff --git a/tests/Stream/InteractiveExecStreamTest.php b/tests/Stream/InteractiveExecStreamTest.php new file mode 100644 index 000000000..9ce26e82e --- /dev/null +++ b/tests/Stream/InteractiveExecStreamTest.php @@ -0,0 +1,231 @@ +stream?->close(); + foreach ($this->sockets as $socket) { + if (\is_resource($socket)) { + fclose($socket); + } + } + parent::tearDown(); + } + + private function open(bool $multiplexed = true, ?int $timeoutMs = null): InteractiveExecStream + { + $this->sockets = stream_socket_pair(\STREAM_PF_UNIX, \STREAM_SOCK_STREAM, \STREAM_IPPROTO_IP); + self::assertIsArray($this->sockets); + stream_set_blocking($this->sockets[1], false); + + return $this->stream = new InteractiveExecStream($this->sockets[0], $multiplexed, $timeoutMs); + } + + public function testHalfCloseKeepsOutputReadable(): void + { + $stream = $this->open(); + self::assertSame(5, $stream->writeStdin('input')); + self::assertSame('input', fread($this->sockets[1], 20)); + $stream->closeStdin(); + $stream->closeStdin(); + self::assertSame('', fread($this->sockets[1], 20)); + self::assertTrue(feof($this->sockets[1])); + fwrite($this->sockets[1], pack('CxxxN', 1, 6).'result'); + fclose($this->sockets[1]); + $output = ''; + $stream->onStdout(static function (string $chunk) use (&$output): void { $output .= $chunk; }); + $stream->wait(); + self::assertSame('result', $output); + self::assertTrue($stream->isFinished()); + self::assertFalse($stream->poll()); + } + + public function testPartialWritesAndBackpressureAreBounded(): void + { + $stream = $this->open(); + $payload = str_repeat('x', 1048576); + $offset = 0; + $started = hrtime(true); + do { + $written = $stream->writeStdin(substr($payload, $offset)); + self::assertLessThanOrEqual(16384, $written); + $offset += $written; + } while ($written > 0 && $offset < \strlen($payload)); + self::assertSame(0, $written, 'The peer must eventually apply backpressure.'); + self::assertLessThan(500000000, hrtime(true) - $started, 'writeStdin blocked.'); + self::assertLessThan(\strlen($payload), $offset); + $received = ''; + while ($offset < \strlen($payload)) { + $received .= stream_get_contents($this->sockets[1]); + $offset += $stream->writeStdin(substr($payload, $offset)); + } + $received .= stream_get_contents($this->sockets[1]); + self::assertSame($payload, $received); + } + + public function testFragmentedHeadersPayloadsAndEmptyFrames(): void + { + $stream = $this->open(); + $stdout = $stderr = ''; + $stream->onStdout(static function (string $chunk) use (&$stdout): void { $stdout .= $chunk; }); + $stream->onStderr(static function (string $chunk) use (&$stderr): void { $stderr .= $chunk; }); + $wire = pack('CxxxN', 1, 0).pack('CxxxN', 1, 5).'hello'.pack('CxxxN', 2, 5).'error'.pack('CxxxN', 0, 4).'echo'; + foreach (str_split($wire, 3) as $chunk) { + fwrite($this->sockets[1], $chunk); + self::assertTrue($stream->poll()); + } + fclose($this->sockets[1]); + $stream->wait(); + self::assertSame('helloecho', $stdout); + self::assertSame('error', $stderr); + } + + public function testTtyBytesRemainUnchanged(): void + { + $stream = $this->open(false); + $output = ''; + $stream->onStdout(static function (string $chunk) use (&$output): void { $output .= $chunk; }); + $stream->onStderr(static function (): void { self::fail('TTY output has no separate stderr.'); }); + $bytes = "\0\xffhello\r\n"; + fwrite($this->sockets[1], $bytes); + fclose($this->sockets[1]); + $stream->wait(); + self::assertSame($bytes, $output); + } + + public function testIdlePollIsBoundedAndTicksReachDeadline(): void + { + $stream = $this->open(true, 160); + $started = hrtime(true); + self::assertTrue($stream->poll(30)); + self::assertGreaterThan(20000000, hrtime(true) - $started); + $ticks = 0; + try { + $stream->wait(static function () use (&$ticks): void { ++$ticks; }, 30); + self::fail('An idle session exceeded its deadline.'); + } catch (InteractiveExecTimeoutException $expected) { + self::assertGreaterThanOrEqual(3, $ticks); + self::assertLessThan(500000000, hrtime(true) - $started); + self::assertFalse($stream->isFinished(), 'A timeout is not successful completion.'); + } + } + + public static function invalidFrames(): array + { + return [ + 'partial header' => ["\x01\x00"], + 'partial payload' => [pack('CxxxN', 1, 5).'ab'], + 'invalid channel' => [pack('CxxxN', 9, 0)], + 'invalid padding' => ["\x01\x01\x00\x00\x00\x00\x00\x00"], + 'system error frame' => [pack('CxxxN', 3, 0)], + ]; + } + + #[DataProvider('invalidFrames')] + public function testInvalidOrTruncatedFramesFail(string $wire): void + { + $stream = $this->open(); + fwrite($this->sockets[1], $wire); + fclose($this->sockets[1]); + $this->expectException(\RuntimeException::class); + $stream->wait(); + } + + public function testHugeFrameDoesNotAllocateItsDeclaredSize(): void + { + $stream = $this->open(); + // Measure used bytes, not allocator pages (which grow in 2 MiB steps), + // and exclude PHPUnit's own assertion/autoload allocations. + $before = memory_get_usage(); + fwrite($this->sockets[1], pack('CxxxN', 1, 4294967295).'x'); + $open = $stream->poll(); + $used = memory_get_usage() - $before; + self::assertTrue($open); + self::assertLessThan(1048576, $used); + } + + public function testCallbackFailureClosesConnection(): void + { + $stream = $this->open(); + $error = new \RuntimeException('callback failed'); + $stream->onStdout(static function () use ($error): void { throw $error; }); + fwrite($this->sockets[1], pack('CxxxN', 1, 1).'x'); + try { + $stream->poll(); + self::fail('Callback error was swallowed.'); + } catch (\RuntimeException $caught) { + self::assertSame($error, $caught); + self::assertSame('', fread($this->sockets[1], 1)); + self::assertTrue(feof($this->sockets[1])); + } + } + + public function testHeartbeatFailureClosesConnection(): void + { + $stream = $this->open(); + $this->expectExceptionMessage('lock lost'); + try { + $stream->wait(static function (): void { throw new \RuntimeException('lock lost'); }); + } finally { + self::assertSame('', fread($this->sockets[1], 1)); + self::assertTrue(feof($this->sockets[1])); + } + } + + public function testWriteAfterHalfCloseFails(): void + { + $stream = $this->open(); + $stream->closeStdin(); + $this->expectException(\LogicException::class); + $stream->writeStdin('x'); + } + + public function testTtyHalfCloseIsRejectedWithoutLosingTheConnection(): void + { + $stream = $this->open(false); + try { + $stream->closeStdin(); + self::fail('Unsafe TTY half-close was accepted.'); + } catch (\LogicException $expected) { + self::assertSame(1, $stream->writeStdin('x')); + } + } + + public function testExplicitCloseIsNotSuccessfulEof(): void + { + $stream = $this->open(); + $stream->close(); + $stream->close(); + self::assertFalse($stream->isFinished()); + $this->expectException(\LogicException::class); + $stream->poll(); + } + + public function testWriteFailureClosesConnection(): void + { + $stream = $this->open(); + fclose($this->sockets[1]); + $this->expectException(\RuntimeException::class); + $stream->writeStdin('x'); + } + + public function testInvalidPollTimeoutIsRejected(): void + { + $stream = $this->open(); + $this->expectException(\InvalidArgumentException::class); + $stream->poll(60001); + } +} diff --git a/tests/Stream/MultiJsonStreamTest.php b/tests/Stream/MultiJsonStreamTest.php index a999f4929..e3683e5c3 100644 --- a/tests/Stream/MultiJsonStreamTest.php +++ b/tests/Stream/MultiJsonStreamTest.php @@ -7,12 +7,12 @@ use Docker\API\Model\BuildInfo; use Docker\Stream\MultiJsonStream; use Docker\Tests\TestCase; -use GuzzleHttp\Psr7\BufferStream; +use Nyholm\Psr7\Stream; use Symfony\Component\Serializer\SerializerInterface; class MultiJsonStreamTest extends TestCase { - public function jsonStreamDataProvider() + public static function jsonStreamDataProvider() { return [ [ @@ -20,7 +20,7 @@ public function jsonStreamDataProvider() ['{}', '{"abc":"def"}'], ], [ - '{"test": "abc\"\""}', + '{"test": "abc\"\""}', ['{"test":"abc\"\""}'], ], [ @@ -31,25 +31,28 @@ public function jsonStreamDataProvider() } /** - * @param $jsonStream - * @param $jsonParts * @dataProvider jsonStreamDataProvider */ public function testReadJsonEscapedDoubleQuote(string $jsonStream, array $jsonParts): void { - $stream = new BufferStream(); - $stream->write($jsonStream); + $stream = Stream::create($jsonStream); + $stream->rewind(); $serializer = $this->getMockBuilder(SerializerInterface::class) ->getMock(); + $callIndex = 0; $serializer ->expects($this->exactly(\count($jsonParts))) ->method('deserialize') - ->withConsecutive(...\array_map(function ($part) { - return [$part, BuildInfo::class, 'json', []]; - }, $jsonParts)) - ; + ->willReturnCallback(function ($data, $class, $format, $context) use ($jsonParts, &$callIndex) { + $this->assertEquals($jsonParts[$callIndex], $data); + $this->assertEquals(BuildInfo::class, $class); + $this->assertEquals('json', $format); + $this->assertEquals([], $context); + $callIndex++; + return null; + }); $stub = $this->getMockForAbstractClass(MultiJsonStream::class, [$stream, $serializer]); $stub->expects($this->any()) diff --git a/tests/Stream/SocketReadStreamTest.php b/tests/Stream/SocketReadStreamTest.php new file mode 100644 index 000000000..90971c243 --- /dev/null +++ b/tests/Stream/SocketReadStreamTest.php @@ -0,0 +1,33 @@ + [7, 8192, 7]; + yield 'buffer exceeds request' => [20, 8, 8]; + yield 'no buffered bytes' => [0, 8192, 8192]; + yield 'metadata unavailable' => [null, 8192, 8192]; + yield 'zero length' => [7, 0, 0]; + } + + #[DataProvider('readSizes')] + public function testUsesBufferedBytesBeforeReadingMore(?int $buffered, int $requested, int $expectedRead): void + { + $source = $this->createMock(StreamInterface::class); + $source->expects(self::once())->method('getMetadata')->with('unread_bytes')->willReturn($buffered); + $expected = str_repeat('x', $expectedRead); + $source->expects(self::once())->method('read')->with($expectedRead)->willReturn($expected); + + self::assertSame($expected, (new SocketReadStream($source))->read($requested)); + } +} diff --git a/tests/Stream/StatsStreamTest.php b/tests/Stream/StatsStreamTest.php new file mode 100644 index 000000000..c30dc28d4 --- /dev/null +++ b/tests/Stream/StatsStreamTest.php @@ -0,0 +1,74 @@ +onFrame(static function (\stdClass $sample) use (&$usage): void { + $usage[$sample->read] = $sample->memory_stats->usage; + }); + + $stream->wait(); + + $this->assertSame(['t1' => 1, 't2' => 2], $usage); + } + + public function testStopFromCallbackEndsWaitAndClosesBody(): void + { + $body = Stream::create(self::BODY); + $stream = new StatsStream($body); + $calls = []; + $stream->onFrame(static function (\stdClass $sample) use ($stream, &$calls): void { + $calls[] = 'first:'.$sample->read; + $stream->stop(); + }); + $stream->onFrame(static function (\stdClass $sample) use (&$calls): void { + $calls[] = 'second:'.$sample->read; + }); + + $stream->wait(); + + $this->assertSame(['first:t1', 'second:t1'], $calls); + $this->assertFalse($body->isReadable()); + } + + public function testStopBeforeWaitSkipsBody(): void + { + $stream = new StatsStream(Stream::create(self::BODY)); + $stream->onFrame(function (): void { + $this->fail('No sample should be delivered after stop().'); + }); + + $stream->stop(); + $stream->stop(); + $stream->wait(); + + $this->addToAssertionCount(1); + } + + public function testIgnoresIncompleteTrailingSample(): void + { + $stream = new StatsStream(Stream::create("{\"read\":\"t1\"}\n{\"read\":")); + $reads = []; + $stream->onFrame(static function (\stdClass $sample) use (&$reads): void { + $reads[] = $sample->read; + }); + + $stream->wait(); + + $this->assertSame(['t1'], $reads); + } +} diff --git a/tests/StreamingTransportTest.php b/tests/StreamingTransportTest.php new file mode 100644 index 000000000..5963e6bdd --- /dev/null +++ b/tests/StreamingTransportTest.php @@ -0,0 +1,69 @@ + false, 'Unix' => true] as $transport => $unix) { + foreach (['TTY' => false, 'multiplexed' => true] as $format => $multiplexed) { + yield $transport.' chunked '.$format => [$unix, $multiplexed, true]; + yield $transport.' upgraded '.$format => [$unix, $multiplexed, false]; + } + } + } + + #[DataProvider('streams')] + public function testCallbacksReceiveOutputBeforeThePeerFinishes(bool $unix, bool $multiplexed, bool $chunked): void + { + $first = $multiplexed ? pack('CxxxN', 1, 6)."first\n".pack('CxxxN', 2, 6)."error\n" : "first\r\nerror\r\n"; + $last = $multiplexed ? pack('CxxxN', 1, 5)."last\n".pack('CxxxN', 2, 6)."final\n" : "last\r\nfinal\r\n"; + $response = ['status' => 101, 'headers' => ['Connection' => 'Upgrade', 'Upgrade' => 'tcp']]; + if ($chunked) { + $response = ['headers' => ['Transfer-Encoding' => 'chunked']]; + $first = dechex(\strlen($first))."\r\n".$first."\r\n"; + $last = dechex(\strlen($last))."\r\n".$last."\r\n0\r\n\r\n"; + } + $address = $this->startServer(['responses' => [$response + [ + 'segments_base64' => [base64_encode($first), base64_encode($last)], + 'delay_ms' => 1000, + ]]], $unix); + putenv('DOCKER_API_VERSION=1.52'); + $client = DockerClientFactory::create([ + 'remote_socket' => ($unix ? 'unix://' : 'tcp://').$address, + 'api_version' => '1.45', + 'timeout' => 3000, + ]); + $response = $client->sendRequest(new Request('GET', '/stream')); + $stream = new DockerRawStream($response->getBody(), $multiplexed); + $stdout = ''; + $stderr = ''; + $firstCallback = null; + $lastCallback = null; + $stream->onStdout(static function (string $output) use (&$stdout, &$firstCallback, &$lastCallback): void { + $firstCallback ??= hrtime(true); + $lastCallback = hrtime(true); + $stdout .= $output; + }); + $stream->onStderr(static function (string $output) use (&$stderr, &$firstCallback, &$lastCallback): void { + $firstCallback ??= hrtime(true); + $lastCallback = hrtime(true); + $stderr .= $output; + }); + $stream->wait(); + + self::assertSame($multiplexed ? "first\nlast\n" : "first\r\nerror\r\nlast\r\nfinal\r\n", $stdout); + self::assertSame($multiplexed ? "error\nfinal\n" : '', $stderr); + self::assertNotNull($firstCallback); + self::assertGreaterThan(500_000_000, $lastCallback - $firstCallback, 'Output was buffered until the peer finished.'); + self::assertStringContainsString('GET /v1.45/stream HTTP/1.1', $this->serverResult()['request']); + } +} diff --git a/tests/TransportTestCase.php b/tests/TransportTestCase.php new file mode 100644 index 000000000..2a4ed52c9 --- /dev/null +++ b/tests/TransportTestCase.php @@ -0,0 +1,114 @@ +directory = sys_get_temp_dir().'/docker-test-'.bin2hex(random_bytes(6)); + mkdir($this->directory, 0700); + + foreach (['DOCKER_HOST', 'DOCKER_API_VERSION', 'DOCKER_TLS_VERIFY', 'DOCKER_CERT_PATH', 'DOCKER_PEER_NAME'] as $name) { + $this->environment[$name] = getenv($name); + putenv($name); + } + } + + protected function tearDown(): void + { + $this->server?->stop(0); + (new Filesystem())->remove($this->directory); + foreach ($this->environment as $name => $value) { + putenv(false === $value ? $name : $name.'='.$value); + } + parent::tearDown(); + } + + protected function startServer(array $options = [], bool $unix = false, string $fixture = 'socket-server.php'): string + { + $socket = $this->directory.'/sock'; + $options['address'] = $unix ? 'unix://'.$socket : 'tcp://127.0.0.1:0'; + $this->server = new Process([\PHP_BINARY, '-d', 'display_errors=stderr', __DIR__.'/fixtures/'.$fixture, json_encode($options, \JSON_THROW_ON_ERROR)]); + $this->server->setTimeout(10); + $this->server->start(); + $ready = $this->server->waitUntil(fn () => str_contains($this->server->getOutput(), "\n")); + $this->assertTrue($ready, $this->server->getErrorOutput()); + $message = json_decode(explode("\n", $this->server->getOutput())[0], true, 512, \JSON_THROW_ON_ERROR); + + return $unix ? $socket : $message['address']; + } + + protected function serverResult(int $index = 0): array + { + $this->server->wait(); + $this->assertTrue($this->server->isSuccessful(), $this->server->getErrorOutput()); + + return json_decode(explode("\n", $this->server->getOutput())[$index + 1], true, 512, \JSON_THROW_ON_ERROR); + } + + protected function serverTlsOptions(): array + { + return [ + 'local_cert' => $this->directory.'/server.pem', + 'local_pk' => $this->directory.'/server-key.pem', + ]; + } + + protected function createCertificates(string $serverNames = 'DNS:docker.test,DNS:localhost,IP:127.0.0.1'): void + { + $config = $this->directory.'/openssl.cnf'; + file_put_contents( + $config, + str_replace( + 'SERVER_NAMES', + $serverNames, + <<<'CONFIG' + [req] + distinguished_name = dn + [dn] + [ca] + basicConstraints = critical,CA:TRUE + keyUsage = critical,keyCertSign,cRLSign + [server] + basicConstraints = critical,CA:FALSE + keyUsage = critical,digitalSignature,keyEncipherment + extendedKeyUsage = serverAuth + subjectAltName = SERVER_NAMES + [client] + basicConstraints = critical,CA:FALSE + keyUsage = critical,digitalSignature,keyEncipherment + extendedKeyUsage = clientAuth + CONFIG + ) + ); + $options = ['config' => $config, 'private_key_bits' => 2048, 'digest_alg' => 'sha256']; + $caKey = openssl_pkey_new($options); + $caRequest = openssl_csr_new(['commonName' => 'Docker PHP test CA'], $caKey, $options); + $ca = openssl_csr_sign($caRequest, null, $caKey, 1, $options + ['x509_extensions' => 'ca'], 1); + $this->assertNotFalse($ca); + openssl_x509_export_to_file($ca, $this->directory.'/ca.pem'); + + foreach (['server' => 'docker.test', 'client' => 'docker-client'] as $type => $name) { + $key = openssl_pkey_new($options); + $request = openssl_csr_new(['commonName' => $name], $key, $options); + $certificate = openssl_csr_sign($request, $ca, $caKey, 1, $options + ['x509_extensions' => $type], 'server' === $type ? 2 : 3); + $this->assertNotFalse($certificate); + openssl_x509_export_to_file($certificate, $this->directory.('server' === $type ? '/server.pem' : '/cert.pem')); + openssl_pkey_export_to_file($key, $this->directory.('server' === $type ? '/server-key.pem' : '/key.pem'), null, $options); + } + } +} diff --git a/tests/UnexpectedStatusTest.php b/tests/UnexpectedStatusTest.php new file mode 100644 index 000000000..72ad3d5f8 --- /dev/null +++ b/tests/UnexpectedStatusTest.php @@ -0,0 +1,154 @@ + 'application/json']; + + private array $deprecations = []; + + protected function setUp(): void + { + set_error_handler(function (int $level, string $message): bool { + $this->deprecations[] = $message; + + return true; + }, \E_USER_DEPRECATED); + } + + protected function tearDown(): void + { + restore_error_handler(); + } + + public function testUnhandledErrorThrowsByDefault(): void + { + $docker = $this->docker(new Response(400, self::JSON, '{"message":"Minimum memory limit allowed is 6MB"}')); + + $this->expectException(UnexpectedClientErrorException::class); + $this->expectExceptionMessage('Docker returned HTTP 400 for POST /containers/web/update: Minimum memory limit allowed is 6MB'); + $docker->containerUpdate('web', new ContainersIdUpdatePostBody()); + } + + public function testOptOutReturnsNull(): void + { + $docker = $this->docker(new Response(400, self::JSON, '{"message":"Minimum memory limit allowed is 6MB"}'))->throwOnUnexpectedStatus(false); + + $this->assertNull($docker->containerUpdate('web', new ContainersIdUpdatePostBody())); + $this->assertSame([], $this->deprecations); + } + + public function testClientErrorDetails(): void + { + $docker = $this->docker(new Response(409, self::JSON, '{"message":"network with name web already exists"}'))->throwOnUnexpectedStatus(); + + try { + $docker->containerUpdate('web', new ContainersIdUpdatePostBody()); + $this->fail('An unhandled 409 should throw.'); + } catch (UnexpectedClientErrorException $error) { + $this->assertInstanceOf(ClientException::class, $error); + $this->assertSame(409, $error->getStatusCode()); + $this->assertSame(409, $error->getCode()); + $this->assertSame('POST', $error->getMethod()); + $this->assertSame('/containers/web/update', $error->getPath()); + $this->assertSame('network with name web already exists', $error->getErrorMessage()); + $this->assertSame('{"message":"network with name web already exists"}', (string) $error->getResponse()->getBody()); + } + $this->assertSame([], $this->deprecations); + } + + public function testServerErrorWithPlainTextBody(): void + { + $docker = $this->docker(new Response(500, ['Content-Type' => 'text/plain'], "invalid reference format\n"))->throwOnUnexpectedStatus(); + + $this->expectException(UnexpectedServerErrorException::class); + $this->expectExceptionMessage('Docker returned HTTP 500 for POST /images/create: invalid reference format'); + $docker->imageCreate(null, ['fromImage' => 'Bad Name']); + } + + public function testDocumentedErrorsKeepGeneratedExceptions(): void + { + $docker = $this->docker(new Response(404, self::JSON, '{"message":"No such container: web"}')); + + try { + $docker->containerInspect('web'); + $this->fail('A documented 404 should throw the generated exception.'); + } catch (ContainerInspectNotFoundException) { + } + $this->assertSame([], $this->deprecations); + } + + public function testSuccessWithoutBodyStillReturnsNull(): void + { + $docker = $this->docker(new Response(304))->throwOnUnexpectedStatus(); + + $this->assertNull($docker->containerStart('web')); + $this->assertSame([], $this->deprecations); + } + + public function testRawResponsesAreNotChecked(): void + { + $docker = $this->docker(new Response(400, self::JSON, '{"message":"bad"}'))->throwOnUnexpectedStatus(); + + $response = $docker->containerUpdate('web', new ContainersIdUpdatePostBody(), Docker::FETCH_RESPONSE); + + $this->assertSame(400, $response->getStatusCode()); + } + + public function testSuccessfulStreamsAreNotBuffered(): void + { + $response = new Response(200, ['Content-Type' => DockerRawStream::MULTIPLEXED_HEADER], pack('CxxxN', 1, 5).'hello'); + $docker = $this->docker($response)->throwOnUnexpectedStatus(); + + $stream = $docker->containerLogs('web', ['stdout' => true]); + + $this->assertInstanceOf(DockerRawStream::class, $stream); + $this->assertSame(0, $response->getBody()->tell(), 'Successful responses must stay unread'); + } + + public function testUnlimitedPidsLimitDecodes(): void + { + // Docker reports a container without a PID limit as the largest uint64. + $docker = $this->docker(new Response(200, self::JSON, '{"read":"t1","pids_stats":{"current":3,"limit":18446744073709551615}}')); + + $stats = $docker->containerStats('web', ['stream' => false]); + + if ($stats instanceof \stdClass) { + // Before API 1.48 the sample is decoded without generated setters. + $this->assertSame(18446744073709551615.0, $stats->pids_stats->limit); + } else { + $this->assertSame(\PHP_INT_MAX, $stats->getPidsStats()->getLimit()); + } + } + + private function docker(ResponseInterface ...$responses): Docker + { + $httpClient = new class([new Response(200, self::JSON, '{}'), ...$responses]) implements ClientInterface { + public function __construct(private array $responses) + { + } + + public function sendRequest(RequestInterface $request): ResponseInterface + { + return array_shift($this->responses) ?? throw new \LogicException('Unexpected request '.$request->getUri()); + } + }; + + return Docker::create($httpClient, [], [], false); + } +} diff --git a/tests/fixtures/interactive-server.php b/tests/fixtures/interactive-server.php new file mode 100644 index 000000000..197b8bcde --- /dev/null +++ b/tests/fixtures/interactive-server.php @@ -0,0 +1,68 @@ + $config['ssl'] ?? []]); +$server = stream_socket_server($config['address'], $errno, $error, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context); +if ($server === false) { + throw new RuntimeException($error, $errno); +} +echo json_encode(['address' => stream_socket_get_name($server, false)], JSON_THROW_ON_ERROR) . "\n"; +fflush(STDOUT); +for ($index = 0; $index < 2; ++$index) { + $connection = stream_socket_accept($server, 5); + if ($connection === false) { + throw new RuntimeException('No interactive test connection.'); + } + stream_set_timeout($connection, 3); + if (isset($config['ssl']) && true !== stream_socket_enable_crypto($connection, true, STREAM_CRYPTO_METHOD_TLSv1_2_SERVER)) { + throw new RuntimeException('Fixture TLS handshake failed.'); + } + $request = ''; + while (false !== ($line = fgets($connection))) { + $request .= $line; + if ($line === "\r\n") { + break; + } + } + $body = ''; + if (preg_match('/\r\nContent-Length:\s*(\d+)/i', $request, $match)) { + while (strlen($body) < (int) $match[1]) { + $bytes = fread($connection, (int) $match[1] - strlen($body)); + if ($bytes === false || $bytes === '') { + throw new RuntimeException('Incomplete HTTP body.'); + } + $body .= $bytes; + } + } + if ($index === 0) { + echo json_encode(['request' => $request], JSON_THROW_ON_ERROR) . "\n"; + fwrite($connection, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}"); + fclose($connection); + continue; + } + $frame = static fn (int $channel, string $bytes): string => ($config['tty'] ?? false) ? $bytes : pack('CxxxN', $channel, strlen($bytes)) . $bytes; + fwrite($connection, "HTTP/1.1 101 UPGRADED\r\nConnection: Upgrade\r\nUpgrade: tcp\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n" . $frame(1, 'ready:')); + $stdin = ''; + while (!feof($connection)) { + $chunk = fread($connection, 16384); + if ($chunk === false) { + throw new RuntimeException('Cannot read fixture stdin.'); + } + if ($chunk !== '') { + $stdin .= $chunk; + fwrite($connection, $frame(1, $chunk)); + if (($config['tty'] ?? false) && strlen($stdin) >= $config['input_length']) { + break; + } + } elseif (stream_get_meta_data($connection)['timed_out']) { + throw new RuntimeException('The client did not half-close stdin.'); + } + } + fwrite($connection, $frame(1, ':done') . $frame(2, 'error')); + echo json_encode(['request' => $request, 'body' => $body, 'stdin_hash' => hash('sha256', $stdin), 'stdin_length' => strlen($stdin)], JSON_THROW_ON_ERROR) . "\n"; + fclose($connection); +} +fclose($server); diff --git a/tests/fixtures/socket-server.php b/tests/fixtures/socket-server.php new file mode 100644 index 000000000..0ff25d471 --- /dev/null +++ b/tests/fixtures/socket-server.php @@ -0,0 +1,99 @@ + $config['ssl'] ?? []]); +$server = stream_socket_server($config['address'], $errno, $error, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context); +if (false === $server) { + throw new RuntimeException($error, $errno); +} + +echo json_encode(['address' => stream_socket_get_name($server, false)], JSON_THROW_ON_ERROR)."\n"; +fflush(STDOUT); + +$responses = $config['responses'] ?? [($config['upgrade'] ?? false) + ? ['status' => 101, 'body' => 'stream-output', 'headers' => ['Connection' => 'Upgrade', 'Upgrade' => 'tcp']] + : ['body' => 'OK']]; + +// Answer the client's unversioned API negotiation ping like a daemon, without +// using up a scripted response. Pings are not reported to the test. +$daemonApiVersion = $config['daemon_api_version'] ?? '1.99'; +$pings = 0; +$response = array_shift($responses); +while (null !== $response) { + $connection = stream_socket_accept($server, 5); + if (false === $connection) { + throw new RuntimeException('No test client connected.'); + } + stream_set_timeout($connection, 5); + + if (isset($config['ssl']) && true !== @stream_socket_enable_crypto($connection, true, STREAM_CRYPTO_METHOD_TLSv1_2_SERVER)) { + echo json_encode(['tls' => false], JSON_THROW_ON_ERROR)."\n"; + fclose($connection); + fclose($server); + exit(0); + } + + $request = ''; + while (false !== ($line = fgets($connection))) { + $request .= $line; + if ("\r\n" === $line) { + break; + } + } + $body = ''; + if (preg_match('/\r\nContent-Length:\s*(\d+)/i', $request, $match)) { + while (strlen($body) < (int) $match[1]) { + $chunk = fread($connection, (int) $match[1] - strlen($body)); + if (false === $chunk || '' === $chunk) { + throw new RuntimeException('Incomplete request body.'); + } + $body .= $chunk; + } + } + + if (($config['negotiation'] ?? true) && str_starts_with($request, "GET /_ping HTTP/1.1\r\n") && $pings < 3) { + ++$pings; + $headers = null === $daemonApiVersion ? '' : 'API-Version: '.$daemonApiVersion."\r\n"; + fwrite($connection, "HTTP/1.1 200 OK\r\n".$headers."Content-Length: 2\r\nConnection: close\r\n\r\nOK"); + fclose($connection); + continue; + } + + $result = ['request' => $request, 'body' => $body]; + $options = stream_context_get_options($connection); + if (isset($options['ssl']['peer_certificate'])) { + $result['peer'] = openssl_x509_parse($options['ssl']['peer_certificate'])['subject']['CN']; + } + echo json_encode($result, JSON_THROW_ON_ERROR)."\n"; + + if ('' !== $request) { + $body = isset($response['body_base64']) ? base64_decode($response['body_base64'], true) : ($response['body'] ?? ''); + $status = $response['status'] ?? 200; + $headers = $response['headers'] ?? []; + if (101 !== $status) { + $headers += ['Connection' => 'close']; + if (!isset($headers['Transfer-Encoding'])) { + $headers += ['Content-Length' => strlen($body)]; + } + } + $message = 'HTTP/1.1 '.$status." Test\r\n"; + foreach ($headers as $name => $value) { + $message .= $name.': '.$value."\r\n"; + } + $segments = isset($response['segments_base64']) + ? array_map(static fn (string $segment): string => base64_decode($segment, true), $response['segments_base64']) + : [$body]; + // Send the first segment with the headers to exercise PHP's read buffer. + fwrite($connection, $message."\r\n".array_shift($segments)); + foreach ($segments as $segment) { + usleep(($response['delay_ms'] ?? 0) * 1000); + fwrite($connection, $segment); + } + } + fclose($connection); + $response = array_shift($responses); +} +fclose($server);