on c80d2d2 help sign in
21 files changed+181−680
since splitsnapshots
unifiedsplit
.gitignore−1 .travis.yml+3−25 CHANGELOG.md−71 CONTRIBUTING.md+2−12 LICENSE+1−1 Makefile+7−22 README.md+9−26 docker.cabal+12−26 src/Docker/Client.hs+1−1 src/Docker/Client/Api.hs+3−21 src/Docker/Client/Http.hs+7−40 src/Docker/Client/Internal.hs+3−11 src/Docker/Client/Types.hs+45−170 stack-7.10.yaml+5−5 stack-8.0.2.yaml−4 stack-8.0.yaml+1−2 stack-8.6.4.yaml−4 stack-8.8.2.yaml−5 stack.yaml+1−1 tests/Dockerfile+1−1 tests/tests.hs+80−231
.gitignore−1
@@ -4,4 +4,3 @@
44*~
55.stack-work/
66dist-newstyle
7−/cabal.project.local
.travis.yml+3−25
@@ -22,30 +22,8 @@ services:
2222 - docker
2323
2424env:
25− global:
26− - RUN_INTEGRATION_TESTS=1
27− - STACK_ARGS=""
28−
29− matrix:
30− - DOCKER_VERSION="1.12.3-0~trusty" GHCVER=7.10
31− - DOCKER_VERSION="1.13.1-0~ubuntu-trusty" GHCVER=7.10
32− - DOCKER_VERSION="17.05.0~ce-0~ubuntu-trusty" GHCVER=7.10
33−
34− - DOCKER_VERSION="1.12.3-0~trusty" GHCVER=8.0
35− - DOCKER_VERSION="1.13.1-0~ubuntu-trusty" GHCVER=8.0
36− - DOCKER_VERSION="17.05.0~ce-0~ubuntu-trusty" GHCVER=8.0
37−
38− - DOCKER_VERSION="1.12.3-0~trusty" GHCVER=8.0.2
39− - DOCKER_VERSION="1.13.1-0~ubuntu-trusty" GHCVER=8.0.2
40− - DOCKER_VERSION="17.05.0~ce-0~ubuntu-trusty" GHCVER=8.0.2
41−
42− - DOCKER_VERSION="1.12.3-0~trusty" GHCVER=8.6.4
43− - DOCKER_VERSION="1.13.1-0~ubuntu-trusty" GHCVER=8.6.4
44− - DOCKER_VERSION="17.05.0~ce-0~ubuntu-trusty" GHCVER=8.6.4
45−
46− - DOCKER_VERSION="1.12.3-0~trusty" GHCVER=8.8.2
47− - DOCKER_VERSION="1.13.1-0~ubuntu-trusty" GHCVER=8.8.2
48− - DOCKER_VERSION="17.05.0~ce-0~ubuntu-trusty" GHCVER=8.8.2
25+ - GHCVER=7.10 STACK_ARGS=""
26+ - GHCVER=8.0 STACK_ARGS=""
4927
5028addons:
5129 apt:
@@ -57,7 +35,7 @@ before_install:
5735 - sudo sh -c 'echo "deb https://apt.dockerproject.org/repo ubuntu-trusty main" > /etc/apt/sources.list.d/docker.list'
5836 - sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
5937 - sudo apt-get update
60− - sudo apt-get -qqy -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" install docker-engine=$DOCKER_VERSION
38+ - sudo apt-get -qqy -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" install docker-engine=1.12.3-0~trusty
6139
6240install:
6341 - mkdir -p "$HOME"/.local/bin
CHANGELOG.md−71
@@ -1,76 +1,5 @@
11# CHANGELOG
22
3−## 0.6.0.3 (2020-02-17)
4−
5−- Support for ghc 8.8.2.
6−- Bump dependency version.
7−- Use MonadFail for later versions.
8−
9−## 0.6.0.1 (2019-05-23)
10−
11−- Support ghc 8.6.4.
12−- Bump containers version.
13−
14−## 0.6.0.0 (2018-06-28)
15−
16−- Rename DeleteOpts to ContainerDeleteOpts.
17−- Implement image deletion.
18−- Bump aeson version.
19−- Implement network aliases.
20−- Implement creating/deleting networks.
21−
22−## 0.5.1.1 (2018-03-09)
23−
24−- Bump aeson version.
25−
26−## 0.5.1.0 (2018-02-23)
27−
28−- Support http-conduit-2.3.0.
29−- Bump http-types versions.
30−
31−## 0.5.0.1 (2018-01-26)
32−
33−- Bumps upper bound for http-types (properly this time).
34−
35−## 0.5.0.0 (2018-01-24)
36−
37−- Added (some) contribution and general docs
38−- Fix case when stopping non-existent container
39−- Added more integration tests
40−- Fixed error while parsing list container endpoint output
41−- Changed State/Status data type (related to the above fix)
42−- Added tests against different docker version to travis CIA
43−- Fixed EnvVar JSON encoding
44−- Fixed NetworkMode parsing
45−- Allow http-types 0.11
46−
47−## 0.4.1.1 (2017-10-16)
48−
49−- Small change to add env var for skipping integration tests.
50− This is mostly to avoid running those on stackage.
51−
52−## 0.4.1.0 (2017-10-04)
53−
54−- Relaxed aeson, tls and time upper bounds
55−
56−
57−## 0.4.0.2 (2017-09-19)
58−
59−- Support LTS 9.4
60−
61−## 0.4.0.1 (2017-06-29)
62−
63−- fixes omKillDisable parsing from json
64−- adds Entrypoint data type and tests edge cases
65−- more tests
66−- small comsmetic changes
67−
68−## 0.4.0.0 (2017-03-20)
69−
70−- Adds streaming support via conduits (changes API a bit hence the major version release)
71−- Added support for streaming log output
72−- Added support for pulling images from the hub (and streaming the output)
73−
743## 0.3.0.1 (2016-09-07)
754
765- Small cosmetic changes and marking OVERLAPPING instance
CONTRIBUTING.md+2−12
@@ -1,14 +1,4 @@
1−# Contributing
1+# TODO
22
3−If you wish to contribute please see [any issue on GitHub tagged with "help
4−wanted"](https://github.com/denibertovic/docker-hs/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22).
5−Before starting to work, consider commenting on the issue you want to resolve or
6−open a new issue to discuss design decisions and implementation details. This is
7−so that no development cycles go to waste on implementing a feature that might
8−not get merged either because of implementation details or other reasons.
3+Add basic guidelines here, things like style guide (using .configuration files from the repo) etc etc.
94
10−Make sure to submit your PR's against the `master` branch.
11−
12−## Project Setup
13−
14−See the `README.md` file on how to setup the project on your development machine.
LICENSE+1−1
@@ -1,4 +1,4 @@
1−Copyright (c) 2014, Deni Bertovic
1+Copyright (c) 2016, Deni Bertovic
22
33All rights reserved.
44
Makefile+7−22
@@ -1,6 +1,4 @@
1−.PHONY: build repl test release help
2−
3−.DEFAULT_GOAL = help
1+.PHONY: build repl test release tag
42
53PROJECT_NAME ?= $(shell grep "^name" docker.cabal | cut -d " " -f17)
64VERSION ?= $(shell grep "^version:" docker.cabal | cut -d " " -f14)
@@ -8,35 +6,22 @@ RESOLVER ?= $(shell grep "^resolver:" stack.yaml | cut -d " " -f2)
86GHC_VERSION ?= $(shell stack ghc -- --version | cut -d " " -f8)
97ARCH=$(shell uname -m)
108
11−## Run build
129build:
1310 @stack build
1411
15−## Run repl
1612repl:
1713 @stack repl
1814
19−## Run tests. Example RUN_INTEGRATION_TESTS=1 make test
2015test:
21− @RUN_INTEGRATION_TESTS=1 stack test
16+ @stack test
17+
18+tag:
19+ @echo Tagging version: ${VERSION}
20+ @git tag ${VERSION}
2221
23−## Cut new release
24−release:
22+release: tag
2523 @stack build --haddock
2624 @stack sdist
2725 @echo "\n\nDone. Now run: \n\nstack upload <path_to_tarball>\n"
2826 @echo "\nAnd: \n\ngit tag ${VERSION} && git push --tags\n"
2927
30−## Show help screen.
31−help:
32− @echo "Please use \`make <target>' where <target> is one of\n\n"
33− @awk '/^[a-zA-Z\-\_0-9]+:/ { \
34− helpMessage = match(lastLine, /^## (.*)/); \
35− if (helpMessage) { \
36− helpCommand = substr($$1, 0, index($$1, ":")-1); \
37− helpMessage = substr(lastLine, RSTART + 3, RLENGTH); \
38− printf "%-30s %s\n", helpCommand, helpMessage; \
39− } \
40− } \
41− { lastLine = $$0 }' $(MAKEFILE_LIST)
42−
README.md+9−26
@@ -7,42 +7,25 @@
77
88## Current state
99
10−Supported Docker Engine Api version: `v1.24` and onwards.
10+**API is still not stable.**
11+
12+Supported Docker Engine Api version: `v1.24`
1113
1214Anything upward of that should work since Docker versions their API.
1315Older docker version and engine api versions are not supported at the moment.
1416
15−## Documentation
16−
17−The API-documentation is available at
18−[Hackage](https://hackage.haskell.org/package/docker). There are also some
19−usage-examples in the main library source file,
20−[`Client.hs`](https://hackage.haskell.org/package/docker/docs/Docker-Client.html).
21−
2217## Contributing
2318
24−Please see [CONTRIBUTING.md](CONTRIBUTING.md).
25−
26−### Project Setup
19+If you wish to contribute please see any issue tagged with "help wanted".
20+Make sure to submit your PR's against the `master` branch.
2721
28−For working on the library, you need the Haskell Tool Stack installed (see [the
29−Haskell Tool Stack
30−website](https://docs.haskellstack.org/en/stable/install_and_upgrade/)). You
31−also need `make` to use the `Makefile` included in the project. Run `make help`
32−to see the available commands (for building, running the tests and releasing).
22+Please consider filling an Issue first and discuss design decisions and implementation details before
23+writing any code. This is so that no development cycles go to waste on implementing a feature that
24+might not get merged either because of implementation details or other reasons.
3325
34−### Tests
35−
36−Tests are located in the `tests` directory and can be run with `make test`. This
37−only runs the unit tests.
38−
39−To run integration tests, you need Docker installed and listening on Port `2375`
40−of `localhost` (docker only listens to a Unix socket by default, see the [Docker
41−documentation](https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-socket-option)
42−for details). Set the environment variable `RUN_INTEGRATION_TESTS`, i.e.
43−`RUN_INTEGRATION_TESTS=1 make test`.
4426
4527## IRC
4628
4729If you have any questions or suggestions you can find the maintainers in `#docker-haskell`
4830on freenode.
31+
docker.cabal+12−26
@@ -1,5 +1,5 @@
11name: docker
2−version: 0.6.0.3
2+version: 0.3.0.1
33synopsis: An API client for docker written in Haskell
44description: See API documentation below.
55homepage: https://github.com/denibertovic/docker-hs
@@ -14,29 +14,24 @@ extra-source-files: README.md
1414cabal-version: >=1.10
1515stability: experimental
1616
17−-- Flag small-http-conduit
18−-- Description: Resolve whether http-conduit < 2.3.0.
19−-- Manual: False
20−-- Default: True
21−
2217library
23− default-extensions: DeriveGeneric, OverloadedStrings, ScopedTypeVariables, ExplicitForAll, MultiParamTypeClasses, FlexibleContexts, GeneralizedNewtypeDeriving, RankNTypes, DeriveFunctor, FlexibleInstances, CPP
18+ default-extensions: DeriveGeneric, OverloadedStrings, ScopedTypeVariables, ExplicitForAll, MultiParamTypeClasses, FlexibleContexts, GeneralizedNewtypeDeriving, RankNTypes, DeriveFunctor, FlexibleInstances
2419 hs-source-dirs: src
2520 exposed-modules: Docker.Client, Docker.Client.Api, Docker.Client.Types, Docker.Client.Internal, Docker.Client.Http, Docker.Client.Utils
2621 -- other-modules: Docker.Internal
2722 build-depends: base >= 4.7 && < 5
28− , aeson >= 0.9.0 && < 2.0.0
23+ , aeson >= 0.9.0 && < 1.1.0
2924 , blaze-builder >= 0.4.0 && < 0.5.0
3025 , bytestring >= 0.10.0 && < 0.11.0
31− , containers >= 0.5.0 && < 0.7.0
26+ , containers >= 0.5.0 && < 0.6.0
3227 , data-default-class >= 0.0.1 && < 0.2.0
33− , http-client >= 0.4.0 && < 0.7.0
34− , http-types >= 0.9 && < 0.13
35− , vector
28+ , http-client >= 0.4.0 && < 0.5.0
29+ , http-types >= 0.9 && < 0.10.0
3630 , conduit
3731 , conduit-combinators
3832 , conduit-extra
3933 , exceptions
34+ , http-conduit
4035 , monad-control
4136 , resourcet
4237 , transformers
@@ -51,20 +46,13 @@ library
5146 , mtl >= 2.0.0 && < 3.0.0
5247 , network >= 2.6.0
5348 , text >= 1.0.0 && < 2.0.0
54− , time >= 1.5.0 && < 2.0.0
49+ , time >= 1.5.0 && < 1.7.0
5550 , scientific >= 0.3.0 && < 0.4.0
56− , tls >= 1.3.7 && < 1.6.0
51+ , tls >= 1.3.7 && < 1.4.0
5752 , unordered-containers >= 0.2.0 && < 0.3.0
58− , x509 >= 1.6.0 && < 1.8.0
59− , x509-store >= 1.6.0 && < 1.8.0
60− , x509-system >= 1.6.0 && < 1.8.0
61− , http-conduit
62− , unliftio-core >= 0.1.0.0 && < 0.2.0
63− -- if flag(small-http-conduit)
64− -- build-depends: http-conduit < 2.3.0
65− -- else
66− -- build-depends: http-conduit >= 2.3.0
67− -- , unliftio-core
53+ , x509 >= 1.6.0 && < 1.7.0
54+ , x509-store >= 1.6.0 && < 1.7.0
55+ , x509-system >= 1.6.0 && < 1.7.0
6856 default-language: Haskell2010
6957 ghc-options: -Wall -fno-warn-name-shadowing
7058
@@ -73,7 +61,6 @@ test-suite docker-hs-tests
7361 , bytestring
7462 , connection
7563 , docker
76− , directory
7764 , aeson
7865 , containers
7966 , unordered-containers
@@ -89,7 +76,6 @@ test-suite docker-hs-tests
8976 , transformers
9077 , QuickCheck
9178 , process
92− , vector
9379 type: exitcode-stdio-1.0
9480 main-is: tests.hs
9581 hs-source-dirs: tests
src/Docker/Client.hs+1−1
@@ -3,7 +3,7 @@
33
44{-|
55Module : Docker.Client
6−Copyright : (c) Deni Bertovic, 2014
6+Copyright : (c) Deni Bertovic, 2016
77License : BSD3
88Maintainer : deni@denibertovic.com
99Stability : experimental
src/Docker/Client/Api.hs+3−21
@@ -18,12 +18,8 @@ module Docker.Client.Api (
1818 , getContainerLogsStream
1919 -- * Images
2020 , listImages
21− , deleteImage
2221 , buildImageFromDockerfile
2322 , pullImage
24− -- * Network
25− , createNetwork
26− , removeNetwork
2723 -- * Other
2824 , getDockerVersion
2925 ) where
@@ -47,7 +43,7 @@ import Docker.Client.Types
4743import Docker.Client.Utils
4844
4945requestUnit :: (MonadIO m, MonadMask m) => HttpVerb -> Endpoint -> DockerT m (Either DockerError ())
50−requestUnit verb endpoint = fmap (const ()) <$> requestHelper verb endpoint
46+requestUnit verb endpoint = const (Right ()) <$> requestHelper verb endpoint
5147
5248requestHelper :: (MonadIO m, MonadMask m) => HttpVerb -> Endpoint -> DockerT m (Either DockerError BSL.ByteString)
5349requestHelper verb endpoint = requestHelper' verb endpoint Conduit.sinkLbs
@@ -94,12 +90,6 @@ listContainers opts = requestHelper GET (ListContainersEndpoint opts) >>= parseR
9490listImages :: forall m. (MonadIO m, MonadMask m) => ListOpts -> DockerT m (Either DockerError [Image])
9591listImages opts = requestHelper GET (ListImagesEndpoint opts) >>= parseResponse
9692
97−-- | Deletes an image with the given 'ImageID'.
98−-- See "ImageDeleteOpts" for options and use 'defaultImageDeleteOpts' for sane
99−-- defaults.
100−deleteImage :: forall m. (MonadIO m, MonadMask m) => ImageDeleteOpts -> ImageID -> DockerT m (Either DockerError ())
101−deleteImage dopts iid = requestUnit DELETE $ DeleteImageEndpoint dopts iid
102−
10393-- | Creates a docker container but does __not__ start it. See
10494-- 'CreateOpts' for a list of options and you can use 'defaultCreateOpts'
10595-- for some sane defaults.
@@ -145,9 +135,9 @@ unpauseContainer :: forall m. (MonadIO m, MonadMask m) => ContainerID -> DockerT
145135unpauseContainer cid = requestUnit GET $ UnpauseContainerEndpoint cid
146136
147137-- | Deletes a container with the given 'ContainerID'.
148−-- See "ContainerDeleteOpts" for options and use 'defaultContainerDeleteOpts' for sane
138+-- See "DeleteOpts" for options and use 'defaultDeleteOpts' for sane
149139-- defaults.
150−deleteContainer :: forall m. (MonadIO m, MonadMask m) => ContainerDeleteOpts -> ContainerID -> DockerT m (Either DockerError ())
140+deleteContainer :: forall m. (MonadIO m, MonadMask m) => DeleteOpts -> ContainerID -> DockerT m (Either DockerError ())
151141deleteContainer dopts cid = requestUnit DELETE $ DeleteContainerEndpoint dopts cid
152142
153143-- | Gets 'ContainerDetails' for a given 'ContainerID'.
@@ -217,11 +207,3 @@ buildImageFromDockerfile opts base = do
217207pullImage :: forall m b . (MonadIO m, MonadMask m) => T.Text -> Tag -> Sink BS.ByteString m b -> DockerT m (Either DockerError b)
218208pullImage name tag = requestHelper' POST (CreateImageEndpoint name tag Nothing)
219209
220−-- | Creates network
221−createNetwork :: forall m. (MonadIO m, MonadMask m) => CreateNetworkOpts -> DockerT m (Either DockerError NetworkID)
222−createNetwork opts = requestHelper POST (CreateNetworkEndpoint opts) >>= parseResponse
223−
224−-- | Removes a network
225−removeNetwork :: forall m. (MonadIO m, MonadMask m) => NetworkID -> DockerT m (Either DockerError ())
226−removeNetwork nid = requestUnit DELETE $ RemoveNetworkEndpoint nid
227−
src/Docker/Client/Http.hs+7−40
@@ -5,9 +5,6 @@ module Docker.Client.Http where
55
66-- import Control.Monad.Base (MonadBase(..), liftBaseDefault)
77import Control.Monad.Catch (MonadMask (..))
8−#if MIN_VERSION_http_conduit(2,3,0)
9−import Control.Monad.IO.Unlift (MonadUnliftIO)
10−#endif
118import Control.Monad.Reader (ReaderT (..), runReaderT)
129import qualified Data.ByteString.Char8 as BSC
1310import qualified Data.ByteString.Lazy as BL
@@ -20,7 +17,7 @@ import Data.X509.CertificateStore (makeCertificateStore)
2017import Data.X509.File (readKeyFile, readSignedObject)
2118import Network.HTTP.Client (defaultManagerSettings,
2219 managerRawConnection, method,
23− newManager, parseRequest,
20+ newManager, parseUrl,
2421 requestBody, requestHeaders)
2522import qualified Network.HTTP.Client as HTTP
2623import Network.HTTP.Client.Internal (makeConnection)
@@ -97,7 +94,7 @@ runDockerT (opts, h) r = runReaderT (unDockerT r) (opts, h)
9794mkHttpRequest :: HttpVerb -> Endpoint -> DockerClientOpts -> Maybe Request
9895mkHttpRequest verb e opts = request
9996 where fullE = T.unpack (baseUrl opts) ++ T.unpack (getEndpoint (apiVer opts) e)
100− initialR = parseRequest fullE
97+ initialR = parseUrl fullE
10198 request' = case initialR of
10299 Just ir ->
103100 return $ ir {method = (encodeUtf8 . T.pack $ show verb),
@@ -107,30 +104,18 @@ mkHttpRequest verb e opts = request
107104 requestHeaders = [("Content-Type", "application/json; charset=utf-8")]}) $ getEndpointRequestBody e) <$> request'
108105 -- Note: Do we need to set length header?
109106
110−defaultHttpHandler :: (
111−#if MIN_VERSION_http_conduit(2,3,0)
112− MonadUnliftIO m,
113−#endif
114− MonadIO m, MonadMask m) => m (HttpHandler m)
107+defaultHttpHandler :: (MonadIO m, MonadMask m) => m (HttpHandler m)
115108defaultHttpHandler = do
116109 manager <- liftIO $ newManager defaultManagerSettings
117110 return $ httpHandler manager
118111
119−httpHandler :: (
120−#if MIN_VERSION_http_conduit(2,3,0)
121− MonadUnliftIO m,
122−#endif
123− MonadIO m, MonadMask m) => HTTP.Manager -> HttpHandler m
112+httpHandler :: (MonadIO m, MonadMask m) => HTTP.Manager -> HttpHandler m
124113httpHandler manager = HttpHandler $ \request' sink -> do -- runResourceT ..
125114 let request = NHS.setRequestManager manager request'
126115 try (NHS.httpSink request sink) >>= \res -> case res of
127116 Right res -> return res
128−#if MIN_VERSION_http_client(0,5,0)
129− Left e@(HTTP.HttpExceptionRequest _ HTTP.ConnectionFailure{}) -> return $ Left $ DockerConnectionError e
130−#else
131117 Left e@HTTP.FailedConnectionException{} -> return $ Left $ DockerConnectionError e
132118 Left e@HTTP.FailedConnectionException2{} -> return $ Left $ DockerConnectionError e
133−#endif
134119 Left e -> return $ Left $ GenericDockerError (T.pack $ show e)
135120
136121-- | Connect to a unix domain socket (the default docker socket is
@@ -138,11 +123,7 @@ httpHandler manager = HttpHandler $ \request' sink -> do -- runResourceT ..
138123--
139124-- Docker seems to ignore the hostname in requests sent over unix domain
140125-- sockets (and the port obviously doesn't matter either)
141−unixHttpHandler :: (
142−#if MIN_VERSION_http_conduit(2,3,0)
143− MonadUnliftIO m,
144−#endif
145− MonadIO m, MonadMask m) => FilePath -- ^ The socket to connect to
126+unixHttpHandler :: (MonadIO m, MonadMask m) => FilePath -- ^ The socket to connect to
146127 -> m (HttpHandler m)
147128unixHttpHandler fp = do
148129 let mSettings = defaultManagerSettings
@@ -156,7 +137,7 @@ unixHttpHandler fp = do
156137 S.connect s (S.SockAddrUnix filePath)
157138 makeConnection (SBS.recv s 8096)
158139 (SBS.sendAll s)
159− (S.close s)
140+ (S.sClose s)
160141
161142-- TODO:
162143-- Move this to http-client-tls or network?
@@ -273,18 +254,4 @@ statusCodeToError (CreateImageEndpoint _ _ _) st =
273254 Nothing
274255 else
275256 Just $ DockerInvalidStatusCode st
276−statusCodeToError (DeleteImageEndpoint _ _) st =
277− if st == status200 then
278− Nothing
279− else
280− Just $ DockerInvalidStatusCode st
281−statusCodeToError (CreateNetworkEndpoint _) st =
282− if st == status201 then
283− Nothing
284− else
285− Just $ DockerInvalidStatusCode st
286−statusCodeToError (RemoveNetworkEndpoint _) st =
287− if st == status204 then
288− Nothing
289− else
290− Just $ DockerInvalidStatusCode st
257+
src/Docker/Client/Internal.hs+3−11
@@ -5,13 +5,12 @@ import qualified Data.Aeson as JSON
55import Data.ByteString (ByteString)
66import qualified Data.ByteString.Char8 as BSC
77import qualified Data.Conduit.Binary as CB
8−import qualified Data.Text as T
8+import Data.Text as T
99import Data.Text.Encoding (decodeUtf8, encodeUtf8)
1010import qualified Network.HTTP.Client as HTTP
1111import Network.HTTP.Conduit (requestBodySourceChunked)
1212import Network.HTTP.Types (Query, encodePath,
1313 encodePathSegments)
14−import Prelude hiding (all)
1514
1615import Docker.Client.Types
1716
@@ -27,7 +26,7 @@ encodeQ = encodeUtf8 . T.pack
2726
2827getEndpoint :: ApiVersion -> Endpoint -> T.Text
2928getEndpoint v VersionEndpoint = encodeURL [v, "version"]
30−getEndpoint v (ListContainersEndpoint (ListOpts all)) = encodeURLWithQuery [v, "containers", "json"] [("all", Just (encodeQ $ show all))]
29+getEndpoint v (ListContainersEndpoint _) = encodeURL [v, "containers", "json"] -- Make use of lsOpts here
3130getEndpoint v (ListImagesEndpoint _) = encodeURL [v, "images", "json"] -- Make use of lsOpts here
3231getEndpoint v (CreateContainerEndpoint _ cn) = case cn of
3332 Just cn -> encodeURLWithQuery [v, "containers", "create"] [("name", Just (encodeQ $ T.unpack cn))]
@@ -57,7 +56,7 @@ getEndpoint v (UnpauseContainerEndpoint cid) = encodeURL [v, "containers", fromC
5756getEndpoint v (ContainerLogsEndpoint (LogOpts stdout stderr _ _ _) follow cid) =
5857 encodeURLWithQuery [v, "containers", fromContainerID cid, "logs"] query
5958 where query = [("stdout", Just (encodeQ $ show stdout)), ("stderr", Just (encodeQ $ show stderr)), ("follow", Just (encodeQ $ show follow))]
60−getEndpoint v (DeleteContainerEndpoint (ContainerDeleteOpts removeVolumes force) cid) =
59+getEndpoint v (DeleteContainerEndpoint (DeleteOpts removeVolumes force) cid) =
6160 encodeURLWithQuery [v, "containers", fromContainerID cid] query
6261 where query = [("v", Just (encodeQ $ show removeVolumes)), ("force", Just (encodeQ $ show force))]
6362getEndpoint v (InspectContainerEndpoint cid) =
@@ -75,9 +74,6 @@ getEndpoint v (CreateImageEndpoint name tag _) = encodeURLWithQuery [v, "images"
7574 where query = [("fromImage", Just n), ("tag", Just t)]
7675 n = encodeQ $ T.unpack name
7776 t = encodeQ $ T.unpack tag
78−getEndpoint v (DeleteImageEndpoint _ cid) = encodeURL [v, "images", fromImageID cid]
79−getEndpoint v (CreateNetworkEndpoint _) = encodeURL [v, "networks", "create"]
80−getEndpoint v (RemoveNetworkEndpoint nid) = encodeURL [v, "networks", fromNetworkID nid]
8177
8278getEndpointRequestBody :: Endpoint -> Maybe HTTP.RequestBody
8379getEndpointRequestBody VersionEndpoint = Nothing
@@ -97,10 +93,6 @@ getEndpointRequestBody (InspectContainerEndpoint _) = Nothing
9793
9894getEndpointRequestBody (BuildImageEndpoint _ fp) = Just $ requestBodySourceChunked $ CB.sourceFile fp
9995getEndpointRequestBody (CreateImageEndpoint _ _ _) = Nothing
100−getEndpointRequestBody (DeleteImageEndpoint _ _) = Nothing
101−
102−getEndpointRequestBody (CreateNetworkEndpoint opts) = Just $ HTTP.RequestBodyLBS (JSON.encode opts)
103−getEndpointRequestBody (RemoveNetworkEndpoint _) = Nothing
10496
10597getEndpointContentType :: Endpoint -> BSC.ByteString
10698getEndpointContentType (BuildImageEndpoint _ _) = BSC.pack "application/tar"
src/Docker/Client/Types.hs+45−170
@@ -11,9 +11,6 @@ module Docker.Client.Types (
1111 , ImageID
1212 , fromImageID
1313 , toImageID
14− , NetworkID
15− , fromNetworkID
16− , toNetworkID
1714 , Timeout(..)
1815 , StatusCode(..)
1916 , Signal(..)
@@ -26,12 +23,11 @@ module Docker.Client.Types (
2623 , ContainerPortInfo(..)
2724 , Container(..)
2825 , ContainerState(..)
29− , State(..)
26+ , Status(..)
3027 , Digest
3128 , Label(..)
3229 , Tag
3330 , Image(..)
34− , Entrypoint(..)
3531 , dropImagePrefix
3632 , CreateOpts(..)
3733 , BuildOpts(..)
@@ -40,16 +36,12 @@ module Docker.Client.Types (
4036 , DetachKeys(..)
4137 , StartOpts(..)
4238 , defaultStartOpts
43− , ContainerDeleteOpts(..)
44− , defaultContainerDeleteOpts
45− , ImageDeleteOpts(..)
46− , defaultImageDeleteOpts
39+ , DeleteOpts(..)
40+ , defaultDeleteOpts
4741 , Timestamp
4842 , TailLogOpt(..)
4943 , LogOpts(..)
5044 , defaultLogOpts
51− , CreateNetworkOpts(..)
52− , defaultCreateNetworkOpts
5345 , VolumePermission(..)
5446 , Bind(..)
5547 , Volume(..)
@@ -75,8 +67,6 @@ module Docker.Client.Types (
7567 , UTSMode(..)
7668 , HostConfig(..)
7769 , defaultHostConfig
78− , NetworkingConfig(..)
79− , EndpointConfig(..)
8070 , Ulimit(..)
8171 , ContainerResources(..)
8272 , defaultContainerResources
@@ -112,7 +102,6 @@ import Data.Scientific (floatingOrInteger)
112102import Data.Text (Text)
113103import qualified Data.Text as T
114104import Data.Time.Clock (UTCTime)
115−import qualified Data.Vector as V
116105import GHC.Generics (Generic)
117106import Prelude hiding (all, tail)
118107import Text.Read (readMaybe)
@@ -132,13 +121,10 @@ data Endpoint =
132121 | UnpauseContainerEndpoint ContainerID
133122 | ContainerLogsEndpoint LogOpts Bool ContainerID -- ^ Second argument (Bool) is whether to follow which is currently hardcoded to False.
134123 -- See note in 'Docker.Client.Api.getContainerLogs' for explanation why.
135− | DeleteContainerEndpoint ContainerDeleteOpts ContainerID
124+ | DeleteContainerEndpoint DeleteOpts ContainerID
136125 | InspectContainerEndpoint ContainerID
137126 | BuildImageEndpoint BuildOpts FilePath
138127 | CreateImageEndpoint T.Text Tag (Maybe T.Text) -- ^ Either pull an image from docker hub or imports an image from a tarball (or URL)
139− | DeleteImageEndpoint ImageDeleteOpts ImageID
140− | CreateNetworkEndpoint CreateNetworkOpts
141− | RemoveNetworkEndpoint NetworkID
142128 deriving (Eq, Show)
143129
144130-- | We should newtype this
@@ -250,7 +236,7 @@ data ContainerDetails = ContainerDetails {
250236 , processLabel :: Text
251237 , resolveConfPath :: FilePath
252238 , restartCount :: Int
253− , containerDetailsState :: ContainerState
239+ , state :: ContainerState
254240 , mounts :: [Mount]
255241 }
256242 deriving (Eq, Show, Generic)
@@ -258,11 +244,11 @@ data ContainerDetails = ContainerDetails {
258244-- | Data type used for parsing the mount information from a container
259245-- list.
260246data Mount = Mount {
261− mountName :: Maybe Text -- this is optional
247+ mountName :: Text
262248 , mountSource :: FilePath
263249 , mountDestination :: FilePath
264− , mountDriver :: Maybe Text
265− -- , mountMode :: Maybe VolumePermission -- apparently this can be null
250+ , mountDriver :: Text
251+ , mountMode :: Maybe VolumePermission -- apparently this can be null
266252 , mountRW :: Bool
267253 , mountPropogation :: Text
268254 }
@@ -270,14 +256,14 @@ data Mount = Mount {
270256
271257instance FromJSON Mount where
272258 parseJSON (JSON.Object o) = do
273− name <- o .:? "Name"
259+ name <- o .: "Name"
274260 src <- o .: "Source"
275261 dest <- o .: "Destination"
276− driver <- o .:? "Driver"
277− -- mode <- o .: "Mode"
262+ driver <- o .: "Driver"
263+ mode <- o .: "Mode"
278264 rw <- o .: "RW"
279265 prop <- o .: "Propagation"
280− return $ Mount name src dest driver rw prop
266+ return $ Mount name src dest driver mode rw prop
281267 parseJSON _ = fail "Mount is not an object"
282268
283269-- | Data type used for parsing the container state from a list of
@@ -293,7 +279,7 @@ data ContainerState = ContainerState {
293279 , restarting :: Bool
294280 , running :: Bool
295281 , startedAt :: UTCTime
296− , state :: State
282+ , status :: Status
297283 }
298284 deriving (Eq, Show, Generic)
299285
@@ -523,8 +509,7 @@ data Container = Container
523509 , containerImageId :: ImageID
524510 , containerCommand :: Text
525511 , containerCreatedAt :: Int
526− , containerState :: State
527− , containerStatus :: Maybe Text
512+ , containerStatus :: Status
528513 , containerPorts :: [ContainerPortInfo]
529514 , containerLabels :: [Label]
530515 , containerNetworks :: [Network]
@@ -532,14 +517,13 @@ data Container = Container
532517 } deriving (Show, Eq)
533518
534519instance FromJSON Container where
535− parseJSON o@(JSON.Object v) =
536− Container <$> parseJSON o
520+ parseJSON (JSON.Object v) =
521+ Container <$> (v .: "Id")
537522 <*> (v .: "Names")
538523 <*> (v .: "Image")
539− <*> (v .: "ImageID") -- Doesn't exist anymore
540− <*> (v .: "Command") -- Doesn't exist anymore
524+ <*> (v .: "ImageID")
525+ <*> (v .: "Command")
541526 <*> (v .: "Created")
542− <*> (v .: "State")
543527 <*> (v .: "Status")
544528 <*> (v .: "Ports")
545529 <*> (v .: "Labels")
@@ -549,20 +533,21 @@ instance FromJSON Container where
549533 parseNetworks (JSON.Object v) =
550534 (v .: "Networks") >>= parseJSON
551535 parseNetworks _ = fail "Container NetworkSettings: Not a JSON object."
536+
552537 parseJSON _ = fail "Container: Not a JSON object."
553538
554−-- | Represents the state of the container life cycle.
555−data State = Created | Restarting | Running | Paused | Exited | Dead
539+-- | Represents the status of the container life cycle.
540+data Status = Created | Restarting | Running | Paused | Exited | Dead
556541 deriving (Eq, Show, Generic)
557542
558−instance FromJSON State where
543+instance FromJSON Status where
559544 parseJSON (JSON.String "running") = return Running
560545 parseJSON (JSON.String "created") = return Created -- Note: Guessing on the string values of these.
561546 parseJSON (JSON.String "restarting") = return Restarting
562547 parseJSON (JSON.String "paused") = return Paused
563548 parseJSON (JSON.String "exited") = return Exited
564549 parseJSON (JSON.String "dead") = return Dead
565− parseJSON s = fail $ "Unknown Status: " ++ show s
550+ parseJSON _ = fail "Unknown Status"
566551
567552-- | Alias for representing a RepoDigest. We could newtype this and add
568553-- some validation.
@@ -623,46 +608,20 @@ instance FromJSON Image where
623608 return $ DockerImage imageId imageCreated imageParentId imageRepoTags imageRepoDigests imageSize imageVirtualSize imageLabels
624609 parseJSON _ = fail "Failed to parse DockerImage."
625610
626−-- | Alias for Aliases.
627−type Alias = Text
628−
629−-- | EndpointsConfig is container configuration for a specific network
630−newtype EndpointConfig = EndpointConfig [Alias] deriving (Eq, Show)
631−
632−instance ToJSON EndpointConfig where
633− toJSON (EndpointConfig aliases) = JSON.object
634− [ "Aliases" .= aliases
635− ]
636−
637−-- | Alias for endpoint name
638−type EndpointName = Text
639−
640−-- | Data type for the NetworkingConfig section of the container settings
641−newtype NetworkingConfig = NetworkingConfig
642− { endpointsConfig :: HM.HashMap EndpointName EndpointConfig
643− } deriving (Eq, Show)
644−
645−instance ToJSON NetworkingConfig where
646− toJSON (NetworkingConfig endpointsConfig) = JSON.object
647− [ "EndpointsConfig" .= endpointsConfig
648− ]
649611
650612-- | Options used for creating a Container.
651613data CreateOpts = CreateOpts {
652− containerConfig :: ContainerConfig
653− , hostConfig :: HostConfig
654− , networkingConfig :: NetworkingConfig
614+ containerConfig :: ContainerConfig
615+ , hostConfig :: HostConfig
655616 } deriving (Eq, Show)
656617
657618instance ToJSON CreateOpts where
658− toJSON (CreateOpts cc hc nc) = do
619+ toJSON (CreateOpts cc hc) = do
659620 let ccJSON = toJSON cc
660621 let hcJSON = toJSON hc
661622 case ccJSON of
662623 JSON.Object (o :: HM.HashMap T.Text JSON.Value) -> do
663− let o1 = HM.insert "HostConfig" hcJSON o
664− let o2 = HM.insert "NetworkingConfig" (toJSON nc) o1
665− JSON.Object o2
624+ JSON.Object $ HM.insert "HostConfig" hcJSON o
666625 _ -> error "ContainerConfig is not an object." -- This should never happen.
667626
668627-- | Container configuration used for creating a container with sensible
@@ -684,7 +643,7 @@ defaultContainerConfig imageName = ContainerConfig {
684643 , cmd=[]
685644 , volumes=[]
686645 , workingDir=Nothing
687− , entrypoint=Entrypoint []
646+ , entrypoint=Nothing
688647 , networkDisabled=Nothing
689648 , macAddress=Nothing
690649 , labels=[]
@@ -697,7 +656,7 @@ defaultHostConfig = HostConfig {
697656 binds=[]
698657 , containerIDFile=Nothing
699658 , logConfig=LogDriverConfig JsonFile []
700− , networkMode=NetworkBridge
659+ , networkMode=Bridge
701660 , portBindings=[]
702661 , restartPolicy=RestartOff
703662 , volumeDriver=Nothing
@@ -737,18 +696,14 @@ defaultContainerResources = ContainerResources {
737696 , memory=Nothing
738697 , memoryReservation=Nothing
739698 , memorySwap=Nothing
740− , oomKillDisable=Just False
699+ , oomKillDisable=False
741700 , ulimits=[]
742701 }
743702
744703-- | Default create options when creating a container. You only need to
745704-- specify an image name and the rest is all sensible defaults.
746705defaultCreateOpts :: T.Text -> CreateOpts
747−defaultCreateOpts imageName = CreateOpts
748− { containerConfig = defaultContainerConfig imageName
749− , hostConfig = defaultHostConfig
750− , networkingConfig = NetworkingConfig HM.empty
751− }
706+defaultCreateOpts imageName = CreateOpts { containerConfig = defaultContainerConfig imageName, hostConfig = defaultHostConfig }
752707
753708-- | Override the key sequence for detaching a container.
754709-- Format is a single character [a-Z] or ctrl-<value> where <value> is one of: a-z, @, ^, [, , or _.
@@ -762,7 +717,7 @@ defaultStartOpts :: StartOpts
762717defaultStartOpts = StartOpts { detachKeys = DefaultDetachKey }
763718
764719-- | Options for deleting a container.
765−data ContainerDeleteOpts = ContainerDeleteOpts {
720+data DeleteOpts = DeleteOpts {
766721 deleteVolumes :: Bool -- ^ Automatically cleanup volumes that the container created as well.
767722 , force :: Bool -- ^ If the container is still running force deletion anyway.
768723 } deriving (Eq, Show)
@@ -792,15 +747,8 @@ defaultBuildOpts nameTag = BuildOpts { buildImageName = nameTag
792747-- | Default options for deleting a container. Most of the time we DON'T
793748-- want to delete the container's volumes or force delete it if it's
794749-- running.
795−defaultContainerDeleteOpts :: ContainerDeleteOpts
796−defaultContainerDeleteOpts = ContainerDeleteOpts { deleteVolumes = False, force = False }
797−
798−-- | Image delete opts
799−data ImageDeleteOpts = ImageDeleteOpts deriving (Eq, Show)
800−
801−-- | Sane image deletion defaults
802−defaultImageDeleteOpts :: ImageDeleteOpts
803−defaultImageDeleteOpts = ImageDeleteOpts
750+defaultDeleteOpts :: DeleteOpts
751+defaultDeleteOpts = DeleteOpts { deleteVolumes = False, force = False }
804752
805753-- | Timestamp alias.
806754type Timestamp = Integer
@@ -828,36 +776,6 @@ defaultLogOpts = LogOpts { stdout = True
828776 , tail = All
829777 }
830778
831−-- | Options for creating a network
832−data CreateNetworkOpts = CreateNetworkOpts
833− { createNetworkName :: Text -- ^ The network's name
834− , createNetworkCheckDuplicate :: Bool -- ^ Check for networks with duplicate names.
835− , createNetworkDriver :: Text -- ^ Name of the network driver plugin to use.
836− , createNetworkInternal :: Bool -- ^ Restrict external access to the network.
837− , createNetworkEnableIPv6 :: Bool -- ^ Enable IPv6 on the network.
838− } deriving (Eq, Show)
839−
840−-- | Sensible defalut for create network options
841−defaultCreateNetworkOpts :: Text -> CreateNetworkOpts
842−defaultCreateNetworkOpts name =
843− CreateNetworkOpts
844− { createNetworkName = name
845− , createNetworkCheckDuplicate = False
846− , createNetworkDriver = "bridge"
847− , createNetworkInternal = True
848− , createNetworkEnableIPv6 = False
849− }
850−
851−instance ToJSON CreateNetworkOpts where
852− toJSON opts =
853− object
854− [ "Name" .= createNetworkName opts
855− , "CheckDuplicate" .= createNetworkCheckDuplicate opts
856− , "Driver" .= createNetworkDriver opts
857− , "Internal" .= createNetworkInternal opts
858− , "EnableIPv6" .= createNetworkEnableIPv6 opts
859− ]
860−
861779-- TOOD: Add support for SELinux Volume labels (eg. "ro,z" or "ro/Z")
862780-- | Set permissions on volumes that you mount in the container.
863781data VolumePermission = ReadWrite | ReadOnly deriving (Eq, Show, Generic)
@@ -869,8 +787,6 @@ instance ToJSON VolumePermission where
869787instance FromJSON VolumePermission where
870788 parseJSON "rw" = return ReadWrite
871789 parseJSON "ro" = return ReadOnly
872− parseJSON "RW" = return ReadWrite
873− parseJSON "RO" = return ReadOnly
874790 parseJSON _ = fail "Failed to parse VolumePermission"
875791
876792-- | Used for marking a directory in the container as "exposed" hence
@@ -1017,41 +933,19 @@ instance FromJSON LogDriverConfig where
1017933 parseJSON _ = fail "LogDriverConfig is not an object"
1018934
1019935-- TODO: Add container:<name|id> mode
1020−data NetworkMode = NetworkBridge | NetworkHost | NetworkDisabled | NetworkNamed Text
936+data NetworkMode = Bridge | Host | NetworkDisabled
1021937 deriving (Eq, Show, Ord)
1022938
1023939instance FromJSON NetworkMode where
1024− parseJSON (JSON.String "bridge") = return NetworkBridge
1025− parseJSON (JSON.String "host") = return NetworkHost -- Note: Guessing on these.
940+ parseJSON (JSON.String "bridge") = return Bridge
941+ parseJSON (JSON.String "host") = return Host -- Note: Guessing on these.
1026942 parseJSON (JSON.String "none") = return NetworkDisabled
1027− parseJSON (JSON.String n) = return $ NetworkNamed n
1028943 parseJSON _ = fail "Unknown NetworkMode"
1029944
1030945instance ToJSON NetworkMode where
1031− toJSON NetworkBridge = JSON.String "bridge"
1032− toJSON NetworkHost = JSON.String "host"
1033− toJSON NetworkDisabled = JSON.String "none"
1034− toJSON (NetworkNamed n) = JSON.String n
1035−
1036−newtype NetworkID = NetworkID Text
1037− deriving (Eq, Show)
1038−
1039−-- | Used for extracting the id of the container from the newtype
1040−fromNetworkID :: NetworkID -> Text
1041−fromNetworkID (NetworkID t) = t
1042−
1043−-- | Used for parsing a Text value into a NetworkID.
1044−toNetworkID :: Text -> Maybe NetworkID
1045−toNetworkID t = Just $ NetworkID t
1046−
1047−instance FromJSON NetworkID where
1048− parseJSON (JSON.Object o) = do
1049− nid <- o .: "Id"
1050− return $ NetworkID nid
1051− parseJSON _ = fail "NetworkID is not an object."
1052−
1053−instance ToJSON NetworkID where
1054− toJSON (NetworkID nid) = object ["Id" .= nid]
946+ toJSON Bridge = JSON.String "bridge"
947+ toJSON Host = JSON.String "host"
948+ toJSON NetworkDisabled = JSON.String "none"
1055949
1056950data PortType = TCP | UDP deriving (Eq, Generic, Read, Ord)
1057951
@@ -1414,7 +1308,7 @@ data ContainerResources = ContainerResources {
14141308 , memoryReservation :: Maybe MemoryConstraint
14151309 , memorySwap :: Maybe MemoryConstraint
14161310 -- , memorySwappiness :: Integer -- 1.24: Missing from inspecting container details... Going to omit for now.
1417− , oomKillDisable :: Maybe Bool
1311+ , oomKillDisable :: Bool
14181312 -- , pidsLimit :: Integer -- 1.24: Missing from inspecting container details... Going to omit for now.
14191313 , ulimits :: [Ulimit]
14201314 -- TODO: Missing from 1.24
@@ -1452,7 +1346,7 @@ instance FromJSON EnvVar where
14521346 parseJSON _ = fail "EnvVar is not a string"
14531347
14541348instance ToJSON EnvVar where
1455− toJSON (EnvVar n v) = JSON.String $ n <> T.pack "=" <> v
1349+ toJSON (EnvVar n v) = object [n .= v]
14561350
14571351-- | ExposedPort represents a port (and it's type)
14581352-- that a container should expose to other containers or the host system.
@@ -1492,21 +1386,6 @@ instance {-# OVERLAPPING #-} ToJSON [ExposedPort] where
14921386 where key (ExposedPort p t) = show p <> slash <> show t
14931387 slash = T.unpack "/"
14941388
1495−data Entrypoint = Entrypoint [T.Text] deriving (Eq, Show, Generic)
1496−
1497−instance ToJSON Entrypoint where
1498− toJSON (Entrypoint (e:es)) = toJSON (e:es)
1499− toJSON (Entrypoint []) = JSON.Null
1500−
1501−instance FromJSON Entrypoint where
1502− parseJSON (JSON.String e) = return $ Entrypoint [e]
1503− parseJSON (JSON.Array ar) = do
1504− arr <- mapM parseJSON (V.toList ar)
1505− return $ Entrypoint arr
1506− parseJSON JSON.Null = return $ Entrypoint []
1507− parseJSON _ = fail "Failed to parse Entrypoint"
1508−
1509−
15101389data ContainerConfig = ContainerConfig {
15111390 hostname :: Maybe Text
15121391 , domainname :: Maybe Text
@@ -1525,7 +1404,7 @@ data ContainerConfig = ContainerConfig {
15251404 , image :: Text
15261405 , volumes :: [Volume]
15271406 , workingDir :: Maybe FilePath
1528− , entrypoint :: Entrypoint
1407+ , entrypoint :: Maybe Text -- Can be null?
15291408 , networkDisabled :: Maybe Bool -- Note: Should we expand the JSON instance and take away the Maybe? Null is False?
15301409 , macAddress :: Maybe Text
15311410 -- , onBuild :: Maybe Text -- For 1.24, only see this in the inspect response.
@@ -1533,7 +1412,6 @@ data ContainerConfig = ContainerConfig {
15331412 , stopSignal :: Signal
15341413 } deriving (Eq, Show, Generic)
15351414
1536−
15371415instance ToJSON ContainerConfig where
15381416 toJSON = genericToJSON defaultOptions {
15391417 fieldLabelModifier = (\(x:xs) -> toUpper x : xs)}
@@ -1555,7 +1433,7 @@ instance FromJSON ContainerConfig where
15551433 image <- o .: "Image"
15561434 volumes <- o .: "Volumes"
15571435 workingDir <- o .:? "WorkingDir"
1558− entrypoint <- o .: "Entrypoint"
1436+ entrypoint <- o .:? "Entrypoint"
15591437 networkDisabled <- o .:? "networkDisabled"
15601438 macAddress <- o .:? "MacAddress"
15611439 labels <- o .:? "Labels" .!= []
@@ -1564,11 +1442,7 @@ instance FromJSON ContainerConfig where
15641442 macAddress labels stopSignal
15651443 parseJSON _ = fail "NetworkSettings is not an object."
15661444
1567−#if MIN_VERSION_base(4,13,0)
1568−parseIntegerText :: (MonadFail m) => Text -> m Integer
1569−#else
15701445parseIntegerText :: (Monad m) => Text -> m Integer
1571−#endif
15721446parseIntegerText t = case readMaybe $ T.unpack t of
15731447 Nothing ->
15741448 fail "Could not parse Integer"
@@ -1590,3 +1464,4 @@ toJsonKeyVal vs getKey getVal = JSON.Object $ foldl f HM.empty vs
15901464-- | Helper function that return an empty dictionary "{}"
15911465emptyJsonObject :: JSON.Value
15921466emptyJsonObject = JSON.Object HM.empty
1467+
stack-7.10.yaml+5−5
@@ -1,20 +1,20 @@
11# For more information, see: https://github.com/commercialhaskell/stack/blob/release/doc/yaml_configuration.md
22
33# Specifies the GHC version and set of packages available (e.g., lts-3.5, nightly-2015-09-21, ghc-7.10.2)
4−resolver: lts-6.30
4+resolver: lts-5.18
55
66# Local packages, usually specified by relative directory name
77packages:
88- '.'
99
10+# Packages to be pulled from upstream that are not in the resolver (e.g., acme-missiles-0.3)
11+extra-deps: [directory-1.2.7.0]
12+
1013# Override default flag values for local packages and extra-deps
1114flags: {}
1215
1316# Extra package databases containing global packages
14−extra-deps:
15−- directory-1.2.7.0
16−- unliftio-core-0.1.1.0
17−- process-1.6.5.1
17+extra-package-dbs: []
1818
1919# Control whether we use the GHC we find on the path
2020# system-ghc: true
stack-8.0.2.yamldeleted−4
@@ -1,4 +0,0 @@
1−resolver: lts-9.4
2−packages:
3−- '.'
4−extra-deps: []
stack-8.0.yaml+1−2
@@ -1,5 +1,4 @@
11resolver: lts-7.12
22packages:
33- '.'
4−extra-deps:
5−- unliftio-core-0.1.1.0
4+extra-deps: []
stack-8.6.4.yamldeleted−4
@@ -1,4 +0,0 @@
1−resolver: lts-13.19
2−packages:
3−- '.'
4−extra-deps: []
stack-8.8.2.yamldeleted−5
@@ -1,5 +0,0 @@
1−resolver: lts-15.0
2−packages:
3−- '.'
4−extra-deps: []
5−
stack.yaml+1−1
@@ -1 +1 @@
1−stack-8.6.4.yaml
1+stack-7.10.yaml
tests/Dockerfile+1−1
@@ -1,4 +1,4 @@
11FROM debian:jessie
22
3−CMD ["/bin/bash", "-c", "echo $TEST"]
3+CMD ["/bin/bash", "-c", "echo 123"]
44
tests/tests.hs+80−231
@@ -2,8 +2,6 @@
22
33module Main where
44
5−import Data.Either (rights)
6−import Prelude hiding (all)
75import qualified Test.QuickCheck.Monadic as QCM
86import Test.Tasty
97import Test.Tasty.HUnit
@@ -11,284 +9,135 @@ import Test.Tasty.QuickCheck (testProperty)
119
1210import Control.Concurrent (threadDelay)
1311import Control.Lens ((^.), (^?))
14−import Control.Monad (forM_)
1512import Control.Monad.IO.Class
1613import Control.Monad.Trans.Class (lift)
1714import qualified Data.Aeson as JSON
18−import Data.Aeson ((.=))
19−import Data.Aeson.Lens (key, _Array, _Null, _Object,
20− _String, _Value)
15+import Data.Aeson.Lens (key, _Object, _String, _Value)
2116import qualified Data.ByteString as B
2217import qualified Data.ByteString.Char8 as C
2318import qualified Data.ByteString.Lazy as BL
2419import qualified Data.HashMap.Strict as HM
2520import Data.Int (Int)
2621import qualified Data.Map as M
27−import Data.Maybe (fromJust, isJust, isNothing, listToMaybe)
22+import Data.Maybe (fromJust, isJust)
2823import Data.Monoid
2924import Data.Text (Text, unpack)
30−import qualified Data.Vector as V
3125import Network.Connection (TLSSettings (..))
3226import Network.HTTP.Client (newManager)
3327import Network.HTTP.Client.TLS
3428import Network.HTTP.Types.Status
35−import System.Directory (getCurrentDirectory)
36−import System.Environment (lookupEnv)
3729import System.Process (system)
3830
3931import Docker.Client
4032
4133-- opts = defaultClientOpts
42−testImageName = "docker-hs/test"
43−imageToDeleteFullName = "hello-world:latest"
34+
35+testImageName = "docker-hs-test"
4436
4537toStrict1 = B.concat . BL.toChunks
4638
47−runDocker f
48− -- let opts = defaultClientOpts {baseUrl = "https://127.0.0.1:2376/"}
49− -- params' <- clientParamsWithClientAuthentication "127.0.0.1" 2376 "~/.docker/test-client-key.pem" "~/.docker/test-client-cert.pem" >>= fromRight
50− -- params <- clientParamsSetCA params' "~/.docker/test-ca.pem"
51− -- let settings = mkManagerSettings (TLSSettings params) Nothing
52− -- mgr <- newManager settings
53− = do
54− h <- defaultHttpHandler
55− runDockerT (defaultClientOpts, h) f
39+runDocker f = do
40+ -- let opts = defaultClientOpts {baseUrl = "https://127.0.0.1:2376/"}
41+ -- params' <- clientParamsWithClientAuthentication "127.0.0.1" 2376 "~/.docker/test-client-key.pem" "~/.docker/test-client-cert.pem" >>= fromRight
42+ -- params <- clientParamsSetCA params' "~/.docker/test-ca.pem"
43+ -- let settings = mkManagerSettings (TLSSettings params) Nothing
44+ -- mgr <- newManager settings
45+ h <- defaultHttpHandler
46+ runDockerT (defaultClientOpts, h) f
5647
5748testDockerVersion :: IO ()
58−testDockerVersion =
59− runDocker $
60− do v <- getDockerVersion
61− lift $ assert $ isRight v
62−
63−testStopNonexisting :: IO ()
64−testStopNonexisting = runDocker $ do
65− res <- stopContainer DefaultTimeout $ fromJust $ toContainerID "thisshouldnotexist"
66− lift $ assert $ isLeft res
49+testDockerVersion = runDocker $ do
50+ v <- getDockerVersion
51+ lift $ assert $ isRight v
6752
6853testFindImage :: IO ()
69−testFindImage =
70− runDocker $
71− do images <- listImages defaultListOpts >>= fromRight
72− let xs = filter (elem imageFullName . imageRepoTags) images
73− lift $ assert $ length xs == 1
74− where
75− imageFullName = testImageName <> ":latest"
76−
77−testDeleteImage :: IO ()
78−testDeleteImage = runDocker $ do
79− img <- fmap fromJust findTestImage
80− result <- deleteImage defaultImageDeleteOpts (imageId img)
81− lift $ assert $ isRight result
82− maybeTestImageAfter <- findTestImage
83− lift $ assert $ isNothing maybeTestImageAfter
84− where
85− findTestImage =
86− do
54+testFindImage = runDocker $ do
8755 images <- listImages defaultListOpts >>= fromRight
88− return $ listToMaybe
89− $ filter (elem imageToDeleteFullName . imageRepoTags) images
90−
91−testListContainers :: IO ()
92−testListContainers =
93− runDocker $
94− do containerId <- createContainer (defaultCreateOpts (testImageName <> ":latest")) Nothing
95− c <- fromRight containerId
96− res <- listContainers $ ListOpts { all=True }
97− deleteContainer (ContainerDeleteOpts True True) c
98− lift $ assert $ isRight res
99−
100−testBuildFromDockerfile :: IO ()
101−testBuildFromDockerfile = do
102− cur <- getCurrentDirectory
103− let ctxDir = cur ++ "/tests"
104− runDocker $ do
105− r <- buildImageFromDockerfile (defaultBuildOpts "docker-hs/dockerfile-test") ctxDir
106− lift $ assert $ isRight r
107−
56+ let xs = filter ((== [imageFullName]) . imageRepoTags) images
57+ lift $ assert $ length xs == 1
58+ where imageFullName = testImageName <> ":latest"
10859
10960testRunAndReadLog :: IO ()
110−testRunAndReadLog = testRunAndReadLogHelper $ NetworkingConfig HM.empty
111−
112−testRunAndReadLogWithNetworking :: IO ()
113−testRunAndReadLogWithNetworking = testRunAndReadLogHelper $ NetworkingConfig $ HM.fromList [("test-network", EndpointConfig ["cellar-door"])]
114−
115−testRunAndReadLogHelper :: NetworkingConfig -> IO ()
116−testRunAndReadLogHelper networkingConfig =
117− runDocker $
118− do let containerConfig = (defaultContainerConfig (testImageName <> ":latest")) {env = [EnvVar "TEST" "123"]}
119− createdNetworks <- rights <$> mapM createNetworkWithName networkNames
120− containerId <- createContainer (CreateOpts containerConfig defaultHostConfig networkingConfig) Nothing
121− c <- fromRight containerId
122− status1 <- startContainer defaultStartOpts c
123− _ <- inspectContainer c >>= fromRight
124− lift $ threadDelay 300000 -- give 300ms for the application to finish
125− lift $ assertBool ("starting the container, unexpected status: " ++ show status1) $ isRightUnit status1
126− logs <- getContainerLogs defaultLogOpts c >>= fromRight
127− lift $ assert $ (C.pack "123") `C.isInfixOf` (toStrict1 logs)
128− status3 <- deleteContainer (ContainerDeleteOpts True True) c
129− lift $ assertBool ("deleting container, unexpected status: " ++ show status3) $ isRightUnit status3
130− mapM_ removeNetwork createdNetworks
131− where
132− isRightUnit (Right ()) = True
133− isRightUnit _ = False
134− networkNames = HM.keys $ endpointsConfig networkingConfig
135− createNetworkWithName name = createNetwork $
136− (defaultCreateNetworkOpts name) { createNetworkCheckDuplicate = True }
137−
138−testCreateRemoveNetwork :: IO ()
139−testCreateRemoveNetwork = do
140− runDocker $ do
141− createStatus <- createNetwork $ defaultCreateNetworkOpts "test-network"
142− lift $ assertBool ("creating a network, unexpected status: " ++ show createStatus) $ isRight createStatus
143− nid <- fromRight createStatus
144− removeStatus <- removeNetwork nid
145− lift $ assertBool ("removing a network, unexpected status: " ++ show removeStatus) $ isRight removeStatus
61+testRunAndReadLog = runDocker $ do
62+ containerId <- createContainer (defaultCreateOpts (testImageName <> ":latest")) Nothing
63+ c <- fromRight containerId
64+ status1 <- startContainer defaultStartOpts c
65+ _ <- inspectContainer c >>= fromRight
66+ lift $ threadDelay 300000 -- give 300ms for the application to finish
67+ lift $ assert $ isRightUnit status1
68+ status2 <- killContainer SIGTERM c
69+ logs <- getContainerLogs defaultLogOpts c >>= fromRight
70+ lift $ assert $ isRightUnit status2
71+ lift $ assert $ (C.pack "123") `C.isInfixOf` (toStrict1 logs)
72+ status3 <- deleteContainer (DeleteOpts True True) c
73+ lift $ assert $ isRightUnit status3
74+
75+ where
76+ isRightUnit (Right ()) = True
77+ isRightUnit _ = False
14678
14779testLogDriverOptionsJson :: TestTree
148−testLogDriverOptionsJson = testGroup "Testing LogDriverOptions JSON" [test1, test2, test3]
149− where
150− test1 = testCase "Driver option 1" $ assert $ JSON.toJSON sample ^. key key1 . _String == val1
151− test2 = testCase "Driver option 2" $ assert $ JSON.toJSON sample ^. key key2 . _String == val2
152− test3 =
153− testCase "Test override" $ assert $ JSON.toJSON sample2 ^. key key1 . _String == "override"
154− sample = [LogDriverOption key1 val1, LogDriverOption key2 val2]
155− sample2 = [LogDriverOption key1 val1, LogDriverOption key1 "override"]
156− key1 = "some-key"
157− val1 = "some-val"
158− key2 = "some-key2"
159− val2 = "some-key2"
80+testLogDriverOptionsJson = testGroup "Testing LogDriverOptions JSON" [ test1, test2, test3 ]
81+ where
82+ test1 = testCase "Driver option 1" $ assert $ JSON.toJSON sample ^. key key1 . _String == val1
83+ test2 = testCase "Driver option 2" $ assert $ JSON.toJSON sample ^. key key2 . _String == val2
84+ test3 = testCase "Test override" $ assert $ JSON.toJSON sample2 ^. key key1 . _String == "override"
85+ sample = [LogDriverOption key1 val1, LogDriverOption key2 val2]
86+ sample2 = [LogDriverOption key1 val1, LogDriverOption key1 "override"]
87+ key1 = "some-key"
88+ val1 = "some-val"
89+ key2 = "some-key2"
90+ val2 = "some-key2"
16091
16192testExposedPortsJson :: TestTree
162−testExposedPortsJson = testGroup "Testing ExposedPorts JSON" [testTCP, testUDP]
163− where
164− testTCP = testCase "tcp port" $ assert $ JSON.toJSON sampleEP ^. key "80/tcp" . _Object == HM.empty
165− testUDP =
166− testCase "udp port" $ assert $ JSON.toJSON sampleEP ^. key "1337/tcp" . _Object == HM.empty
167− sampleEP = [ExposedPort 80 TCP, ExposedPort 1337 UDP]
93+testExposedPortsJson = testGroup "Testing ExposedPorts JSON" [ testTCP, testUDP ]
94+ where
95+ testTCP = testCase "tcp port" $ assert $ JSON.toJSON sampleEP ^. key "80/tcp" . _Object == HM.empty
96+ testUDP = testCase "udp port" $ assert $ JSON.toJSON sampleEP ^. key "1337/tcp" . _Object == HM.empty
97+ sampleEP = [ExposedPort 80 TCP, ExposedPort 1337 UDP]
16898
16999testLabelsJson :: TestTree
170−testLabelsJson = testGroup "Testing Labels JSON" [testLS1, testLS2, testOverride]
171− where
172− testLS1 = testCase "test label key1" $ assert $ JSON.toJSON sampleLS ^. key key1 . _String == val1
173− testLS2 = testCase "test label key2" $ assert $ JSON.toJSON sampleLS ^. key key2 . _String == val2
174− testOverride =
175− testCase "test label override" $ assert $ JSON.toJSON [Label key1 val1, Label key1 "override"] ^.
176− key key1 .
177− _String ==
178− "override"
179− sampleLS = [Label key1 val1, Label key2 val2]
180− key1 = "com.example.some-label"
181− val1 = "some-value"
182− key2 = "something"
183− val2 = "value"
100+testLabelsJson = testGroup "Testing Labels JSON" [ testLS1, testLS2, testOverride ]
101+ where
102+ testLS1 = testCase "test label key1" $ assert $ JSON.toJSON sampleLS ^. key key1 . _String == val1
103+ testLS2 = testCase "test label key2" $ assert $ JSON.toJSON sampleLS ^. key key2 . _String == val2
104+ testOverride = testCase "test label override" $ assert $ JSON.toJSON [Label key1 val1, Label key1 "override"] ^. key key1 . _String == "override"
105+ sampleLS = [Label key1 val1, Label key2 val2]
106+ key1 = "com.example.some-label"
107+ val1 = "some-value"
108+ key2 = "something"
109+ val2 = "value"
184110
185111testVolumesJson :: TestTree
186−testVolumesJson = testGroup "Testing Volumes JSON" [testSample1, testSample2]
187− where
188− testSample1 =
189− testCase "Test exposing volume: /tmp" $ assert $ JSON.toJSON sampleVolumes ^. key "/tmp" . _Object ==
190− HM.empty
191− testSample2 =
192− testCase "Test exposing volume: /opt" $ assert $ JSON.toJSON sampleVolumes ^. key "/opt" . _Object ==
193− HM.empty
194− sampleVolumes = [Volume "/tmp", Volume "/opt"]
195−
196−testEntrypointJson :: TestTree
197−testEntrypointJson = testGroup "Testing ContainerConfig JSON" [testSample1, testSample2, testSample3, testSample4, testSample5]
198− where
199− testSample1 =
200− testCase "Test toJSON with empty entrypoint (null)" $ assert $ JSON.toJSON (Entrypoint []) ^. _Null == ()
201− testSample2 =
202− testCase "Test toJSON with entrypoint as Array" $ assert $
203− JSON.toJSON (Entrypoint sampleEntrypointArr) ==
204− JSON.toJSON sampleEntrypointArr
205− testSample3 =
206− testCase "Test decoding entrypoint as string" $ assert $ (JSON.decode "\"cmd\"") ==
207− Just (Entrypoint ["cmd"])
208− testSample4 =
209− testCase "Test decoding as null" $ assert $ (JSON.decode "null" :: Maybe Entrypoint) ==
210− Just (Entrypoint [])
211− testSample5 =
212− testCase "Test decoding as array" $ assert $ (JSON.decode (JSON.encode sampleEntrypointArr) :: Maybe Entrypoint) ==
213− Just (Entrypoint sampleEntrypointArr)
214− sampleEntrypointArr = ["cmd", "--some-flag", "--some-flag2"]
215−
216−testEnvVarJson :: TestTree
217−testEnvVarJson = testGroup "Testing EnvVar JSON" [testSampleEncode, testSampleDecode]
218− where
219− testSampleEncode =
220− testCase "Test toJSON" $ assert $ JSON.toJSON (EnvVar "cellar" "door") == JSON.String "cellar=door"
221− testSampleDecode =
222− testCase "Test fromJSON" $ assert $ (JSON.decode "\"cellar=door\"" :: Maybe EnvVar) ==
223− Just (EnvVar "cellar" "door")
224−
225−testNetworkingConfigJson :: TestTree
226−testNetworkingConfigJson = testGroup "Testing NetworkingConfig JSON" [testSampleEncode]
227− where
228− testSampleEncode =
229− let networkingConfig = NetworkingConfig $ HM.fromList [("custom-network", EndpointConfig ["cellar", "door"])]
230− in testCase "Test toJSON" $ assert $ JSON.toJSON networkingConfig ==
231− JSON.object
232− [ "EndpointsConfig" .= JSON.object
233− [ "custom-network" .= JSON.object
234− [ "Aliases" .= (["cellar", "door"] :: [Text])
235− ]
236− ]
237− ]
112+testVolumesJson = testGroup "Testing Volumes JSON" [ testSample1, testSample2 ]
113+ where
114+ testSample1 = testCase "Test exposing volume: /tmp" $ assert $ JSON.toJSON sampleVolumes ^. key "/tmp" . _Object == HM.empty
115+ testSample2 = testCase "Test exposing volume: /opt" $ assert $ JSON.toJSON sampleVolumes ^. key "/opt" . _Object == HM.empty
116+ sampleVolumes = [Volume "/tmp", Volume "/opt"]
238117
239118integrationTests :: TestTree
240−integrationTests =
241− testGroup
242− "Integration Tests"
243− [ testCase "Get docker version" testDockerVersion
244− , testCase "Build image from Dockerfile" testBuildFromDockerfile
245− , testCase "Find image by name" testFindImage
246− , testCase "Delete image" testDeleteImage
247− , testCase "List containers" testListContainers
248− , testCase "Run a dummy container and read its log" testRunAndReadLog
249− , testCase "Run a dummy container with networking and read its log" testRunAndReadLogWithNetworking
250− , testCase "Try to stop a container that doesn't exist" testStopNonexisting
251− , testCase "Create and remove a network" testCreateRemoveNetwork
252− ]
119+integrationTests = testGroup "Integration Tests" [
120+ testCase "Get docker version" testDockerVersion,
121+ testCase "Find image by name" testFindImage,
122+ testCase "Run a dummy container and read its log" testRunAndReadLog]
253123
254124jsonTests :: TestTree
255−jsonTests =
256− testGroup
257− "JSON Tests"
258− [ testExposedPortsJson
259− , testVolumesJson
260− , testLabelsJson
261− , testLogDriverOptionsJson
262− , testEntrypointJson
263− , testEnvVarJson
264− , testNetworkingConfigJson
265− ]
125+jsonTests = testGroup "JSON Tests" [testExposedPortsJson, testVolumesJson, testLabelsJson, testLogDriverOptionsJson]
266126
267127setup :: IO ()
268−setup =
269− mapM_ system
270− [ "docker pull " ++ unpack imageToDeleteFullName
271− , "docker build -t " ++ unpack testImageName ++ " tests"
272− ]
273−
274−isLeft = not . isRight
128+setup = system ("docker build -t "++unpack testImageName++" tests") >> return ()
275129
276−isRight (Left _) = False
130+isRight (Left _) = False
277131isRight (Right _) = True
278132
279−fromRight
280− :: (MonadIO m, Show l)
281− => Either l r -> m r
133+fromRight :: (MonadIO m, Show l) => Either l r -> m r
282134fromRight (Left l) = do
283− liftIO $ assertFailure $ "Left: " ++ show l
284− undefined
135+ liftIO $ assertFailure $ "Left: " ++ show l
136+ undefined
285137fromRight (Right r) = return r
286138
287139main :: IO ()
288140main = do
289− stackage <- lookupEnv "RUN_INTEGRATION_TESTS"
290− case stackage of
291− Nothing -> defaultMain $ testGroup "Tests" [jsonTests]
292− Just _ -> do
293− setup
294− defaultMain $ testGroup "Tests" [jsonTests, integrationTests]
141+ setup
142+ defaultMain $ testGroup "Tests" [jsonTests, integrationTests]
143+