-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathDocker.hs
More file actions
1240 lines (1113 loc) · 34.4 KB
/
Docker.hs
File metadata and controls
1240 lines (1113 loc) · 34.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module TestContainers.Docker
( MonadDocker,
TestContainer,
-- * Configuration
Config (..),
defaultDockerConfig,
determineConfig,
-- * Exeuction tracing
Tracer,
Trace (..),
newTracer,
withTrace,
-- * Docker image
ImageTag,
Image,
imageTag,
-- * Port
Port (..),
-- * Docker container
ContainerId,
Container,
containerId,
containerImage,
containerAlias,
containerGateway,
containerIp,
containerPort,
containerAddress,
containerReleaseKey,
-- * Container state
State,
Status (..),
stateError,
stateExitCode,
stateFinishedAt,
stateOOMKilled,
statePid,
stateStartedAt,
stateStatus,
-- * Predicates to assert container state
successfulExit,
-- * Referring to images
ToImage,
fromTag,
fromBuildContext,
fromDockerfile,
build,
-- * Exceptions
DockerException (..),
-- * Running containers
ContainerRequest,
containerRequest,
withLabels,
setName,
setFixedName,
setSuffixedName,
setRandomName,
setCmd,
setVolumeMounts,
setRm,
setEnv,
withWorkingDirectory,
withNetwork,
withNetworkAlias,
setLink,
setExpose,
setWaitingFor,
run,
-- * Following logs
LogConsumer,
consoleLogConsumer,
withFollowLogs,
-- * Network related functionality
NetworkId,
Network,
NetworkRequest,
networkId,
networkRequest,
createNetwork,
fromExistingNetwork,
withIpv6,
withDriver,
-- * Managing the container lifecycle
InspectOutput,
inspect,
stop,
kill,
rm,
withLogs,
-- * Wait for containers to become ready
WaitUntilReady,
waitUntilReady,
-- * Only block for defined amounts of time
TimeoutException (..),
waitUntilTimeout,
-- * Wait for container state
waitForState,
-- * Wait until a specific pattern appears in the logs
waitWithLogs,
Pipe (..),
UnexpectedEndOfPipe (..),
waitForLogLine,
-- * Misc. Docker functions
dockerHostOs,
isDockerOnLinux,
-- * Wait until a socket is reachable
waitUntilMappedPortReachable,
-- * Wait until the http server responds with a specific status code
waitForHttp,
-- * Reaper
createRyukReaper,
-- * Reexports for convenience
ResIO,
runResourceT,
(&),
)
where
import Control.Concurrent (threadDelay)
import Control.Exception (IOException, throw)
import Control.Monad (forM_, replicateM, unless)
import Control.Monad.Catch
( Exception,
MonadCatch,
MonadThrow,
bracket,
throwM,
try,
)
import Control.Monad.IO.Class (MonadIO (liftIO))
import Control.Monad.IO.Unlift (MonadUnliftIO (withRunInIO))
import Control.Monad.Reader (MonadReader (..))
import Control.Monad.Trans.Resource
( ReleaseKey,
ResIO,
register,
runResourceT,
)
import Data.Aeson (decode')
import qualified Data.Aeson.Optics as Optics
import qualified Data.ByteString.Lazy.Char8 as LazyByteString
import Data.Function ((&))
import Data.List (find)
import Data.String (IsString (..))
import Data.Text (Text, pack, splitOn, strip, unpack)
import Data.Text.Encoding (encodeUtf8)
import Data.Text.Encoding.Error (lenientDecode)
import qualified Data.Text.Lazy as LazyText
import qualified Data.Text.Lazy.Encoding as LazyText
import Data.Text.Read (decimal)
import GHC.Stack (withFrozenCallStack)
import Network.HTTP.Client
( HttpException,
Manager,
Request (..),
defaultManagerSettings,
defaultRequest,
httpNoBody,
newManager,
responseStatus,
)
import Network.HTTP.Types (statusCode)
import qualified Network.Socket as Socket
import Optics.Fold (pre)
import Optics.Operators ((^?))
import Optics.Optic ((%))
import System.Directory (doesFileExist)
import System.IO (Handle, hClose)
import System.IO.Unsafe (unsafePerformIO)
import qualified System.Process as Process
import qualified System.Random as Random
import System.Timeout (timeout)
import TestContainers.Config
( Config (..),
defaultDockerConfig,
determineConfig,
)
import TestContainers.Docker.Internal
( ContainerId,
DockerException (..),
InspectOutput,
LogConsumer,
Pipe (..),
consoleLogConsumer,
docker,
dockerFollowLogs,
dockerWithStdin,
)
import TestContainers.Docker.Network
( Network,
NetworkId,
NetworkRequest,
createNetwork,
fromExistingNetwork,
networkId,
networkRequest,
withDriver,
withIpv6,
)
import TestContainers.Docker.Reaper
( Reaper,
newRyukReaper,
reaperLabels,
ryukImageTag,
ryukPort,
)
import TestContainers.Docker.State
( State,
Status (..),
containerState,
stateError,
stateExitCode,
stateFinishedAt,
stateOOMKilled,
statePid,
stateStartedAt,
stateStatus,
)
import TestContainers.Monad
( MonadDocker,
TestContainer,
)
import TestContainers.Trace (Trace (..), Tracer, newTracer, withTrace)
import Prelude hiding (error, id)
import qualified Prelude
-- | Parameters for a running a Docker container.
--
-- @since 0.1.0.0
data ContainerRequest = ContainerRequest
{ toImage :: ToImage,
cmd :: Maybe [Text],
env :: [(Text, Text)],
exposedPorts :: [Port],
volumeMounts :: [(Text, Text)],
network :: Maybe (Either Network Text),
networkAlias :: [Text],
links :: [ContainerId],
naming :: NamingStrategy,
rmOnExit :: Bool,
readiness :: WaitUntilReady,
labels :: [(Text, Text)],
noReaper :: Bool,
followLogs :: Maybe LogConsumer,
workDirectory :: Maybe Text
}
-- | Parameters for a naming a Docker container.
--
-- @since 0.5.0.0
data NamingStrategy
= RandomName
| FixedName Text
| SuffixedName Text
-- | Default `ContainerRequest`. Used as base for every Docker container.
--
-- @since 0.1.0.0
containerRequest :: ToImage -> ContainerRequest
containerRequest image =
ContainerRequest
{ toImage = image,
naming = RandomName,
cmd = Nothing,
env = [],
exposedPorts = [],
volumeMounts = [],
network = Nothing,
networkAlias = [],
links = [],
rmOnExit = False,
readiness = mempty,
labels = mempty,
noReaper = False,
followLogs = Nothing,
workDirectory = Nothing
}
-- | Set the name of a Docker container. This is equivalent to invoking @docker run@
-- with the @--name@ parameter.
--
-- @since 0.1.0.0
setName :: Text -> ContainerRequest -> ContainerRequest
setName = setFixedName
{-# DEPRECATED setName "See setFixedName" #-}
-- | Set the name of a Docker container. This is equivalent to invoking @docker run@
-- with the @--name@ parameter.
--
-- @since 0.5.0.0
setFixedName :: Text -> ContainerRequest -> ContainerRequest
setFixedName newName req =
-- TODO error on empty Text
req {naming = FixedName newName}
-- | Set the name randomly given of a Docker container. This is equivalent to omitting
-- the @--name@ parameter calling @docker run@.
--
-- @since 0.5.0.0
setRandomName :: ContainerRequest -> ContainerRequest
setRandomName req =
-- TODO error on empty Text
req {naming = RandomName}
-- | Set the name randomly suffixed of a Docker container. This is equivalent to invoking
-- @docker run@ with the @--name@ parameter.
--
-- @since 0.5.0.0
setSuffixedName :: Text -> ContainerRequest -> ContainerRequest
setSuffixedName preffix req =
-- TODO error on empty Text
req {naming = SuffixedName preffix}
-- | The command to execute inside the Docker container. This is the equivalent
-- of passing the command on the @docker run@ invocation.
--
-- @since 0.1.0.0
setCmd :: [Text] -> ContainerRequest -> ContainerRequest
setCmd newCmd req =
req {cmd = Just newCmd}
-- | The volume mounts to link to Docker container. This is the equivalent
-- of passing the command on the @docker run -v@ invocation.
setVolumeMounts :: [(Text, Text)] -> ContainerRequest -> ContainerRequest
setVolumeMounts newVolumeMounts req =
req {volumeMounts = newVolumeMounts}
-- | Wether to remove the container once exited. This is equivalent to passing
-- @--rm@ to @docker run@. (default is `True`).
--
-- @since 0.1.0.0
setRm :: Bool -> ContainerRequest -> ContainerRequest
setRm newRm req =
req {rmOnExit = newRm}
-- | Set the environment for the container. This is equivalent to passing @--env key=value@
-- to @docker run@.
--
-- @since 0.1.0.0
setEnv :: [(Text, Text)] -> ContainerRequest -> ContainerRequest
setEnv newEnv req =
req {env = newEnv}
-- | Sets the working directory inside the container.
--
-- @since x.x.x
withWorkingDirectory :: Text -> ContainerRequest -> ContainerRequest
withWorkingDirectory workdir request =
request {workDirectory = Just workdir}
-- | Set the network the container will connect to. This is equivalent to passing
-- @--network network_name@ to @docker run@.
--
-- @since 0.5.0.0
withNetwork :: Network -> ContainerRequest -> ContainerRequest
withNetwork network req =
req {network = Just (Left network)}
-- | Set the network alias for this container. This is equivalent to passing
-- @--network-alias alias@ to @docker run@. 'withNetworkAlias' can be used more
-- than once on a 'ContainerRequest'.
--
-- @since 0.5.0.0
withNetworkAlias :: Text -> ContainerRequest -> ContainerRequest
withNetworkAlias alias req@ContainerRequest{networkAlias} =
req {networkAlias = alias : networkAlias }
-- | Sets labels for a container
--
-- @since 0.5.0.0
withLabels :: [(Text, Text)] -> ContainerRequest -> ContainerRequest
withLabels xs request =
request {labels = xs}
-- | Set link on the container. This is equivalent to passing @--link other_container@
-- to @docker run@.
--
-- @since 0.1.0.0
setLink :: [ContainerId] -> ContainerRequest -> ContainerRequest
setLink newLink req =
req {links = newLink}
-- | Forwards container logs to the given 'LogConsumer' once ran.
--
-- @since 0.5.0.0
withFollowLogs :: LogConsumer -> ContainerRequest -> ContainerRequest
withFollowLogs logConsumer request =
request {followLogs = Just logConsumer}
-- | Defintion of a 'Port'. Allows for specifying ports using various protocols. Due to the
-- 'Num' and 'IsString' instance allows for convenient Haskell literals.
--
-- >>> "80" :: Port
-- 80/tcp
--
-- >>> "80/tcp" :: Port
-- 80/tcp
--
-- >>> 80 :: Port
-- 80/tcp
--
-- >>> "90/udp" :: Port
-- 90/udp
data Port = Port
{ port :: Int,
protocol :: Text
}
deriving stock (Eq, Ord)
defaultProtocol :: Text
defaultProtocol = "tcp"
-- @since 0.5.0.0
instance Show Port where
show Port {port, protocol} =
show port <> "/" <> unpack protocol
-- | A cursed but handy instance supporting literal 'Port's.
--
-- @since 0.5.0.0
instance Num Port where
fromInteger x =
Port {port = fromIntegral x, protocol = defaultProtocol}
(+) = Prelude.error "not implemented"
(*) = Prelude.error "not implemented"
abs = Prelude.error "not implemented"
signum = Prelude.error "not implemented"
negate = Prelude.error "not implemented"
-- | A cursed but handy instance supporting literal 'Port's of them
-- form @"8080"@, @"8080/udp"@, @"8080/tcp"@.
--
-- @since 0.5.0.0
instance IsString Port where
fromString input = case splitOn "/" (pack input) of
[numberish]
| Right (port, "") <- decimal numberish ->
Port {port, protocol = defaultProtocol}
[numberish, protocol]
| Right (port, "") <- decimal numberish ->
Port {port, protocol}
_ ->
Prelude.error ("invalid port literal: " <> input)
-- | Set exposed ports on the container. This is equivalent to setting @--publish $PORT@ to
-- @docker run@. Docker assigns a random port for the host port. You will have to use `containerIp`
-- and `containerPort` to connect to the published port.
--
-- @
-- container <- `run` $ `containerRequest` `redis` & `setExpose` [ 6379 ]
-- let (redisHost, redisPort) = (`containerIp` container, `containerPort` container 6379)
-- print (redisHost, redisPort)
-- @
--
-- @since 0.1.0.0
setExpose :: [Port] -> ContainerRequest -> ContainerRequest
setExpose newExpose req =
req {exposedPorts = newExpose}
-- | Set the waiting strategy on the container. Depending on a Docker container
-- it can take some time until the provided service is ready. You will want to
-- use to `setWaitingFor` to block until the container is ready to use.
--
-- @since 0.1.0.0
setWaitingFor :: WaitUntilReady -> ContainerRequest -> ContainerRequest
setWaitingFor newWaitingFor req =
req {readiness = newWaitingFor}
-- | Runs a Docker container from an `Image` and `ContainerRequest`. A finalizer
-- is registered so that the container is aways stopped when it goes out of scope.
-- This function is essentially @docker run@.
--
-- @since 0.1.0.0
run :: ContainerRequest -> TestContainer Container
run request = do
let ContainerRequest
{ toImage,
naming,
cmd,
env,
exposedPorts,
volumeMounts,
network,
networkAlias,
links,
rmOnExit,
readiness,
labels,
noReaper,
followLogs,
workDirectory
} = request
config@Config {configTracer, configCreateReaper} <-
ask
additionalLabels <-
if noReaper
then do
pure []
else reaperLabels <$> configCreateReaper
image@Image {tag} <- runToImage toImage
name <-
case naming of
RandomName -> return Nothing
FixedName n -> return $ Just n
SuffixedName prefix ->
Just . (prefix <>) . ("-" <>) . pack
<$> replicateM 6 (Random.randomRIO ('a', 'z'))
let dockerRun :: [Text]
dockerRun =
concat $
[["run"]]
++ [["--detach"]]
++ [["--name", containerName] | Just containerName <- [name]]
++ [["--label", label <> "=" <> value] | (label, value) <- additionalLabels ++ labels]
++ [["--env", variable <> "=" <> value] | (variable, value) <- env]
++ [["--publish", pack (show port) <> "/" <> protocol] | Port {port, protocol} <- exposedPorts]
++ [["--network", networkName] | Just (Right networkName) <- [network]]
++ [["--network", networkId dockerNetwork] | Just (Left dockerNetwork) <- [network]]
++ [["--network-alias", alias] | alias <- networkAlias]
++ [["--link", container] | container <- links]
++ [["--volume", src <> ":" <> dest] | (src, dest) <- volumeMounts]
++ [["--rm"] | rmOnExit]
++ [["--workdir", workdir] | Just workdir <- [workDirectory]]
++ [[tag]]
++ [command | Just command <- [cmd]]
stdout <- docker configTracer dockerRun
let id :: ContainerId
!id =
-- N.B. Force to not leak STDOUT String
strip (pack stdout)
-- Careful, this is really meant to be lazy
~inspectOutput =
unsafePerformIO $
internalInspect configTracer id
-- We don't issue 'ReleaseKeys' for cleanup anymore. Ryuk takes care of cleanup
-- for us once the session has been closed.
releaseKey <- register (pure ())
forM_ followLogs $
dockerFollowLogs configTracer id
let container =
Container
{ id,
releaseKey,
image,
inspectOutput,
config
}
-- Last but not least, execute the WaitUntilReady checks
waitUntilReady container readiness
pure container
-- | Sets up a Ryuk 'Reaper'.
--
-- @since 0.5.0.0
createRyukReaper :: TestContainer Reaper
createRyukReaper = do
ryukContainer <-
run $
containerRequest (fromTag ryukImageTag)
& skipReaper
& setVolumeMounts [("/var/run/docker.sock", "/var/run/docker.sock")]
& setExpose [ryukPort]
& setWaitingFor (waitUntilMappedPortReachable ryukPort)
& setRm True
let (ryukContainerAddress, ryukContainerPort) =
containerAddress ryukContainer ryukPort
newRyukReaper ryukContainerAddress ryukContainerPort
-- | Internal attribute, serving as a loop breaker: When runnign a container
-- we ensure a 'Reaper' is present, since the 'Reaper' itself is a running
-- container we need to break the loop to avoid spinning up a new 'Reaper' for
-- the 'Reaper'.
skipReaper :: ContainerRequest -> ContainerRequest
skipReaper request =
request {noReaper = True}
-- | Kills a Docker container. `kill` is essentially @docker kill@.
--
-- @since 0.1.0.0
kill :: Container -> TestContainer ()
kill Container {id} = do
tracer <- askTracer
_ <- docker tracer ["kill", id]
return ()
-- | Stops a Docker container. `stop` is essentially @docker stop@.
--
-- @since 0.1.0.0
stop :: Container -> TestContainer ()
stop Container {id} = do
tracer <- askTracer
_ <- docker tracer ["stop", id]
return ()
-- | Remove a Docker container. `rm` is essentially @docker rm -f@
--
-- @since 0.1.0.0
rm :: Container -> TestContainer ()
rm Container {id} = do
tracer <- askTracer
_ <- docker tracer ["rm", "-f", "-v", id]
return ()
-- | Access STDOUT and STDERR of a running Docker container. This is essentially
-- @docker logs@ under the hood.
--
-- @since 0.1.0.0
withLogs :: Container -> (Handle -> Handle -> TestContainer a) -> TestContainer a
withLogs Container {id} logger = do
let acquire :: TestContainer (Handle, Handle, Handle, Process.ProcessHandle)
acquire =
liftIO $
Process.runInteractiveProcess
"docker"
["logs", "--follow", unpack id]
Nothing
Nothing
release :: (Handle, Handle, Handle, Process.ProcessHandle) -> TestContainer ()
release (stdin, stdout, stderr, handle) =
liftIO $
Process.cleanupProcess
(Just stdin, Just stdout, Just stderr, handle)
bracket acquire release $ \(stdin, stdout, stderr, _handle) -> do
-- No need to keep it around...
liftIO $ hClose stdin
logger stdout stderr
-- | A tag to a Docker image.
--
-- @since 0.1.0.0
type ImageTag = Text
-- | A description of how to build an `Image`.
--
-- @since 0.1.0.0
data ToImage = ToImage
{ runToImage :: TestContainer Image
}
-- | Build the `Image` referred to by the argument. If the construction of the
-- image is expensive (e.g. a call to `fromBuildContext`) we don't want to
-- repeatedly build the image. Instead, `build` can be used to execute the
-- underlying Docker build once and re-use the resulting `Image`.
--
-- @since 0.1.0.0
build :: ToImage -> TestContainer ToImage
build toImage = do
image <- runToImage toImage
return $
toImage
{ runToImage = pure image
}
-- | Default `ToImage`. Doesn't apply anything to to `ContainerRequests`.
--
-- @since 0.1.0.0
defaultToImage :: TestContainer Image -> ToImage
defaultToImage action =
ToImage
{ runToImage = action
}
-- | Get an `Image` from a tag.
--
-- @since 0.1.0.0
fromTag :: ImageTag -> ToImage
fromTag tag = defaultToImage $ do
tracer <- askTracer
output <- docker tracer ["pull", "--quiet", tag]
return $
Image
{ tag = strip (pack output)
}
-- | Build the image from a build path and an optional path to the
-- Dockerfile (default is Dockerfile)
--
-- @since 0.1.0.0
fromBuildContext ::
FilePath ->
Maybe FilePath ->
ToImage
fromBuildContext path mdockerfile = defaultToImage $ do
let args
| Just dockerfile <- mdockerfile =
["build", "--quiet", "--file", pack dockerfile, pack path]
| otherwise =
["build", "--quiet", pack path]
tracer <- askTracer
output <- docker tracer args
return $
Image
{ tag = strip (pack output)
}
-- | Build a contextless image only from a Dockerfile passed as `Text`.
--
-- @since 0.1.0.0
fromDockerfile ::
Text ->
ToImage
fromDockerfile dockerfile = defaultToImage $ do
tracer <- askTracer
output <- dockerWithStdin tracer ["build", "--quiet", "-"] dockerfile
return $
Image
{ tag = strip (pack output)
}
-- | A strategy that describes how to asses readiness of a `Container`. Allows
-- Users to plug in their definition of readiness.
--
-- @since 0.1.0.0
data WaitUntilReady
= -- | A blocking action that attests readiness
WaitReady
-- Check to run
(Container -> TestContainer ())
| -- | In order to keep readiness checking at bay this node
-- ensures checks are not exceeding their time share
WaitUntilTimeout
-- Timeout in seconds
Int
-- Action to watch with with timeout
WaitUntilReady
| WaitMany
-- First check
WaitUntilReady
-- Next check
WaitUntilReady
-- | @since 0.5.0.0
instance Semigroup WaitUntilReady where
(<>) = WaitMany
-- | @since 0.5.0.0
instance Monoid WaitUntilReady where
mempty = WaitReady mempty
-- | The exception thrown by `waitForLine` in case the expected log line
-- wasn't found.
--
-- @since 0.1.0.0
newtype UnexpectedEndOfPipe = UnexpectedEndOfPipe
{ -- | The id of the underlying container.
id :: ContainerId
}
deriving (Eq, Show)
instance Exception UnexpectedEndOfPipe
-- | The exception thrown by `waitUntilTimeout`.
--
-- @since 0.1.0.0
newtype TimeoutException = TimeoutException
{ -- | The id of the underlying container that was not ready in time.
id :: ContainerId
}
deriving (Eq, Show)
instance Exception TimeoutException
-- | The exception thrown by `waitForState`.
--
-- @since 0.1.0.0
newtype InvalidStateException = InvalidStateException
{ -- | The id of the underlying container that was not ready in time.
id :: ContainerId
}
deriving stock (Eq, Show)
instance Exception InvalidStateException
-- | @waitForState@ waits for a certain state of the container. If the container reaches a terminal
-- state 'InvalidStateException' will be thrown.
--
-- @since 0.5.0.0
waitForState :: (State -> Bool) -> WaitUntilReady
waitForState isReady = WaitReady $ \Container {id} -> do
let wait = do
Config {configTracer} <-
ask
inspectOutput <-
internalInspect configTracer id
let state = containerState inspectOutput
if isReady state
then pure ()
else do
case stateStatus state of
Exited ->
-- Once exited, state won't change!
throwM InvalidStateException {id}
Dead ->
-- Once dead, state won't change!
throwM InvalidStateException {id}
_ -> do
liftIO (threadDelay 500000)
wait
wait
-- | @successfulExit@ is supposed to be used in conjunction with 'waitForState'.
--
-- @since 0.5.0.0
successfulExit :: State -> Bool
successfulExit state =
stateStatus state == Exited && stateExitCode state == Just 0
-- | @waitUntilTimeout n waitUntilReady@ waits @n@ seconds for the container
-- to be ready. If the container is not ready by then a `TimeoutException` will
-- be thrown.
--
-- @since 0.1.0.0
waitUntilTimeout :: Int -> WaitUntilReady -> WaitUntilReady
waitUntilTimeout = WaitUntilTimeout
-- | Waits for a specific http status code.
-- This combinator should always be used with `waitUntilTimeout`.
--
-- @since 0.5.0.0
waitForHttp ::
-- | Port
Port ->
-- | URL path
String ->
-- | Acceptable status codes
[Int] ->
WaitUntilReady
waitForHttp port path acceptableStatusCodes = WaitReady $ \container -> do
Config {configTracer} <- ask
let wait :: (MonadIO m, MonadCatch m) => m ()
wait =
liftIO (newManager defaultManagerSettings) >>= retry
retry :: (MonadIO m, MonadCatch m) => Manager -> m ()
retry manager = do
let (endpointHost, endpointPort) =
containerAddress container port
let request =
defaultRequest
{ host = encodeUtf8 endpointHost,
port = endpointPort,
path = encodeUtf8 (pack path)
}
result <-
try $
statusCode . responseStatus <$> liftIO (httpNoBody request manager)
case result of
Right code -> do
withTrace
configTracer
(TraceHttpCall endpointHost endpointPort (Right code))
unless (code `elem` acceptableStatusCodes) $
retry manager
Left (exception :: HttpException) -> do
withTrace
configTracer
(TraceHttpCall endpointHost endpointPort (Left $ show exception))
liftIO (threadDelay 500000)
retry manager
wait
-- | Waits until the port of a container is ready to accept connections.
-- This combinator should always be used with `waitUntilTimeout`.
--
-- @since 0.1.0.0
waitUntilMappedPortReachable ::
Port ->
WaitUntilReady
waitUntilMappedPortReachable port = WaitReady $ \container -> do
withFrozenCallStack $ do
Config {configTracer} <- ask
let resolve endpointHost endpointPort = do
let hints = Socket.defaultHints {Socket.addrSocketType = Socket.Stream}
head <$> Socket.getAddrInfo (Just hints) (Just endpointHost) (Just (show endpointPort))
open addr = do
socket <-
Socket.socket
(Socket.addrFamily addr)
(Socket.addrSocketType addr)
(Socket.addrProtocol addr)
Socket.connect
socket
(Socket.addrAddress addr)
pure socket
wait = do
let (endpointHost, endpointPort) =
containerAddress container port
result <- try (resolve (unpack endpointHost) endpointPort >>= open)
case result of
Right socket -> do
withTrace configTracer (TraceOpenSocket endpointHost endpointPort Nothing)
Socket.close socket
pure ()
Left (exception :: IOException) -> do
withTrace
configTracer
(TraceOpenSocket endpointHost endpointPort (Just exception))
threadDelay 500000
wait
liftIO wait
-- | A low-level primitive that allows scanning the logs for specific log lines
-- that indicate readiness of a container.
--
-- The `Handle`s passed to the function argument represent @stdout@ and @stderr@
-- of the container.
--
-- @since 0.1.0.0
waitWithLogs :: (Container -> Handle -> Handle -> IO ()) -> WaitUntilReady
waitWithLogs waiter = WaitReady $ \container ->
withLogs container $ \stdout stderr ->
liftIO $ waiter container stdout stderr
-- | Waits for a specific line to occur in the logs. Throws a `UnexpectedEndOfPipe`
-- exception in case the desired line can not be found on the logs.
--
-- Say you want to find "Ready to accept connections" in the logs on Stdout try:
--
-- @
-- waitForLogLine Stdout ("Ready to accept connections" ``LazyText.isInfixOf``)
-- @
--
-- @since 0.1.0.0
waitForLogLine :: Pipe -> (LazyText.Text -> Bool) -> WaitUntilReady
waitForLogLine whereToLook matches = waitWithLogs $ \Container {id} stdout stderr -> do
let logs :: Handle
logs = case whereToLook of
Stdout -> stdout
Stderr -> stderr
logContent <- LazyByteString.hGetContents logs
let logLines :: [LazyText.Text]
logLines =
-- FIXME: This is assuming UTF8 encoding. Do better!
map
(LazyText.decodeUtf8With lenientDecode)
(LazyByteString.lines logContent)