on master help sign in
20 files changed+541−105
since splitsnapshots
unifiedsplit
.travis.yml+25−3 CHANGELOG.md+71 CONTRIBUTING.md+12−2 LICENSE+1−1 Makefile+21−2 README.md+26−9 docker.cabal+24−12 src/Docker/Client.hs+1−1 src/Docker/Client/Api.hs+21−3 src/Docker/Client/Http.hs+40−7 src/Docker/Client/Internal.hs+11−3 src/Docker/Client/Types.hs+149−41 stack-7.10.yaml+5−5 stack-8.0.2.yaml+4 stack-8.0.yaml+2−1 stack-8.6.4.yaml+4 stack-8.8.2.yaml+5 stack.yaml+1−1 tests/Dockerfile+1−1 tests/tests.hs+117−13
.travis.yml+25−3
@@ -22,8 +22,30 @@ services:
2222 - docker
2323
2424env:
25− - GHCVER=7.10 STACK_ARGS=""
26− - GHCVER=8.0 STACK_ARGS=""
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
2749
2850addons:
2951 apt:
@@ -35,7 +57,7 @@ before_install:
3557 - sudo sh -c 'echo "deb https://apt.dockerproject.org/repo ubuntu-trusty main" > /etc/apt/sources.list.d/docker.list'
3658 - sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
3759 - sudo apt-get update
38− - sudo apt-get -qqy -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" install docker-engine=1.12.3-0~trusty
60+ - sudo apt-get -qqy -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" install docker-engine=$DOCKER_VERSION
3961
4062install:
4163 - mkdir -p "$HOME"/.local/bin
CHANGELOG.md+71
@@ -1,5 +1,76 @@
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+
374## 0.3.0.1 (2016-09-07)
475
576- Small cosmetic changes and marking OVERLAPPING instance
CONTRIBUTING.md+12−2
@@ -1,4 +1,14 @@
1−# TODO
1+# Contributing
22
3−Add basic guidelines here, things like style guide (using .configuration files from the repo) etc etc.
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.
49
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) 2016, Deni Bertovic
1+Copyright (c) 2014, Deni Bertovic
22
33All rights reserved.
44
Makefile+21−2
@@ -1,4 +1,6 @@
1−.PHONY: build repl test release
1+.PHONY: build repl test release help
2+
3+.DEFAULT_GOAL = help
24
35PROJECT_NAME ?= $(shell grep "^name" docker.cabal | cut -d " " -f17)
46VERSION ?= $(shell grep "^version:" docker.cabal | cut -d " " -f14)
@@ -6,18 +8,35 @@ RESOLVER ?= $(shell grep "^resolver:" stack.yaml | cut -d " " -f2)
68GHC_VERSION ?= $(shell stack ghc -- --version | cut -d " " -f8)
79ARCH=$(shell uname -m)
810
11+## Run build
912build:
1013 @stack build
1114
15+## Run repl
1216repl:
1317 @stack repl
1418
19+## Run tests. Example RUN_INTEGRATION_TESTS=1 make test
1520test:
16− @stack test
21+ @RUN_INTEGRATION_TESTS=1 stack test
1722
23+## Cut new release
1824release:
1925 @stack build --haddock
2026 @stack sdist
2127 @echo "\n\nDone. Now run: \n\nstack upload <path_to_tarball>\n"
2228 @echo "\nAnd: \n\ngit tag ${VERSION} && git push --tags\n"
2329
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+26−9
@@ -7,25 +7,42 @@
77
88## Current state
99
10−**API is still not stable.**
11−
12−Supported Docker Engine Api version: `v1.24`
10+Supported Docker Engine Api version: `v1.24` and onwards.
1311
1412Anything upward of that should work since Docker versions their API.
1513Older docker version and engine api versions are not supported at the moment.
1614
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+
1722## Contributing
1823
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.
24+Please see [CONTRIBUTING.md](CONTRIBUTING.md).
25+
26+### Project Setup
2127
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.
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).
2533
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`.
2644
2745## IRC
2846
2947If you have any questions or suggestions you can find the maintainers in `#docker-haskell`
3048on freenode.
31−
docker.cabal+24−12
@@ -1,5 +1,5 @@
11name: docker
2−version: 0.4.0.0
2+version: 0.6.0.3
33synopsis: An API client for docker written in Haskell
44description: See API documentation below.
55homepage: https://github.com/denibertovic/docker-hs
@@ -14,25 +14,29 @@ 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+
1722library
18− default-extensions: DeriveGeneric, OverloadedStrings, ScopedTypeVariables, ExplicitForAll, MultiParamTypeClasses, FlexibleContexts, GeneralizedNewtypeDeriving, RankNTypes, DeriveFunctor, FlexibleInstances
23+ default-extensions: DeriveGeneric, OverloadedStrings, ScopedTypeVariables, ExplicitForAll, MultiParamTypeClasses, FlexibleContexts, GeneralizedNewtypeDeriving, RankNTypes, DeriveFunctor, FlexibleInstances, CPP
1924 hs-source-dirs: src
2025 exposed-modules: Docker.Client, Docker.Client.Api, Docker.Client.Types, Docker.Client.Internal, Docker.Client.Http, Docker.Client.Utils
2126 -- other-modules: Docker.Internal
2227 build-depends: base >= 4.7 && < 5
23− , aeson >= 0.9.0 && < 1.1.0
28+ , aeson >= 0.9.0 && < 2.0.0
2429 , blaze-builder >= 0.4.0 && < 0.5.0
2530 , bytestring >= 0.10.0 && < 0.11.0
26− , containers >= 0.5.0 && < 0.6.0
31+ , containers >= 0.5.0 && < 0.7.0
2732 , data-default-class >= 0.0.1 && < 0.2.0
28− , http-client >= 0.4.0 && < 0.5.0
29− , http-types >= 0.9 && < 0.10.0
33+ , http-client >= 0.4.0 && < 0.7.0
34+ , http-types >= 0.9 && < 0.13
3035 , vector
3136 , conduit
3237 , conduit-combinators
3338 , conduit-extra
3439 , exceptions
35− , http-conduit
3640 , monad-control
3741 , resourcet
3842 , transformers
@@ -47,13 +51,20 @@ library
4751 , mtl >= 2.0.0 && < 3.0.0
4852 , network >= 2.6.0
4953 , text >= 1.0.0 && < 2.0.0
50− , time >= 1.5.0 && < 1.7.0
54+ , time >= 1.5.0 && < 2.0.0
5155 , scientific >= 0.3.0 && < 0.4.0
52− , tls >= 1.3.7 && < 1.4.0
56+ , tls >= 1.3.7 && < 1.6.0
5357 , unordered-containers >= 0.2.0 && < 0.3.0
54− , x509 >= 1.6.0 && < 1.7.0
55− , x509-store >= 1.6.0 && < 1.7.0
56− , x509-system >= 1.6.0 && < 1.7.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
5768 default-language: Haskell2010
5869 ghc-options: -Wall -fno-warn-name-shadowing
5970
@@ -62,6 +73,7 @@ test-suite docker-hs-tests
6273 , bytestring
6374 , connection
6475 , docker
76+ , directory
6577 , aeson
6678 , containers
6779 , unordered-containers
src/Docker/Client.hs+1−1
@@ -3,7 +3,7 @@
33
44{-|
55Module : Docker.Client
6−Copyright : (c) Deni Bertovic, 2016
6+Copyright : (c) Deni Bertovic, 2014
77License : BSD3
88Maintainer : deni@denibertovic.com
99Stability : experimental
src/Docker/Client/Api.hs+21−3
@@ -18,8 +18,12 @@ module Docker.Client.Api (
1818 , getContainerLogsStream
1919 -- * Images
2020 , listImages
21+ , deleteImage
2122 , buildImageFromDockerfile
2223 , pullImage
24+ -- * Network
25+ , createNetwork
26+ , removeNetwork
2327 -- * Other
2428 , getDockerVersion
2529 ) where
@@ -43,7 +47,7 @@ import Docker.Client.Types
4347import Docker.Client.Utils
4448
4549requestUnit :: (MonadIO m, MonadMask m) => HttpVerb -> Endpoint -> DockerT m (Either DockerError ())
46−requestUnit verb endpoint = const (Right ()) <$> requestHelper verb endpoint
50+requestUnit verb endpoint = fmap (const ()) <$> requestHelper verb endpoint
4751
4852requestHelper :: (MonadIO m, MonadMask m) => HttpVerb -> Endpoint -> DockerT m (Either DockerError BSL.ByteString)
4953requestHelper verb endpoint = requestHelper' verb endpoint Conduit.sinkLbs
@@ -90,6 +94,12 @@ listContainers opts = requestHelper GET (ListContainersEndpoint opts) >>= parseR
9094listImages :: forall m. (MonadIO m, MonadMask m) => ListOpts -> DockerT m (Either DockerError [Image])
9195listImages opts = requestHelper GET (ListImagesEndpoint opts) >>= parseResponse
9296
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+
93103-- | Creates a docker container but does __not__ start it. See
94104-- 'CreateOpts' for a list of options and you can use 'defaultCreateOpts'
95105-- for some sane defaults.
@@ -135,9 +145,9 @@ unpauseContainer :: forall m. (MonadIO m, MonadMask m) => ContainerID -> DockerT
135145unpauseContainer cid = requestUnit GET $ UnpauseContainerEndpoint cid
136146
137147-- | Deletes a container with the given 'ContainerID'.
138−-- See "DeleteOpts" for options and use 'defaultDeleteOpts' for sane
148+-- See "ContainerDeleteOpts" for options and use 'defaultContainerDeleteOpts' for sane
139149-- defaults.
140−deleteContainer :: forall m. (MonadIO m, MonadMask m) => DeleteOpts -> ContainerID -> DockerT m (Either DockerError ())
150+deleteContainer :: forall m. (MonadIO m, MonadMask m) => ContainerDeleteOpts -> ContainerID -> DockerT m (Either DockerError ())
141151deleteContainer dopts cid = requestUnit DELETE $ DeleteContainerEndpoint dopts cid
142152
143153-- | Gets 'ContainerDetails' for a given 'ContainerID'.
@@ -207,3 +217,11 @@ buildImageFromDockerfile opts base = do
207217pullImage :: forall m b . (MonadIO m, MonadMask m) => T.Text -> Tag -> Sink BS.ByteString m b -> DockerT m (Either DockerError b)
208218pullImage name tag = requestHelper' POST (CreateImageEndpoint name tag Nothing)
209219
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+40−7
@@ -5,6 +5,9 @@ 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
811import Control.Monad.Reader (ReaderT (..), runReaderT)
912import qualified Data.ByteString.Char8 as BSC
1013import qualified Data.ByteString.Lazy as BL
@@ -17,7 +20,7 @@ import Data.X509.CertificateStore (makeCertificateStore)
1720import Data.X509.File (readKeyFile, readSignedObject)
1821import Network.HTTP.Client (defaultManagerSettings,
1922 managerRawConnection, method,
20− newManager, parseUrl,
23+ newManager, parseRequest,
2124 requestBody, requestHeaders)
2225import qualified Network.HTTP.Client as HTTP
2326import Network.HTTP.Client.Internal (makeConnection)
@@ -94,7 +97,7 @@ runDockerT (opts, h) r = runReaderT (unDockerT r) (opts, h)
9497mkHttpRequest :: HttpVerb -> Endpoint -> DockerClientOpts -> Maybe Request
9598mkHttpRequest verb e opts = request
9699 where fullE = T.unpack (baseUrl opts) ++ T.unpack (getEndpoint (apiVer opts) e)
97− initialR = parseUrl fullE
100+ initialR = parseRequest fullE
98101 request' = case initialR of
99102 Just ir ->
100103 return $ ir {method = (encodeUtf8 . T.pack $ show verb),
@@ -104,18 +107,30 @@ mkHttpRequest verb e opts = request
104107 requestHeaders = [("Content-Type", "application/json; charset=utf-8")]}) $ getEndpointRequestBody e) <$> request'
105108 -- Note: Do we need to set length header?
106109
107−defaultHttpHandler :: (MonadIO m, MonadMask m) => m (HttpHandler m)
110+defaultHttpHandler :: (
111+#if MIN_VERSION_http_conduit(2,3,0)
112+ MonadUnliftIO m,
113+#endif
114+ MonadIO m, MonadMask m) => m (HttpHandler m)
108115defaultHttpHandler = do
109116 manager <- liftIO $ newManager defaultManagerSettings
110117 return $ httpHandler manager
111118
112−httpHandler :: (MonadIO m, MonadMask m) => HTTP.Manager -> HttpHandler m
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
113124httpHandler manager = HttpHandler $ \request' sink -> do -- runResourceT ..
114125 let request = NHS.setRequestManager manager request'
115126 try (NHS.httpSink request sink) >>= \res -> case res of
116127 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
117131 Left e@HTTP.FailedConnectionException{} -> return $ Left $ DockerConnectionError e
118132 Left e@HTTP.FailedConnectionException2{} -> return $ Left $ DockerConnectionError e
133+#endif
119134 Left e -> return $ Left $ GenericDockerError (T.pack $ show e)
120135
121136-- | Connect to a unix domain socket (the default docker socket is
@@ -123,7 +138,11 @@ httpHandler manager = HttpHandler $ \request' sink -> do -- runResourceT ..
123138--
124139-- Docker seems to ignore the hostname in requests sent over unix domain
125140-- sockets (and the port obviously doesn't matter either)
126−unixHttpHandler :: (MonadIO m, MonadMask m) => FilePath -- ^ The socket to connect to
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
127146 -> m (HttpHandler m)
128147unixHttpHandler fp = do
129148 let mSettings = defaultManagerSettings
@@ -137,7 +156,7 @@ unixHttpHandler fp = do
137156 S.connect s (S.SockAddrUnix filePath)
138157 makeConnection (SBS.recv s 8096)
139158 (SBS.sendAll s)
140− (S.sClose s)
159+ (S.close s)
141160
142161-- TODO:
143162-- Move this to http-client-tls or network?
@@ -254,4 +273,18 @@ statusCodeToError (CreateImageEndpoint _ _ _) st =
254273 Nothing
255274 else
256275 Just $ DockerInvalidStatusCode st
257−
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
src/Docker/Client/Internal.hs+11−3
@@ -5,12 +5,13 @@ 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 Data.Text as T
8+import qualified 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)
1415
1516import Docker.Client.Types
1617
@@ -26,7 +27,7 @@ encodeQ = encodeUtf8 . T.pack
2627
2728getEndpoint :: ApiVersion -> Endpoint -> T.Text
2829getEndpoint v VersionEndpoint = encodeURL [v, "version"]
29−getEndpoint v (ListContainersEndpoint _) = encodeURL [v, "containers", "json"] -- Make use of lsOpts here
30+getEndpoint v (ListContainersEndpoint (ListOpts all)) = encodeURLWithQuery [v, "containers", "json"] [("all", Just (encodeQ $ show all))]
3031getEndpoint v (ListImagesEndpoint _) = encodeURL [v, "images", "json"] -- Make use of lsOpts here
3132getEndpoint v (CreateContainerEndpoint _ cn) = case cn of
3233 Just cn -> encodeURLWithQuery [v, "containers", "create"] [("name", Just (encodeQ $ T.unpack cn))]
@@ -56,7 +57,7 @@ getEndpoint v (UnpauseContainerEndpoint cid) = encodeURL [v, "containers", fromC
5657getEndpoint v (ContainerLogsEndpoint (LogOpts stdout stderr _ _ _) follow cid) =
5758 encodeURLWithQuery [v, "containers", fromContainerID cid, "logs"] query
5859 where query = [("stdout", Just (encodeQ $ show stdout)), ("stderr", Just (encodeQ $ show stderr)), ("follow", Just (encodeQ $ show follow))]
59−getEndpoint v (DeleteContainerEndpoint (DeleteOpts removeVolumes force) cid) =
60+getEndpoint v (DeleteContainerEndpoint (ContainerDeleteOpts removeVolumes force) cid) =
6061 encodeURLWithQuery [v, "containers", fromContainerID cid] query
6162 where query = [("v", Just (encodeQ $ show removeVolumes)), ("force", Just (encodeQ $ show force))]
6263getEndpoint v (InspectContainerEndpoint cid) =
@@ -74,6 +75,9 @@ getEndpoint v (CreateImageEndpoint name tag _) = encodeURLWithQuery [v, "images"
7475 where query = [("fromImage", Just n), ("tag", Just t)]
7576 n = encodeQ $ T.unpack name
7677 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]
7781
7882getEndpointRequestBody :: Endpoint -> Maybe HTTP.RequestBody
7983getEndpointRequestBody VersionEndpoint = Nothing
@@ -93,6 +97,10 @@ getEndpointRequestBody (InspectContainerEndpoint _) = Nothing
9397
9498getEndpointRequestBody (BuildImageEndpoint _ fp) = Just $ requestBodySourceChunked $ CB.sourceFile fp
9599getEndpointRequestBody (CreateImageEndpoint _ _ _) = Nothing
100+getEndpointRequestBody (DeleteImageEndpoint _ _) = Nothing
101+
102+getEndpointRequestBody (CreateNetworkEndpoint opts) = Just $ HTTP.RequestBodyLBS (JSON.encode opts)
103+getEndpointRequestBody (RemoveNetworkEndpoint _) = Nothing
96104
97105getEndpointContentType :: Endpoint -> BSC.ByteString
98106getEndpointContentType (BuildImageEndpoint _ _) = BSC.pack "application/tar"
src/Docker/Client/Types.hs+149−41
@@ -11,6 +11,9 @@ module Docker.Client.Types (
1111 , ImageID
1212 , fromImageID
1313 , toImageID
14+ , NetworkID
15+ , fromNetworkID
16+ , toNetworkID
1417 , Timeout(..)
1518 , StatusCode(..)
1619 , Signal(..)
@@ -23,7 +26,7 @@ module Docker.Client.Types (
2326 , ContainerPortInfo(..)
2427 , Container(..)
2528 , ContainerState(..)
26− , Status(..)
29+ , State(..)
2730 , Digest
2831 , Label(..)
2932 , Tag
@@ -37,12 +40,16 @@ module Docker.Client.Types (
3740 , DetachKeys(..)
3841 , StartOpts(..)
3942 , defaultStartOpts
40− , DeleteOpts(..)
41− , defaultDeleteOpts
43+ , ContainerDeleteOpts(..)
44+ , defaultContainerDeleteOpts
45+ , ImageDeleteOpts(..)
46+ , defaultImageDeleteOpts
4247 , Timestamp
4348 , TailLogOpt(..)
4449 , LogOpts(..)
4550 , defaultLogOpts
51+ , CreateNetworkOpts(..)
52+ , defaultCreateNetworkOpts
4653 , VolumePermission(..)
4754 , Bind(..)
4855 , Volume(..)
@@ -68,6 +75,8 @@ module Docker.Client.Types (
6875 , UTSMode(..)
6976 , HostConfig(..)
7077 , defaultHostConfig
78+ , NetworkingConfig(..)
79+ , EndpointConfig(..)
7180 , Ulimit(..)
7281 , ContainerResources(..)
7382 , defaultContainerResources
@@ -123,10 +132,13 @@ data Endpoint =
123132 | UnpauseContainerEndpoint ContainerID
124133 | ContainerLogsEndpoint LogOpts Bool ContainerID -- ^ Second argument (Bool) is whether to follow which is currently hardcoded to False.
125134 -- See note in 'Docker.Client.Api.getContainerLogs' for explanation why.
126− | DeleteContainerEndpoint DeleteOpts ContainerID
135+ | DeleteContainerEndpoint ContainerDeleteOpts ContainerID
127136 | InspectContainerEndpoint ContainerID
128137 | BuildImageEndpoint BuildOpts FilePath
129138 | 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
130142 deriving (Eq, Show)
131143
132144-- | We should newtype this
@@ -238,7 +250,7 @@ data ContainerDetails = ContainerDetails {
238250 , processLabel :: Text
239251 , resolveConfPath :: FilePath
240252 , restartCount :: Int
241− , state :: ContainerState
253+ , containerDetailsState :: ContainerState
242254 , mounts :: [Mount]
243255 }
244256 deriving (Eq, Show, Generic)
@@ -246,11 +258,11 @@ data ContainerDetails = ContainerDetails {
246258-- | Data type used for parsing the mount information from a container
247259-- list.
248260data Mount = Mount {
249− mountName :: Text
261+ mountName :: Maybe Text -- this is optional
250262 , mountSource :: FilePath
251263 , mountDestination :: FilePath
252− , mountDriver :: Text
253− , mountMode :: Maybe VolumePermission -- apparently this can be null
264+ , mountDriver :: Maybe Text
265+ -- , mountMode :: Maybe VolumePermission -- apparently this can be null
254266 , mountRW :: Bool
255267 , mountPropogation :: Text
256268 }
@@ -258,14 +270,14 @@ data Mount = Mount {
258270
259271instance FromJSON Mount where
260272 parseJSON (JSON.Object o) = do
261− name <- o .: "Name"
273+ name <- o .:? "Name"
262274 src <- o .: "Source"
263275 dest <- o .: "Destination"
264− driver <- o .: "Driver"
265− mode <- o .: "Mode"
276+ driver <- o .:? "Driver"
277+ -- mode <- o .: "Mode"
266278 rw <- o .: "RW"
267279 prop <- o .: "Propagation"
268− return $ Mount name src dest driver mode rw prop
280+ return $ Mount name src dest driver rw prop
269281 parseJSON _ = fail "Mount is not an object"
270282
271283-- | Data type used for parsing the container state from a list of
@@ -281,7 +293,7 @@ data ContainerState = ContainerState {
281293 , restarting :: Bool
282294 , running :: Bool
283295 , startedAt :: UTCTime
284− , status :: Status
296+ , state :: State
285297 }
286298 deriving (Eq, Show, Generic)
287299
@@ -511,7 +523,8 @@ data Container = Container
511523 , containerImageId :: ImageID
512524 , containerCommand :: Text
513525 , containerCreatedAt :: Int
514− , containerStatus :: Status
526+ , containerState :: State
527+ , containerStatus :: Maybe Text
515528 , containerPorts :: [ContainerPortInfo]
516529 , containerLabels :: [Label]
517530 , containerNetworks :: [Network]
@@ -519,13 +532,14 @@ data Container = Container
519532 } deriving (Show, Eq)
520533
521534instance FromJSON Container where
522− parseJSON (JSON.Object v) =
523− Container <$> (v .: "Id")
535+ parseJSON o@(JSON.Object v) =
536+ Container <$> parseJSON o
524537 <*> (v .: "Names")
525538 <*> (v .: "Image")
526− <*> (v .: "ImageID")
527− <*> (v .: "Command")
539+ <*> (v .: "ImageID") -- Doesn't exist anymore
540+ <*> (v .: "Command") -- Doesn't exist anymore
528541 <*> (v .: "Created")
542+ <*> (v .: "State")
529543 <*> (v .: "Status")
530544 <*> (v .: "Ports")
531545 <*> (v .: "Labels")
@@ -535,21 +549,20 @@ instance FromJSON Container where
535549 parseNetworks (JSON.Object v) =
536550 (v .: "Networks") >>= parseJSON
537551 parseNetworks _ = fail "Container NetworkSettings: Not a JSON object."
538−
539552 parseJSON _ = fail "Container: Not a JSON object."
540553
541−-- | Represents the status of the container life cycle.
542−data Status = Created | Restarting | Running | Paused | Exited | Dead
554+-- | Represents the state of the container life cycle.
555+data State = Created | Restarting | Running | Paused | Exited | Dead
543556 deriving (Eq, Show, Generic)
544557
545−instance FromJSON Status where
558+instance FromJSON State where
546559 parseJSON (JSON.String "running") = return Running
547560 parseJSON (JSON.String "created") = return Created -- Note: Guessing on the string values of these.
548561 parseJSON (JSON.String "restarting") = return Restarting
549562 parseJSON (JSON.String "paused") = return Paused
550563 parseJSON (JSON.String "exited") = return Exited
551564 parseJSON (JSON.String "dead") = return Dead
552− parseJSON _ = fail "Unknown Status"
565+ parseJSON s = fail $ "Unknown Status: " ++ show s
553566
554567-- | Alias for representing a RepoDigest. We could newtype this and add
555568-- some validation.
@@ -610,20 +623,46 @@ instance FromJSON Image where
610623 return $ DockerImage imageId imageCreated imageParentId imageRepoTags imageRepoDigests imageSize imageVirtualSize imageLabels
611624 parseJSON _ = fail "Failed to parse DockerImage."
612625
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+ ]
613649
614650-- | Options used for creating a Container.
615651data CreateOpts = CreateOpts {
616− containerConfig :: ContainerConfig
617− , hostConfig :: HostConfig
652+ containerConfig :: ContainerConfig
653+ , hostConfig :: HostConfig
654+ , networkingConfig :: NetworkingConfig
618655 } deriving (Eq, Show)
619656
620657instance ToJSON CreateOpts where
621− toJSON (CreateOpts cc hc) = do
658+ toJSON (CreateOpts cc hc nc) = do
622659 let ccJSON = toJSON cc
623660 let hcJSON = toJSON hc
624661 case ccJSON of
625662 JSON.Object (o :: HM.HashMap T.Text JSON.Value) -> do
626− JSON.Object $ HM.insert "HostConfig" hcJSON o
663+ let o1 = HM.insert "HostConfig" hcJSON o
664+ let o2 = HM.insert "NetworkingConfig" (toJSON nc) o1
665+ JSON.Object o2
627666 _ -> error "ContainerConfig is not an object." -- This should never happen.
628667
629668-- | Container configuration used for creating a container with sensible
@@ -658,7 +697,7 @@ defaultHostConfig = HostConfig {
658697 binds=[]
659698 , containerIDFile=Nothing
660699 , logConfig=LogDriverConfig JsonFile []
661− , networkMode=Bridge
700+ , networkMode=NetworkBridge
662701 , portBindings=[]
663702 , restartPolicy=RestartOff
664703 , volumeDriver=Nothing
@@ -698,14 +737,18 @@ defaultContainerResources = ContainerResources {
698737 , memory=Nothing
699738 , memoryReservation=Nothing
700739 , memorySwap=Nothing
701− , oomKillDisable=False
740+ , oomKillDisable=Just False
702741 , ulimits=[]
703742 }
704743
705744-- | Default create options when creating a container. You only need to
706745-- specify an image name and the rest is all sensible defaults.
707746defaultCreateOpts :: T.Text -> CreateOpts
708−defaultCreateOpts imageName = CreateOpts { containerConfig = defaultContainerConfig imageName, hostConfig = defaultHostConfig }
747+defaultCreateOpts imageName = CreateOpts
748+ { containerConfig = defaultContainerConfig imageName
749+ , hostConfig = defaultHostConfig
750+ , networkingConfig = NetworkingConfig HM.empty
751+ }
709752
710753-- | Override the key sequence for detaching a container.
711754-- Format is a single character [a-Z] or ctrl-<value> where <value> is one of: a-z, @, ^, [, , or _.
@@ -719,7 +762,7 @@ defaultStartOpts :: StartOpts
719762defaultStartOpts = StartOpts { detachKeys = DefaultDetachKey }
720763
721764-- | Options for deleting a container.
722−data DeleteOpts = DeleteOpts {
765+data ContainerDeleteOpts = ContainerDeleteOpts {
723766 deleteVolumes :: Bool -- ^ Automatically cleanup volumes that the container created as well.
724767 , force :: Bool -- ^ If the container is still running force deletion anyway.
725768 } deriving (Eq, Show)
@@ -749,8 +792,15 @@ defaultBuildOpts nameTag = BuildOpts { buildImageName = nameTag
749792-- | Default options for deleting a container. Most of the time we DON'T
750793-- want to delete the container's volumes or force delete it if it's
751794-- running.
752−defaultDeleteOpts :: DeleteOpts
753−defaultDeleteOpts = DeleteOpts { deleteVolumes = False, force = False }
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
754804
755805-- | Timestamp alias.
756806type Timestamp = Integer
@@ -778,6 +828,36 @@ defaultLogOpts = LogOpts { stdout = True
778828 , tail = All
779829 }
780830
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+
781861-- TOOD: Add support for SELinux Volume labels (eg. "ro,z" or "ro/Z")
782862-- | Set permissions on volumes that you mount in the container.
783863data VolumePermission = ReadWrite | ReadOnly deriving (Eq, Show, Generic)
@@ -789,6 +869,8 @@ instance ToJSON VolumePermission where
789869instance FromJSON VolumePermission where
790870 parseJSON "rw" = return ReadWrite
791871 parseJSON "ro" = return ReadOnly
872+ parseJSON "RW" = return ReadWrite
873+ parseJSON "RO" = return ReadOnly
792874 parseJSON _ = fail "Failed to parse VolumePermission"
793875
794876-- | Used for marking a directory in the container as "exposed" hence
@@ -935,19 +1017,41 @@ instance FromJSON LogDriverConfig where
9351017 parseJSON _ = fail "LogDriverConfig is not an object"
9361018
9371019-- TODO: Add container:<name|id> mode
938−data NetworkMode = Bridge | Host | NetworkDisabled
1020+data NetworkMode = NetworkBridge | NetworkHost | NetworkDisabled | NetworkNamed Text
9391021 deriving (Eq, Show, Ord)
9401022
9411023instance FromJSON NetworkMode where
942− parseJSON (JSON.String "bridge") = return Bridge
943− parseJSON (JSON.String "host") = return Host -- Note: Guessing on these.
1024+ parseJSON (JSON.String "bridge") = return NetworkBridge
1025+ parseJSON (JSON.String "host") = return NetworkHost -- Note: Guessing on these.
9441026 parseJSON (JSON.String "none") = return NetworkDisabled
1027+ parseJSON (JSON.String n) = return $ NetworkNamed n
9451028 parseJSON _ = fail "Unknown NetworkMode"
9461029
9471030instance ToJSON NetworkMode where
948− toJSON Bridge = JSON.String "bridge"
949− toJSON Host = JSON.String "host"
950− toJSON NetworkDisabled = JSON.String "none"
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]
9511055
9521056data PortType = TCP | UDP deriving (Eq, Generic, Read, Ord)
9531057
@@ -1310,7 +1414,7 @@ data ContainerResources = ContainerResources {
13101414 , memoryReservation :: Maybe MemoryConstraint
13111415 , memorySwap :: Maybe MemoryConstraint
13121416 -- , memorySwappiness :: Integer -- 1.24: Missing from inspecting container details... Going to omit for now.
1313− , oomKillDisable :: Bool
1417+ , oomKillDisable :: Maybe Bool
13141418 -- , pidsLimit :: Integer -- 1.24: Missing from inspecting container details... Going to omit for now.
13151419 , ulimits :: [Ulimit]
13161420 -- TODO: Missing from 1.24
@@ -1348,7 +1452,7 @@ instance FromJSON EnvVar where
13481452 parseJSON _ = fail "EnvVar is not a string"
13491453
13501454instance ToJSON EnvVar where
1351− toJSON (EnvVar n v) = object [n .= v]
1455+ toJSON (EnvVar n v) = JSON.String $ n <> T.pack "=" <> v
13521456
13531457-- | ExposedPort represents a port (and it's type)
13541458-- that a container should expose to other containers or the host system.
@@ -1460,7 +1564,11 @@ instance FromJSON ContainerConfig where
14601564 macAddress labels stopSignal
14611565 parseJSON _ = fail "NetworkSettings is not an object."
14621566
1567+#if MIN_VERSION_base(4,13,0)
1568+parseIntegerText :: (MonadFail m) => Text -> m Integer
1569+#else
14631570parseIntegerText :: (Monad m) => Text -> m Integer
1571+#endif
14641572parseIntegerText t = case readMaybe $ T.unpack t of
14651573 Nothing ->
14661574 fail "Could not parse Integer"
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-5.18
4+resolver: lts-6.30
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−
1310# Override default flag values for local packages and extra-deps
1411flags: {}
1512
1613# Extra package databases containing global packages
17−extra-package-dbs: []
14+extra-deps:
15+- directory-1.2.7.0
16+- unliftio-core-0.1.1.0
17+- process-1.6.5.1
1818
1919# Control whether we use the GHC we find on the path
2020# system-ghc: true
stack-8.0.2.yamlnew file+4
@@ -0,0 +1,4 @@
1+resolver: lts-9.4
2+packages:
3+- '.'
4+extra-deps: []
stack-8.0.yaml+2−1
@@ -1,4 +1,5 @@
11resolver: lts-7.12
22packages:
33- '.'
4−extra-deps: []
4+extra-deps:
5+- unliftio-core-0.1.1.0
stack-8.6.4.yamlnew file+4
@@ -0,0 +1,4 @@
1+resolver: lts-13.19
2+packages:
3+- '.'
4+extra-deps: []
stack-8.8.2.yamlnew file+5
@@ -0,0 +1,5 @@
1+resolver: lts-15.0
2+packages:
3+- '.'
4+extra-deps: []
5+
stack.yaml+1−1
@@ -1 +1 @@
1−stack-7.10.yaml
1+stack-8.6.4.yaml
tests/Dockerfile+1−1
@@ -1,4 +1,4 @@
11FROM debian:jessie
22
3−CMD ["/bin/bash", "-c", "echo 123"]
3+CMD ["/bin/bash", "-c", "echo $TEST"]
44
tests/tests.hs+117−13
@@ -2,6 +2,8 @@
22
33module Main where
44
5+import Data.Either (rights)
6+import Prelude hiding (all)
57import qualified Test.QuickCheck.Monadic as QCM
68import Test.Tasty
79import Test.Tasty.HUnit
@@ -9,9 +11,11 @@ import Test.Tasty.QuickCheck (testProperty)
911
1012import Control.Concurrent (threadDelay)
1113import Control.Lens ((^.), (^?))
14+import Control.Monad (forM_)
1215import Control.Monad.IO.Class
1316import Control.Monad.Trans.Class (lift)
1417import qualified Data.Aeson as JSON
18+import Data.Aeson ((.=))
1519import Data.Aeson.Lens (key, _Array, _Null, _Object,
1620 _String, _Value)
1721import qualified Data.ByteString as B
@@ -20,7 +24,7 @@ import qualified Data.ByteString.Lazy as BL
2024import qualified Data.HashMap.Strict as HM
2125import Data.Int (Int)
2226import qualified Data.Map as M
23−import Data.Maybe (fromJust, isJust)
27+import Data.Maybe (fromJust, isJust, isNothing, listToMaybe)
2428import Data.Monoid
2529import Data.Text (Text, unpack)
2630import qualified Data.Vector as V
@@ -28,12 +32,15 @@ import Network.Connection (TLSSettings (..))
2832import Network.HTTP.Client (newManager)
2933import Network.HTTP.Client.TLS
3034import Network.HTTP.Types.Status
35+import System.Directory (getCurrentDirectory)
36+import System.Environment (lookupEnv)
3137import System.Process (system)
3238
3339import Docker.Client
3440
3541-- opts = defaultClientOpts
36−testImageName = "docker-hs-test"
42+testImageName = "docker-hs/test"
43+imageToDeleteFullName = "hello-world:latest"
3744
3845toStrict1 = B.concat . BL.toChunks
3946
@@ -53,33 +60,89 @@ testDockerVersion =
5360 do v <- getDockerVersion
5461 lift $ assert $ isRight v
5562
63+testStopNonexisting :: IO ()
64+testStopNonexisting = runDocker $ do
65+ res <- stopContainer DefaultTimeout $ fromJust $ toContainerID "thisshouldnotexist"
66+ lift $ assert $ isLeft res
67+
5668testFindImage :: IO ()
5769testFindImage =
5870 runDocker $
5971 do images <- listImages defaultListOpts >>= fromRight
60− let xs = filter ((== [imageFullName]) . imageRepoTags) images
72+ let xs = filter (elem imageFullName . imageRepoTags) images
6173 lift $ assert $ length xs == 1
6274 where
6375 imageFullName = testImageName <> ":latest"
6476
65−testRunAndReadLog :: IO ()
66−testRunAndReadLog =
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
87+ images <- listImages defaultListOpts >>= fromRight
88+ return $ listToMaybe
89+ $ filter (elem imageToDeleteFullName . imageRepoTags) images
90+
91+testListContainers :: IO ()
92+testListContainers =
6793 runDocker $
6894 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+
108+
109+testRunAndReadLog :: 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
69121 c <- fromRight containerId
70122 status1 <- startContainer defaultStartOpts c
71123 _ <- inspectContainer c >>= fromRight
72124 lift $ threadDelay 300000 -- give 300ms for the application to finish
73− lift $ assert $ isRightUnit status1
74− status2 <- killContainer SIGTERM c
125+ lift $ assertBool ("starting the container, unexpected status: " ++ show status1) $ isRightUnit status1
75126 logs <- getContainerLogs defaultLogOpts c >>= fromRight
76− lift $ assert $ isRightUnit status2
77127 lift $ assert $ (C.pack "123") `C.isInfixOf` (toStrict1 logs)
78− status3 <- deleteContainer (DeleteOpts True True) c
79− lift $ assert $ isRightUnit status3
128+ status3 <- deleteContainer (ContainerDeleteOpts True True) c
129+ lift $ assertBool ("deleting container, unexpected status: " ++ show status3) $ isRightUnit status3
130+ mapM_ removeNetwork createdNetworks
80131 where
81132 isRightUnit (Right ()) = True
82133 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
83146
84147testLogDriverOptionsJson :: TestTree
85148testLogDriverOptionsJson = testGroup "Testing LogDriverOptions JSON" [test1, test2, test3]
@@ -150,13 +213,42 @@ testEntrypointJson = testGroup "Testing ContainerConfig JSON" [testSample1, test
150213 Just (Entrypoint sampleEntrypointArr)
151214 sampleEntrypointArr = ["cmd", "--some-flag", "--some-flag2"]
152215
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+ ]
238+
153239integrationTests :: TestTree
154240integrationTests =
155241 testGroup
156242 "Integration Tests"
157243 [ testCase "Get docker version" testDockerVersion
244+ , testCase "Build image from Dockerfile" testBuildFromDockerfile
158245 , testCase "Find image by name" testFindImage
246+ , testCase "Delete image" testDeleteImage
247+ , testCase "List containers" testListContainers
159248 , 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
160252 ]
161253
162254jsonTests :: TestTree
@@ -168,10 +260,18 @@ jsonTests =
168260 , testLabelsJson
169261 , testLogDriverOptionsJson
170262 , testEntrypointJson
263+ , testEnvVarJson
264+ , testNetworkingConfigJson
171265 ]
172266
173267setup :: IO ()
174−setup = system ("docker build -t " ++ unpack testImageName ++ " tests") >> return ()
268+setup =
269+ mapM_ system
270+ [ "docker pull " ++ unpack imageToDeleteFullName
271+ , "docker build -t " ++ unpack testImageName ++ " tests"
272+ ]
273+
274+isLeft = not . isRight
175275
176276isRight (Left _) = False
177277isRight (Right _) = True
@@ -186,5 +286,9 @@ fromRight (Right r) = return r
186286
187287main :: IO ()
188288main = do
189− setup
190− defaultMain $ testGroup "Tests" [jsonTests, integrationTests]
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]