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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
//! Container API: run docker containers and manage their lifecycle

use arrayvec::ArrayVec;
use chrono::serde::ts_seconds;
use chrono::{DateTime, Utc};
use failure::Error;
use futures::{stream, Stream};
use http::request::Builder;
use hyper::client::connect::Connect;
use hyper::rt::Future;
use hyper::{Body, Method};
use serde::Serialize;
use serde_json;

use std::cmp::Eq;
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;

use super::{Docker, DockerChain};
use docker::{FALSE_STR, TRUE_STR};
use either::EitherStream;

/// Parameters used in the [List Container API](../struct.Docker.html#method.list_containers)
///
/// ## Examples
///
/// ```rust
/// use bollard::container::ListContainersOptions;
///
/// use std::collections::HashMap;
/// use std::default::Default;
///
/// let mut filters = HashMap::new();
/// filters.insert("health", vec!("unhealthy"));
///
/// ListContainersOptions{
///     all: true,
///     filters: filters,
///     ..Default::default()
/// };
/// ```
///
/// ```rust
/// # use bollard::container::ListContainersOptions;
/// # use std::default::Default;
/// ListContainersOptions::<String>{
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct ListContainersOptions<T>
where
    T: AsRef<str> + Eq + Hash,
{
    /// Return all containers. By default, only running containers are shown
    pub all: bool,
    /// Return this number of most recently created containers, including non-running ones
    pub limit: Option<isize>,
    /// Return the size of container as fields `SizeRw` and `SizeRootFs`
    pub size: bool,
    /// Filters to process on the container list, encoded as JSON. Available filters:
    ///  - `ancestor`=`(<image-name>[:<tag>]`, `<image id>`, or `<image@digest>`)
    ///  - `before`=(`<container id>` or `<container name>`)
    ///  - `expose`=(`<port>[/<proto>]`|`<startport-endport>`/`[<proto>]`)
    ///  - `exited`=`<int>` containers with exit code of `<int>`
    ///  - `health`=(`starting`|`healthy`|`unhealthy`|`none`)
    ///  - `id`=`<ID>` a container's ID
    ///  - `isolation`=(`default`|`process`|`hyperv`) (Windows daemon only)
    ///  - `is-task`=`(true`|`false`)
    ///  - `label`=`key` or `label`=`"key=value"` of a container label
    ///  - `name`=`<name>` a container's name
    ///  - `network`=(`<network id>` or `<network name>`)
    ///  - `publish`=(`<port>[/<proto>]`|`<startport-endport>`/`[<proto>]`)
    ///  - `since`=(`<container id>` or `<container name>`)
    ///  - `status`=(`created`|`restarting`|`running`|`removing`|`paused`|`exited`|`dead`)
    ///  - `volume`=(`<volume name>` or `<mount point destination>`)
    pub filters: HashMap<T, Vec<T>>,
}

#[allow(missing_docs)]
/// Trait providing implementations for [List Containers Options](struct.ListContainersOptions.html)
/// struct.
pub trait ListContainersQueryParams<K, V>
where
    K: AsRef<str>,
    V: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, V); 4]>, Error>;
}

impl<'a, T: AsRef<str> + ::std::cmp::Eq + ::std::hash::Hash>
    ListContainersQueryParams<&'a str, String> for ListContainersOptions<T>
where
    T: ::serde::Serialize,
{
    fn into_array(self) -> Result<ArrayVec<[(&'a str, String); 4]>, Error> {
        Ok(ArrayVec::from([
            ("all", self.all.to_string()),
            (
                "limit",
                self.limit
                    .map(|l| l.to_string())
                    .unwrap_or_else(|| String::new()),
            ),
            ("size", self.size.to_string()),
            ("filters", serde_json::to_string(&self.filters)?),
        ]))
    }
}

/// Parameters used in the [Create Container API](../struct.Docker.html#method.create_container)
///
/// ## Examples
///
/// ```rust
/// use bollard::container::CreateContainerOptions;
///
/// CreateContainerOptions{
///     name: "my-new-container",
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct CreateContainerOptions<T>
where
    T: AsRef<str>,
{
    /// Assign the specified name to the container.
    pub name: T,
}

/// Trait providing implementations for [Create Container Options](struct.CreateContainerOptions.html)
/// struct.
#[allow(missing_docs)]
pub trait CreateContainerQueryParams<K, V>
where
    K: AsRef<str>,
    V: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, V); 1]>, Error>;
}

impl<'a, T: AsRef<str>> CreateContainerQueryParams<&'a str, T> for CreateContainerOptions<T> {
    fn into_array(self) -> Result<ArrayVec<[(&'a str, T); 1]>, Error> {
        Ok(ArrayVec::from([("name", self.name)]))
    }
}

/// Container configuration that depends on the host we are running on
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct HostConfig<T>
where
    T: AsRef<str> + Eq + Hash,
{
    /// A list of volume bindings for this container. Each volume binding is a string in one of these forms:
    /// - `host-src:container-dest` to bind-mount a host path into the container. Both `host-src`, and `container-dest` must be an *absolute* path.
    /// - `host-src:container-dest:ro` to make the bind mount read-only inside the container. Both `host-src`, and `container-dest` must be an *absolute* path.
    /// - `volume-name:container-dest` to bind-mount a volume managed by a volume driver into the container. `container-dest` must be an *absolute* path.
    /// - `volume-name:container-dest:ro` to mount the volume read-only inside the container. `container-dest` must be an *absolute* path.
    pub binds: Option<Vec<T>>,
    /// A list of links for the container in the form `container_name:alias`.
    pub links: Option<Vec<T>>,
    /// Memory limit in bytes.
    pub memory: Option<u64>,
    /// Total memory limit (memory + swap). Set as `-1` to enable unlimited swap.
    pub memory_swap: Option<i64>,
    /// Memory soft limit in bytes.
    pub memory_reservation: Option<u64>,
    /// Kernel memory limit in bytes.
    pub kernel_memory: Option<u64>,
    /// CPU quota in units of 10<sup>-9</sup> CPUs.
    pub nano_cpus: Option<u64>,
    pub cpu_percent: Option<u64>,
    /// An integer value representing this container's relative CPU weight versus other containers.
    pub cpu_shares: Option<u64>,
    /// The length of a CPU period in microseconds.
    pub cpu_period: Option<u64>,
    /// The length of a CPU real-time period in microseconds. Set to 0 to allocate no time allocated to real-time tasks.
    pub cpu_realtime_period: Option<u64>,
    /// The length of a CPU real-time runtime in microseconds. Set to 0 to allocate no time allocated to real-time tasks.
    pub cpu_realtime_runtime: Option<u64>,
    /// Microseconds of CPU time that the container can get in a CPU period.
    pub cpu_quota: Option<u64>,
    /// CPUs in which to allow execution (e.g., `0-3`, `0,1`)
    pub cpuset_cpus: Option<T>,
    /// Memory nodes (MEMs) in which to allow execution (`0-3`, `0,1`). Only effective on NUMA systems.
    pub cpuset_mems: Option<T>,
    /// Block IO weight (relative weight).
    pub blkio_weight: Option<u64>,
    /// Block IO weight (relative device weight).
    pub blkio_weight_device: Option<Vec<HashMap<T, T>>>,
    /// Limit read rate (bytes per second) from a device.
    pub blkio_device_read_bps: Option<Vec<HashMap<T, T>>>,
    /// Limit write rate (bytes per second) to a device.
    pub blkio_device_write_bps: Option<Vec<HashMap<T, T>>>,
    /// Limit read rate (IO per second) from a device.
    #[serde(rename = "BlkioDeviceReadIOps")]
    pub blkio_device_read_iops: Option<Vec<HashMap<T, T>>>,
    /// Limit write rate (IO per second) to a device.
    #[serde(rename = "BlkioDeviceWriteIOps")]
    pub blkio_device_write_iops: Option<Vec<HashMap<T, T>>>,
    /// Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100.
    pub memory_swappiness: Option<u64>,
    /// Disable OOM Killer for the container.
    pub oom_kill_disable: Option<bool>,
    /// An integer value containing the score given to the container in order to tune OOM killer
    /// preferences.
    pub oom_score_adj: Option<isize>,
    /// Set the PID (Process) Namespace mode for the container. It can be either:
    /// - `"container:<name|id>"`: joins another container's PID namespace
    /// - `"host"`: use the host's PID namespace inside the container
    pub pid_mode: Option<String>,
    /// Tune a container's pids limit. Set `-1` for unlimited.
    pub pids_limit: Option<u64>,
    /// PortMap describes the mapping of container ports to host ports, using the container's
    /// port-number and protocol as key in the format `<port>/<protocol`>, for example, `80/udp`.  If a
    /// container's port is mapped for multiple protocols, separate entries are added to the
    /// mapping table.
    pub port_bindings: Option<HashMap<T, Vec<PortBinding<T>>>>,
    /// Allocates an ephemeral host port for all of a container's exposed ports.
    /// Ports are de-allocated when the container stops and allocated when the container starts.
    /// The allocated port might be changed when restarting the container.  
    /// The port is selected from the ephemeral port range that depends on the kernel. For example,
    /// on Linux the range is defined by `/proc/sys/net/ipv4/ip_local_port_range`.
    pub publish_all_ports: Option<bool>,
    /// Gives the container full access to the host.
    pub privileged: Option<bool>,
    /// Mount the container's root filesystem as read only.
    pub readonly_rootfs: Option<bool>,
    /// A list of DNS servers for the container to use.
    pub dns: Option<Vec<T>>,
    /// A list of DNS options.
    pub dns_options: Option<Vec<T>>,
    /// A list of DNS search domains.
    pub dns_search: Option<Vec<T>>,
    /// A list of volumes to inherit from another container, specified in the form `<container
    /// name>[:<ro|rw>]`.
    pub volumes_from: Option<Vec<T>>,
    /// A list of kernel capabilities to add to the container.
    pub cap_add: Option<Vec<T>>,
    /// A list of kernel capabilities to drop from the container.
    pub cap_drop: Option<Vec<T>>,
    pub group_add: Option<Vec<T>>,
    /// The behavior to apply when the container exits. The default is not to restart.
    /// An ever increasing delay (double the previous delay, starting at 100ms) is added before
    /// each restart to prevent flooding the server.
    pub restart_policy: Option<RestartPolicy<T>>,
    /// Automatically remove the container when the container's process exits. This has no effect
    /// if `RestartPolicy` is set.
    pub auto_remove: Option<bool>,
    /// Network mode to use for this container. Supported standard values are: `bridge`, `host`,
    /// `none`, and `container:<name|id>`. Any other value is taken as a custom network's name to
    /// which this container should connect to.
    pub network_mode: Option<T>,
    pub devices: Option<Vec<T>>,
    /// A list of resource limits to set in the container. For example: `{"Name": "nofile", "Soft":
    /// 1024, "Hard": 2048}`
    pub ulimits: Option<Vec<HashMap<T, T>>>,
    /// The logging configuration for this container.
    pub log_config: Option<LogConfig>,
    /// A list of string values to customize labels for MLS systems, such as SELinux.
    pub security_opt: Option<Vec<T>>,
    /// Path to `cgroups` under which the container's `cgroup` is created. If the path is not absolute,
    /// the path is considered to be relative to the `cgroups` path of the init process. Cgroups are
    /// created if they do not already exist.
    pub cgroup_parent: Option<T>,
    /// Driver that this container uses to mount volumes.
    pub volume_driver: Option<T>,
    /// Size of `/dev/shm` in bytes. If omitted, the system uses 64MB.
    pub shm_size: Option<u64>,
    /// Path to a file where the container ID is written.
    #[serde(rename = "ContainerIDFile")]
    pub container_id_file: Option<String>,
    /// A list of hostnames/IP mappings to add to the container's `/etc/hosts` file. Specified in
    /// the form `["hostname:IP"]`.
    pub extra_hosts: Option<Vec<T>>,
    /// IPC sharing mode for the container. Possible values are:
    ///  - `"none"`: own private IPC namespace, with /dev/shm not mounted
    ///  - `"private"`: own private IPC namespace
    ///  - `"shareable"`: own private IPC namespace, with a possibility to share it with other containers
    ///  - `"container:<name|id>"`: join another (shareable) container's IPC namespace
    ///  - `"host"`: use the host system's IPC namespace
    /// If not specified, daemon default is used, which can either be "private" or "shareable",
    /// depending on daemon version and configuration.
    pub ipc_mode: Option<T>,
    /// Cgroup to use for the container.
    pub cgroup: Option<T>,
    /// UTS namespace to use for the container.
    #[serde(rename = "UTSMode")]
    pub uts_mode: Option<T>,
    /// Sets the usernamespace mode for the container when usernamespace remapping option is enabled.
    pub userns_mode: Option<T>,
    /// Runtime to use with this container.
    pub runtime: Option<T>,
    /// Initial console size, as an [height, width] array. (Windows only)
    pub console_size: Option<Vec<isize>>,
    /// Isolation technology of the container. (Windows only)
    pub isolation: Option<T>,
    /// A list of cgroup rules to apply to the container.
    pub device_cgroup_rules: Option<Vec<T>>,
    /// Disk limit (in bytes).
    pub disk_quota: Option<u64>,
    /// The usable percentage of the available CPUs (Windows only).
    /// On Windows Server containers, the processor resource controls are mutually exclusive. The
    /// order of precedence is `CPUCount` first, then `CPUShares`, and `CPUPercent` last.
    pub cpu_count: Option<u64>,
    /// Maximum IOps for the container system drive (Windows only).
    #[serde(rename = "IOMaximumIOps")]
    pub io_maximum_iops: Option<u64>,
    /// Maximum IO in bytes per second for the container system drive (Windows only).
    #[serde(rename = "IOMaximumBandwidth")]
    pub io_maximum_bandwidth: Option<u64>,
    pub masked_paths: Option<Vec<T>>,
    pub readonly_paths: Option<Vec<T>>,
}

/// Storage driver name and configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct GraphDriver {
    pub name: String,
    pub data: Option<HashMap<String, String>>,
}

/// Describes the mapping of container ports to host ports, using the container's
/// port-number and protocol as key in the format `<port>/<protocol>`, for example, `80/udp`.  If a
/// container's port is mapped for multiple protocols, separate entries are added to the mapping
/// table.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct PortBinding<T>
where
    T: AsRef<str>,
{
    #[serde(rename = "HostIp")]
    pub host_ip: T,
    pub host_port: T,
}

/// The behavior to apply when the container exits. The default is not to restart.  An ever
/// increasing delay (double the previous delay, starting at 100ms) is added before each restart to
/// prevent flooding the server.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct RestartPolicy<T>
where
    T: AsRef<str>,
{
    pub name: Option<T>,
    pub maximum_retry_count: Option<isize>,
}

/// The logging configuration for this container.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct LogConfig {
    #[serde(rename = "Type")]
    pub type_: Option<String>,
    pub config: Option<HashMap<String, String>>,
}

/// This container's networking configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(missing_docs)]
pub struct NetworkingConfig {
    pub endpoints_config: HashMap<String, ContainerNetwork>,
}

/// EndpointIPAMConfig represents an endpoint's IPAM configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(missing_docs)]
pub struct EndpointIPAMConfig {
    #[serde(rename = "IPV4Address")]
    pub ipv4_address: String,
    #[serde(rename = "IPV6Address")]
    pub ipv6_address: String,
}

/// Configuration for a network endpoint.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct ContainerNetwork {
    #[serde(rename = "IPAMConfig")]
    pub ipam_config: Option<EndpointIPAMConfig>,
    pub links: Option<Vec<String>>,
    pub aliases: Option<Vec<String>>,
    pub mac_address: String,
    #[serde(rename = "GlobalIPv6Address")]
    pub global_ipv6_address: String,
    #[serde(rename = "GlobalIPv6PrefixLen")]
    pub global_ipv6_prefix_len: isize,
    #[serde(rename = "IPv6Gateway")]
    pub ipv6_gateway: String,
    #[serde(rename = "IPAddress")]
    pub ip_address: String,
    #[serde(rename = "IPPrefixLen")]
    pub ip_prefix_len: i64,
    pub gateway: String,
    #[serde(rename = "EndpointID")]
    pub endpoint_id: String,
    #[serde(rename = "NetworkID")]
    pub network_id: String,
    pub driver_opts: Option<HashMap<String, String>>,
}

/// Network Settings for a container.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct NetworkSettings {
    pub networks: HashMap<String, ContainerNetwork>,
    #[serde(rename = "IPAddress")]
    pub ip_address: String,
    #[serde(rename = "IPPrefixLen")]
    pub ip_prefix_len: isize,
    pub mac_address: String,
    pub gateway: String,
    pub bridge: String,
    #[serde(rename = "EndpointID")]
    pub endpoint_id: String,
    pub sandbox_key: String,
    #[serde(rename = "GlobalIPv6Address")]
    pub global_ipv6_address: String,
    #[serde(rename = "GlobalIPv6PrefixLen")]
    pub global_ipv6_prefix_len: isize,
    #[serde(rename = "IPv6Gateway")]
    pub ipv6_gateway: String,
    #[serde(rename = "LinkLocalIPv6Address")]
    pub link_local_ipv6_address: String,
    #[serde(rename = "LinkLocalIPv6PrefixLen")]
    pub link_local_ipv6_prefix_len: isize,
    #[serde(rename = "SecondaryIPAddresses")]
    pub secondary_ip_addresses: Option<Vec<String>>,
    #[serde(rename = "SecondaryIPv6Addresses")]
    pub secondary_ipv6_addresses: Option<Vec<String>>,
    #[serde(rename = "SandboxID")]
    pub sandbox_id: String,
    pub hairpin_mode: bool,
    pub ports: HashMap<String, Option<Vec<PortBinding<String>>>>,
}

/// Specification for mounts to be added to the container.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct Mount {
    pub name: Option<String>,
    pub source: String,
    pub destination: String,
    pub driver: Option<String>,
    pub mode: String,
    #[serde(rename = "RW")]
    pub rw: bool,
    #[serde(rename = "Type")]
    pub type_: String,
    pub propagation: String,
}

/// Runtime status of the container.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct State {
    pub status: String,
    pub running: bool,
    pub paused: bool,
    pub restarting: bool,
    #[serde(rename = "OOMKilled")]
    pub oomkilled: bool,
    pub dead: bool,
    pub pid: isize,
    pub exit_code: u16,
    pub error: String,
    pub started_at: DateTime<Utc>,
    pub finished_at: DateTime<Utc>,
}

/// Maps internal container port to external host port.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct APIPort {
    #[serde(rename = "IP")]
    pub ip: Option<String>,
    pub private_port: i64,
    pub public_port: Option<i64>,
    #[serde(rename = "Type")]
    pub type_: String,
}

/// A mapping of network name to endpoint configuration for that network.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct NetworkList {
    pub networks: HashMap<String, ContainerNetwork>,
}

/// Result type for the [List Containers API](../struct.Docker.html#method.list_containers)
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct APIContainers {
    pub id: String,
    pub names: Vec<String>,
    pub image: String,
    #[serde(rename = "ImageID")]
    pub image_id: String,
    pub command: String,
    #[serde(with = "ts_seconds")]
    pub created: DateTime<Utc>,
    pub state: String,
    pub status: String,
    pub ports: Vec<APIPort>,
    pub labels: HashMap<String, String>,
    pub size_rw: Option<i64>,
    pub size_root_fs: Option<i64>,
    pub mounts: Vec<Mount>,
    pub network_settings: NetworkList,
    pub host_config: HostConfig<String>,
}

/// Result type for the [Inspect Container API](../struct.Docker.html#method.inspect_container)
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct Container {
    pub id: String,
    pub created: DateTime<Utc>,
    pub path: String,
    pub args: Vec<String>,
    pub config: Config<String>,
    pub state: State,
    pub image: String,
    pub network_settings: NetworkSettings,
    pub resolv_conf_path: String,
    pub hostname_path: String,
    pub hosts_path: String,
    pub log_path: String,
    pub name: String,
    pub driver: String,
    pub mounts: Vec<Mount>,
    pub host_config: HostConfig<String>,
    pub restart_count: isize,
    pub platform: String,
    pub mount_label: String,
    pub process_label: String,
    pub app_armor_profile: String,
    #[serde(rename = "ExecIDs")]
    pub exec_ids: Option<Vec<String>>,
    pub graph_driver: GraphDriver,
}

/// Container to create.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
pub struct Config<T>
where
    T: AsRef<str> + Eq + Hash,
{
    /// The hostname to use for the container, as a valid RFC 1123 hostname.
    pub hostname: Option<T>,
    /// The domain name to use for the container.
    pub domainname: Option<T>,
    /// The user that commands are run as inside the container.
    pub user: Option<T>,
    /// Whether to attach to `stdin`.
    pub attach_stdin: Option<bool>,
    /// Whether to attach to `stdout`.
    pub attach_stdout: Option<bool>,
    /// Whether to attach to `stderr`.
    pub attach_stderr: Option<bool>,
    /// Command is already escaped (Windows only).
    pub args_escaped: Option<bool>,
    /// Attach standard streams to a TTY, including `stdin` if it is not closed.
    pub tty: Option<bool>,
    /// Open `stdin`.
    pub open_stdin: Option<bool>,
    /// Close stdin after one attached client disconnects.
    pub stdin_once: Option<bool>,
    /// A list of environment variables to set inside the container in the form `["VAR=value", ...]`.
    /// A variable without `=` is removed from the environment, rather than to have an empty value.
    pub env: Option<Vec<T>>,
    /// Command to run specified as a string or an array of strings.
    pub cmd: Option<Vec<T>>,
    /// The entry point for the container as a string or an array of strings.
    ///
    /// If the array consists of exactly one empty string (`[""]`) then the entry point is reset to
    /// system default (i.e., the entry point used by docker when there is no `ENTRYPOINT`
    /// instruction in the `Dockerfile`).
    pub entrypoint: Option<Vec<T>>,
    /// The name of the image to use when creating the container.
    pub image: Option<T>,
    /// User-defined key/value metadata.
    pub labels: Option<HashMap<T, T>>,
    /// An object mapping mount point paths inside the container to empty objects.
    pub volumes: Option<HashMap<T, HashMap<(), ()>>>,
    /// The working directory for commands to run in.
    pub working_dir: Option<T>,
    /// Disable networking for the container.
    pub network_disabled: Option<bool>,
    /// `ONBUILD` metadata that were defined in the image's `Dockerfile`.
    pub on_build: Option<Vec<T>>,
    /// MAC address of the container.
    pub mac_address: Option<T>,
    /// An object mapping ports to an empty object in the form:
    /// `{"<port>/<tcp|udp|sctp>": {}}`
    pub exposed_ports: Option<HashMap<T, HashMap<(), ()>>>,
    /// Signal to stop a container as a string or unsigned integer.
    pub stop_signal: Option<T>,
    /// Timeout to stop a container in seconds.
    pub stop_timeout: Option<isize>,
    /// Container configuration that depends on the host we are running on.
    pub host_config: Option<HostConfig<T>>,
    /// This container's networking configuration.
    pub networking_config: Option<NetworkingConfig>,
}

/// Result type for the [Create Container API](../struct.Docker.html#method.create_container)
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct CreateContainerResults {
    pub id: String,
    pub warnings: Option<Vec<String>>,
}

/// Parameters used in the [Stop Container API](../struct.Docker.html#method.stop_container)
///
/// ## Examples
///
/// use bollard::container::StopContainerOptions;
///
/// StopContainerOptions{
///     t: 30,
/// };
#[derive(Debug, Copy, Clone, Default)]
pub struct StopContainerOptions {
    /// Number of seconds to wait before killing the container
    pub t: i64,
}

/// Trait providing implementations for [Stop Container Options](struct.StopContainerOptions.html).
#[allow(missing_docs)]
pub trait StopContainerQueryParams<K>
where
    K: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, String); 1]>, Error>;
}

impl<'a> StopContainerQueryParams<&'a str> for StopContainerOptions {
    fn into_array(self) -> Result<ArrayVec<[(&'a str, String); 1]>, Error> {
        Ok(ArrayVec::from([("t", self.t.to_string())]))
    }
}

/// Parameters used in the [Start Container API](../struct.Docker.html#method.start_container)
///
/// ## Examples
///
/// ```rust
/// use bollard::container::StartContainerOptions;
///
/// StartContainerOptions{
///     detach_keys: "ctrl-^"
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct StartContainerOptions<T>
where
    T: AsRef<str>,
{
    /// Override the key sequence for detaching a container. Format is a single character `[a-Z]` or
    /// `ctrl-<value>` where `<value>` is one of: `a-z`, `@`, `^`, `[`, `,` or `_`.
    pub detach_keys: T,
}

/// Trait providing implementations for [Start Container Options](struct.StartContainerOptions.html).
#[allow(missing_docs)]
pub trait StartContainerQueryParams<K, V>
where
    K: AsRef<str>,
    V: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, V); 1]>, Error>;
}

impl<'a, T: AsRef<str>> StartContainerQueryParams<&'a str, T> for StartContainerOptions<T> {
    fn into_array(self) -> Result<ArrayVec<[(&'a str, T); 1]>, Error> {
        Ok(ArrayVec::from([("detachKeys", self.detach_keys)]))
    }
}

/// Parameters used in the [Remove Container API](../struct.Docker.html#method.remove_container)
///
/// ## Examples
///
/// ```rust
/// use bollard::container::RemoveContainerOptions;
///
/// use std::default::Default;
///
/// RemoveContainerOptions{
///     force: true,
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Copy, Clone, Default)]
pub struct RemoveContainerOptions {
    /// Remove the volumes associated with the container.
    pub v: bool,
    /// If the container is running, kill it before removing it.
    pub force: bool,
    /// Remove the specified link associated with the container.
    pub link: bool,
}

/// Trait providing implementations for [Remove Container Options](struct.RemoveContainerOptions.html).
#[allow(missing_docs)]
pub trait RemoveContainerQueryParams<K, V>
where
    K: AsRef<str>,
    V: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, V); 3]>, Error>;
}

impl<'a> RemoveContainerQueryParams<&'a str, &'a str> for RemoveContainerOptions {
    fn into_array(self) -> Result<ArrayVec<[(&'a str, &'a str); 3]>, Error> {
        Ok(ArrayVec::from([
            ("v", if self.v { TRUE_STR } else { FALSE_STR }),
            ("force", if self.force { TRUE_STR } else { FALSE_STR }),
            ("link", if self.link { TRUE_STR } else { FALSE_STR }),
        ]))
    }
}

/// Parameters used in the [Wait Container API](../struct.Docker.html#method.wait_container)
///
/// ## Examples
///
/// ```rust
/// use bollard::container::WaitContainerOptions;
///
/// WaitContainerOptions{
///     condition: "not-running",
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct WaitContainerOptions<T>
where
    T: AsRef<str>,
{
    /// Wait until a container state reaches the given condition, either 'not-running' (default),
    /// 'next-exit', or 'removed'.
    pub condition: T,
}

/// Trait providing implementations for [Wait Container Options](struct.WaitContainerOptions.html).
#[allow(missing_docs)]
pub trait WaitContainerQueryParams<K, V>
where
    K: AsRef<str>,
    V: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, V); 1]>, Error>;
}

impl<'a, T: AsRef<str>> WaitContainerQueryParams<&'a str, T> for WaitContainerOptions<T> {
    fn into_array(self) -> Result<ArrayVec<[(&'a str, T); 1]>, Error> {
        Ok(ArrayVec::from([("condition", self.condition)]))
    }
}

/// Error messages returned in the [Wait Container API](../struct.Docker.html#method.wait_container)
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct WaitContainerResultsError {
    pub message: String,
}

/// Result type for the [Wait Container API](../struct.Docker.html#method.wait_container)
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct WaitContainerResults {
    pub status_code: u16,
    pub error: Option<WaitContainerResultsError>,
}

/// Parameters used in the [Restart Container API](../struct.Docker.html#method.restart_container)
///
/// ## Example
///
/// ```rust
/// use bollard::container::RestartContainerOptions;
///
/// RestartContainerOptions{
///     t: 30,
/// };
/// ```
#[derive(Debug, Copy, Clone, Default)]
pub struct RestartContainerOptions {
    /// Number of seconds to wait before killing the container.
    pub t: isize,
}

/// Trait providing implementations for [Restart Container Options](struct.RestartContainerOptions.html).
#[allow(missing_docs)]
pub trait RestartContainerQueryParams<K>
where
    K: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, String); 1]>, Error>;
}

impl<'a> RestartContainerQueryParams<&'a str> for RestartContainerOptions {
    fn into_array(self) -> Result<ArrayVec<[(&'a str, String); 1]>, Error> {
        Ok(ArrayVec::from([("t", self.t.to_string())]))
    }
}

/// Parameters used in the [Inspect Container API](../struct.Docker.html#method.inspect_container)
///
/// ## Examples
///
/// ```rust
/// use bollard::container::InspectContainerOptions;
///
/// InspectContainerOptions{
///     size: false,
/// };
/// ```
#[derive(Debug, Copy, Clone, Default)]
pub struct InspectContainerOptions {
    /// Return the size of container as fields `SizeRw` and `SizeRootFs`
    pub size: bool,
}

/// Trait providing implementations for [Inspect Container Options](struct.InspectContainerOptions.html).
#[allow(missing_docs)]
pub trait InspectContainerQueryParams<K, V>
where
    K: AsRef<str>,
    V: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, V); 1]>, Error>;
}

impl<'a> InspectContainerQueryParams<&'a str, &'a str> for InspectContainerOptions {
    fn into_array(self) -> Result<ArrayVec<[(&'a str, &'a str); 1]>, Error> {
        Ok(ArrayVec::from([(
            "size",
            if self.size { TRUE_STR } else { FALSE_STR },
        )]))
    }
}

/// Parameters used in the [Top Processes API](../struct.Docker.html#method.top_processes)
///
/// ## Examples
///
/// ```rust
/// use bollard::container::TopOptions;
///
/// TopOptions{
///     ps_args: "aux",
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct TopOptions<T>
where
    T: AsRef<str>,
{
    /// The arguments to pass to `ps`. For example, `aux`
    pub ps_args: T,
}

/// ## Top Query Params
///
/// Trait providing implementations for [Top Options](struct.TopOptions.html).
#[allow(missing_docs)]
pub trait TopQueryParams<K, V>
where
    K: AsRef<str>,
    V: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, V); 1]>, Error>;
}

impl<'a, T: AsRef<str>> TopQueryParams<&'a str, T> for TopOptions<T> {
    fn into_array(self) -> Result<ArrayVec<[(&'a str, T); 1]>, Error> {
        Ok(ArrayVec::from([("ps_args", self.ps_args)]))
    }
}

/// Result type for the [Top Processes API](../struct.Docker.html#method.top_processes)
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct TopResult {
    pub titles: Vec<String>,
    pub processes: Vec<Vec<String>>,
}

/// Parameters used in the [Logs API](../struct.Docker.html#method.logs)
///
/// ## Examples
///
/// ```rust
/// use bollard::container::LogsOptions;
///
/// use std::default::Default;
///
/// LogsOptions{
///     stdout: true,
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct LogsOptions {
    /// Return the logs as a finite stream.
    pub follow: bool,
    /// Return logs from `stdout`.
    pub stdout: bool,
    /// Return logs from `stderr`.
    pub stderr: bool,
    /// Only return logs since this time, as a UNIX timestamp.
    pub since: i64,
    /// Only return logs before this time, as a UNIX timestamp.
    pub until: i64,
    /// Add timestamps to every log line.
    pub timestamps: bool,
    /// Only return this number of log lines from the end of the logs. Specify as an integer or all
    /// to output `all` log lines.
    pub tail: String,
}

/// Trait providing implementations for [Logs Options](struct.LogsOptions.html).
#[allow(missing_docs)]
pub trait LogsQueryParams<K>
where
    K: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, String); 7]>, Error>;
}

impl<'a> LogsQueryParams<&'a str> for LogsOptions {
    fn into_array(self) -> Result<ArrayVec<[(&'a str, String); 7]>, Error> {
        Ok(ArrayVec::from([
            ("follow", self.follow.to_string()),
            ("stdout", self.stdout.to_string()),
            ("stderr", self.stderr.to_string()),
            ("since", self.since.to_string()),
            ("until", self.until.to_string()),
            ("timestamps", self.timestamps.to_string()),
            ("tail", self.tail),
        ]))
    }
}

/// Result type for the [Logs API](../struct.Docker.html#method.logs)
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub enum LogOutput {
    StdErr { message: String },
    StdOut { message: String },
    StdIn { message: String },
}

impl fmt::Display for LogOutput {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self {
            LogOutput::StdErr { message } => write!(f, "{}", message),
            LogOutput::StdOut { message } => write!(f, "{}", message),
            LogOutput::StdIn { message } => write!(f, "{}", message),
        }
    }
}

/// Result type for the [Container Changes API](../struct.Docker.html#method.container_changes)
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct Change {
    pub path: String,
    pub kind: isize,
}

impl fmt::Display for Change {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.kind {
            0 => write!(f, "C {}", self.path),
            1 => write!(f, "A {}", self.path),
            2 => write!(f, "D {}", self.path),
            _ => unreachable!(),
        }
    }
}

/// Parameters used in the [Stats API](../struct.Docker.html#method.stats)
///
/// ## Examples
///
/// ```rust
/// use bollard::container::StatsOptions;
///
/// StatsOptions{
///     stream: false,
/// };
/// ```
#[derive(Debug, Copy, Clone, Default)]
pub struct StatsOptions {
    /// Stream the output. If false, the stats will be output once and then it will disconnect.
    pub stream: bool,
}

/// Trait providing implementations for [Stats Options](struct.StatsOptions.html).
#[allow(missing_docs)]
pub trait StatsQueryParams<K, V>
where
    K: AsRef<str>,
    V: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, V); 1]>, Error>;
}

impl<'a> StatsQueryParams<&'a str, &'a str> for StatsOptions {
    fn into_array(self) -> Result<ArrayVec<[(&'a str, &'a str); 1]>, Error> {
        Ok(ArrayVec::from([(
            "stream",
            if self.stream { TRUE_STR } else { FALSE_STR },
        )]))
    }
}

/// Granular memory statistics for the container.
#[derive(Debug, Copy, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(missing_docs)]
pub struct MemoryStatsStats {
    pub cache: u64,
    pub dirty: u64,
    pub mapped_file: u64,
    pub total_inactive_file: u64,
    pub pgpgout: u64,
    pub rss: u64,
    pub total_mapped_file: u64,
    pub writeback: u64,
    pub unevictable: u64,
    pub pgpgin: u64,
    pub total_unevictable: u64,
    pub pgmajfault: u64,
    pub total_rss: u64,
    pub total_rss_huge: u64,
    pub total_writeback: u64,
    pub total_inactive_anon: u64,
    pub rss_huge: u64,
    pub hierarchical_memory_limit: u64,
    pub total_pgfault: u64,
    pub total_active_file: u64,
    pub active_anon: u64,
    pub total_active_anon: u64,
    pub total_pgpgout: u64,
    pub total_cache: u64,
    pub total_dirty: u64,
    pub inactive_anon: u64,
    pub active_file: u64,
    pub pgfault: u64,
    pub inactive_file: u64,
    pub total_pgmajfault: u64,
    pub total_pgpgin: u64,
    pub hierarchical_memsw_limit: Option<u64>,
}

/// General memory statistics for the container.
#[derive(Debug, Copy, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(missing_docs)]
pub struct MemoryStats {
    pub stats: Option<MemoryStatsStats>,
    pub max_usage: Option<u64>,
    pub usage: Option<u64>,
    pub failcnt: Option<u64>,
    pub limit: Option<u64>,
    pub commit: Option<u64>,
    pub commit_peak: Option<u64>,
    pub commitbytes: Option<u64>,
    pub private_working_set: Option<u64>,
}

/// Process ID statistics for the container.
#[derive(Debug, Copy, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(missing_docs)]
pub struct PidsStats {
    pub current: Option<u64>,
    pub limit: Option<u64>,
}

/// I/O statistics for the container.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(missing_docs)]
pub struct BlkioStats {
    pub io_service_bytes_recursive: Option<Vec<BlkioStatsEntry>>,
    pub io_serviced_recursive: Option<Vec<BlkioStatsEntry>>,
    pub io_queue_recursive: Option<Vec<BlkioStatsEntry>>,
    pub io_service_time_recursive: Option<Vec<BlkioStatsEntry>>,
    pub io_wait_time_recursive: Option<Vec<BlkioStatsEntry>>,
    pub io_merged_recursive: Option<Vec<BlkioStatsEntry>>,
    pub io_time_recursive: Option<Vec<BlkioStatsEntry>>,
    pub sectors_recursive: Option<Vec<BlkioStatsEntry>>,
}

/// File I/O statistics for the container.
#[derive(Debug, Copy, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(missing_docs)]
pub struct StorageStats {
    pub read_count_normalized: Option<u64>,
    pub read_size_bytes: Option<u64>,
    pub write_count_normalized: Option<u64>,
    pub write_size_bytes: Option<u64>,
}

/// Statistics for the container.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(missing_docs)]
pub struct Stats {
    pub read: DateTime<Utc>,
    pub preread: DateTime<Utc>,
    pub num_procs: u32,
    pub pids_stats: PidsStats,
    pub network: Option<NetworkStats>,
    pub networks: Option<HashMap<String, NetworkStats>>,
    pub memory_stats: MemoryStats,
    pub blkio_stats: BlkioStats,
    pub cpu_stats: CPUStats,
    pub precpu_stats: CPUStats,
    pub storage_stats: StorageStats,
    pub name: String,
    pub id: String,
}

/// Network statistics for the container.
#[derive(Debug, Copy, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(missing_docs)]
pub struct NetworkStats {
    pub rx_dropped: u64,
    pub rx_bytes: u64,
    pub rx_errors: u64,
    pub tx_packets: u64,
    pub tx_dropped: u64,
    pub rx_packets: u64,
    pub tx_errors: u64,
    pub tx_bytes: u64,
}

/// CPU usage statistics for the container.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(missing_docs)]
pub struct CPUUsage {
    pub percpu_usage: Option<Vec<u64>>,
    pub usage_in_usermode: u64,
    pub total_usage: u64,
    pub usage_in_kernelmode: u64,
}

/// CPU throttling statistics.
#[derive(Debug, Copy, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(missing_docs)]
pub struct ThrottlingData {
    pub periods: u64,
    pub throttled_periods: u64,
    pub throttled_time: u64,
}

/// General CPU statistics for the container.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(missing_docs)]
pub struct CPUStats {
    pub cpu_usage: CPUUsage,
    pub system_cpu_usage: Option<u64>,
    pub online_cpus: Option<u64>,
    pub throttling_data: ThrottlingData,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(missing_docs)]
pub struct BlkioStatsEntry {
    pub major: u64,
    pub minor: u64,
    pub op: String,
    pub value: u64,
}

/// Parameters used in the [Kill Container API](../struct.Docker.html#method.kill_container)
///
/// ## Examples
///
/// ```rust
/// use bollard::container::KillContainerOptions;
///
/// KillContainerOptions{
///     signal: "SIGINT",
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct KillContainerOptions<T>
where
    T: AsRef<str>,
{
    /// Signal to send to the container as an integer or string (e.g. `SIGINT`)
    pub signal: T,
}

/// Trait providing implementations for [Kill Container Options](struct.KillContainerOptions.html).
#[allow(missing_docs)]
pub trait KillContainerQueryParams<K, V>
where
    K: AsRef<str>,
    V: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, V); 1]>, Error>;
}

impl<'a, T: AsRef<str>> KillContainerQueryParams<&'a str, T> for KillContainerOptions<T> {
    fn into_array(self) -> Result<ArrayVec<[(&'a str, T); 1]>, Error> {
        Ok(ArrayVec::from([("signal", self.signal)]))
    }
}

/// Block IO weight (relative device weight).
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct UpdateContainerOptionsBlkioWeight {
    pub path: String,
    pub weight: isize,
}

/// Limit read/write rate (IO/bytes per second) from/to a device.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct UpdateContainerOptionsBlkioDeviceRate {
    pub path: String,
    pub rate: isize,
}

/// A list of devices to add to the container.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct UpdateContainerOptionsDevices {
    pub path_on_host: String,
    pub path_in_container: String,
    pub cgroup_permissions: String,
}

/// A list of resource limits to set in the container.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct UpdateContainerOptionsUlimits {
    pub name: String,
    pub soft: isize,
    pub hard: isize,
}

/// The behavior to apply when the container exits. The default is not to restart.
///
/// An ever increasing delay (double the previous delay, starting at 100ms) is added before each
/// restart to prevent flooding the server.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct UpdateContainerOptionsRestartPolicy {
    pub name: String,
    pub maximum_retry_count: isize,
}

/// Configuration for the [Update Container API](../struct.Docker.html#method.update_container)
///
/// ## Examples
///
/// ```rust
/// use bollard::container::UpdateContainerOptions;
/// use std::default::Default;
///
/// UpdateContainerOptions {
///     memory: Some(314572800),
///     memory_swap: Some(314572800),
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
pub struct UpdateContainerOptions {
    /// An integer value representing this container's relative CPU weight versus other containers.
    pub cpu_shares: Option<isize>,
    /// Memory limit in bytes.
    pub memory: Option<u64>,
    /// Path to `cgroups` under which the container's `cgroup` is created. If the path is not absolute,
    /// the path is considered to be relative to the `cgroups` path of the init process. Cgroups are
    /// created if they do not already exist.
    pub cgroup_parent: Option<String>,
    /// Block IO weight (relative weight).
    pub blkio_weight: Option<isize>,
    /// Block IO weight (relative device weight).
    pub blkio_weight_device: Vec<UpdateContainerOptionsBlkioWeight>,
    /// Limit read rate (bytes per second) from a device.
    pub blkio_device_read_bps: Vec<UpdateContainerOptionsBlkioDeviceRate>,
    /// Limit write rate (bytes per second) to a device.
    #[serde(rename = "BlkioDeviceWriteIOps")]
    pub blkio_device_write_iops: Vec<UpdateContainerOptionsBlkioDeviceRate>,
    /// Limit read rate (IO per second) from a device.
    #[serde(rename = "BlkioDeviceReadIOps")]
    pub blkio_device_read_iops: Vec<UpdateContainerOptionsBlkioDeviceRate>,
    /// The length of a CPU period in microseconds.
    pub cpu_period: Option<u64>,
    /// Microseconds of CPU time that the container can get in a CPU period.
    pub cpu_quota: Option<u64>,
    /// The length of a CPU real-time period in microseconds. Set to 0 to allocate no time allocated to real-time tasks.
    pub cpu_realtime_period: Option<u64>,
    /// The length of a CPU real-time runtime in microseconds. Set to 0 to allocate no time allocated to real-time tasks.
    pub cpu_realtime_runtime: Option<u64>,
    /// CPUs in which to allow execution (e.g., `0-3`, `0,1`)
    pub cpuset_cpus: Option<String>,
    /// Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.
    pub cpuset_mems: Option<String>,
    /// A list of devices to add to the container.
    pub devices: Option<Vec<UpdateContainerOptionsDevices>>,
    /// A list of cgroup rules to apply to the container.
    pub device_cgroup_rules: Option<Vec<String>>,
    /// Disk limit (in bytes).
    pub disk_quota: Option<u64>,
    /// Kernel memory limit in bytes.
    pub kernel_memory: Option<u64>,
    /// Memory soft limit in bytes.
    pub memory_reservation: Option<u64>,
    /// Total memory limit (memory + swap). Set as `-1` to enable unlimited swap.
    pub memory_swap: Option<i64>,
    /// Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100.
    pub memory_swappiness: Option<u64>,
    /// CPU quota in units of 10<sup>-9</sup> CPUs.
    pub nano_cpus: Option<u64>,
    /// Disable OOM Killer for the container.
    pub oom_kill_disable: Option<bool>,
    /// Run an init inside the container that forwards signals and reaps processes. This field is
    /// omitted if empty, and the default (as configured on the daemon) is used.
    pub init: Option<bool>,
    /// Tune a container's pids limit. Set -1 for unlimited.
    pub pids_limit: Option<u64>,
    /// A list of resource limits to set in the container.
    pub ulimits: Vec<UpdateContainerOptionsUlimits>,
    /// The number of usable CPUs (Windows only).
    ///
    /// On Windows Server containers, the processor resource controls are mutually exclusive. The
    /// order of precedence is `CPUCount` first, then `CPUShares`, and `CPUPercent` last.
    pub cpu_count: Option<u64>,
    /// The usable percentage of the available CPUs (Windows only).
    ///
    /// On Windows Server containers, the processor resource controls are mutually exclusive. The
    /// order of precedence is `CPUCount` first, then `CPUShares`, and `CPUPercent` last.
    pub cpu_percent: Option<u64>,
    /// Maximum IOps for the container system drive (Windows only).
    #[serde(rename = "IOMaximumIOps")]
    pub io_maximum_iops: Option<u64>,
    /// Maximum IO in bytes per second for the container system drive (Windows only).
    #[serde(rename = "IOMaximumBandwidth")]
    pub io_maximum_bandwidth: Option<u64>,
    /// The behavior to apply when the container exits. The default is not to restart.
    ///
    /// An ever increasing delay (double the previous delay, starting at 100ms) is added before
    /// each restart to prevent flooding the server.
    pub restart_policy: Option<UpdateContainerOptionsRestartPolicy>,
}

/// Parameters used in the [Rename Container API](../struct.Docker.html#method.rename_container)
///
/// ## Examples
///
/// ```rust
/// use bollard::container::RenameContainerOptions;
///
/// RenameContainerOptions {
///     name: "my_new_container_name"
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct RenameContainerOptions<T>
where
    T: AsRef<str>,
{
    /// New name for the container.
    pub name: T,
}

/// Trait providing implementations for [Rename Container Options](struct.RenameContainerOptions.html).
#[allow(missing_docs)]
pub trait RenameContainerQueryParams<K, V>
where
    K: AsRef<str>,
    V: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, V); 1]>, Error>;
}

impl<'a, T: AsRef<str>> RenameContainerQueryParams<&'a str, T> for RenameContainerOptions<T> {
    fn into_array(self) -> Result<ArrayVec<[(&'a str, T); 1]>, Error> {
        Ok(ArrayVec::from([("name", self.name)]))
    }
}

/// Parameters used in the [Prune Containers API](../struct.Docker.html#method.prune_containers)
///
/// ## Examples
///
/// ```rust
/// use bollard::container::PruneContainersOptions;
///
/// use std::collections::HashMap;
///
/// let mut filters = HashMap::new();
/// filters.insert("until", vec!("10m"));
///
/// PruneContainersOptions{
///     filters: filters
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct PruneContainersOptions<T>
where
    T: AsRef<str> + Eq + Hash,
{
    /// Filters to process on the prune list, encoded as JSON.
    ///
    /// Available filters:
    ///  - `until=<timestamp>` Prune containers created before this timestamp. The `<timestamp>` can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed relative to the daemon machine's time.
    ///  - label (`label=<key>`, `label=<key>=<value>`, `label!=<key>`, or `label!=<key>=<value>`) Prune containers with (or without, in case `label!=...` is used) the specified labels.
    pub filters: HashMap<T, Vec<T>>,
}

/// Trait providing implementations for [Prune Containers Options](struct.PruneContainersOptions.html).
#[allow(missing_docs)]
pub trait PruneContainersQueryParams<K>
where
    K: AsRef<str>,
{
    fn into_array(self) -> Result<ArrayVec<[(K, String); 1]>, Error>;
}

impl<'a, T: AsRef<str> + Eq + Hash + Serialize> PruneContainersQueryParams<&'a str>
    for PruneContainersOptions<T>
{
    fn into_array(self) -> Result<ArrayVec<[(&'a str, String); 1]>, Error> {
        Ok(ArrayVec::from([(
            "filters",
            serde_json::to_string(&self.filters)?,
        )]))
    }
}

/// Result type for the [Prune Containers API](../struct.Docker.html#method.prune_containers)
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "PascalCase", deny_unknown_fields)]
#[allow(missing_docs)]
pub struct PruneContainersResults {
    pub containers_deleted: Option<Vec<String>>,
    pub space_reclaimed: u64,
}

impl<C> Docker<C>
where
    C: Connect + Sync + 'static,
{
    /// ---
    ///
    /// # List Containers
    ///
    /// Returns a list of containers.
    ///
    /// # Arguments
    ///
    ///  - Optional [ListContainersOptions](container/struct.ListContainersOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - Vector of [APIContainers](container/struct.APIContainers.html), wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    /// use bollard::container::{ListContainersOptions};
    ///
    /// use std::collections::HashMap;
    /// use std::default::Default;
    ///
    /// let mut filters = HashMap::new();
    /// filters.insert("health", vec!("unhealthy"));
    ///
    /// let options = Some(ListContainersOptions{
    ///     all: true,
    ///     filters: filters,
    ///     ..Default::default()
    /// });
    ///
    /// docker.list_containers(options);
    /// ```
    pub fn list_containers<T, K>(
        &self,
        options: Option<T>,
    ) -> impl Future<Item = Vec<APIContainers>, Error = Error>
    where
        T: ListContainersQueryParams<K, String>,
        K: AsRef<str>,
    {
        let url = "/containers/json";

        let req = self.build_request(
            url,
            Builder::new().method(Method::GET),
            Docker::<C>::transpose_option(options.map(|o| o.into_array())),
            Ok(Body::empty()),
        );

        self.process_into_value(req)
    }

    /// ---
    ///
    /// # Create Container
    ///
    /// Prepares a container for a subsequent start operation.
    ///
    /// # Arguments
    ///
    ///  - Optional [Create Container Options](container/struct.CreateContainerOptions.html) struct.
    ///  - Container [Config](container/struct.Config.html) struct.
    ///
    /// # Returns
    ///
    ///  - [Create Container Results](container/struct.CreateContainerResults.html), wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    /// use bollard::container::{CreateContainerOptions, Config};
    ///
    /// use std::default::Default;
    ///
    /// let options = Some(CreateContainerOptions{
    ///     name: "my-new-container",
    /// });
    ///
    /// let config = Config {
    ///     image: Some("hello-world"),
    ///     cmd: Some(vec!["/hello"]),
    ///     ..Default::default()
    /// };
    ///
    /// docker.create_container(options, config);
    /// ```
    pub fn create_container<T, K, V, Z>(
        &self,
        options: Option<T>,
        config: Config<Z>,
    ) -> impl Future<Item = CreateContainerResults, Error = Error>
    where
        T: CreateContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
        Z: AsRef<str> + Eq + Hash + Serialize,
    {
        let url = "/containers/create";

        let req = self.build_request(
            url,
            Builder::new().method(Method::POST),
            Docker::<C>::transpose_option(options.map(|o| o.into_array())),
            Docker::<C>::serialize_payload(Some(config)),
        );

        self.process_into_value(req)
    }

    /// ---
    ///
    /// # Start Container
    ///
    /// Starts a container, after preparing it with the [Create Container
    /// API](struct.Docker.html#method.create_container).
    ///
    /// # Arguments
    ///
    ///  - Container name as a string slice.
    ///  - Optional [Start Container Options](container/struct.StartContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - unit type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    /// use bollard::container::StartContainerOptions;
    ///
    /// docker.start_container("hello-world", None::<StartContainerOptions<String>>);
    /// ```
    pub fn start_container<T, K, V>(
        &self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (), Error = Error>
    where
        T: StartContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let url = format!("/containers/{}/start", container_name);

        let req = self.build_request(
            &url,
            Builder::new().method(Method::POST),
            Docker::<C>::transpose_option(options.map(|o| o.into_array())),
            Ok(Body::empty()),
        );

        self.process_into_unit(req)
    }

    /// ---
    ///
    /// # Stop Container
    ///
    /// Stops a container.
    ///
    /// # Arguments
    ///
    /// - Container name as string slice.
    /// - Optional [Stop Container Options](container/struct.StopContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - unit type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// use bollard::container::StopContainerOptions;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// let options = Some(StopContainerOptions{
    ///     t: 30,
    /// });
    ///
    /// docker.stop_container("hello-world", options);
    /// ```
    pub fn stop_container<T, K>(
        &self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (), Error = Error>
    where
        T: StopContainerQueryParams<K>,
        K: AsRef<str>,
    {
        let url = format!("/containers/{}/stop", container_name);

        let req = self.build_request(
            &url,
            Builder::new().method(Method::POST),
            Docker::<C>::transpose_option(options.map(|o| o.into_array())),
            Ok(Body::empty()),
        );

        self.process_into_unit(req)
    }

    /// ---
    ///
    /// # Remove Container
    ///
    /// Remove a container.
    ///
    /// # Arguments
    ///
    /// - Container name as a string slice.
    /// - Optional [Remove Container Options](container/struct.RemoveContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - unit type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::RemoveContainerOptions;
    ///
    /// use std::default::Default;
    ///
    /// let options = Some(RemoveContainerOptions{
    ///     force: true,
    ///     ..Default::default()
    /// });
    ///
    /// docker.remove_container("hello-world", options);
    /// ```
    pub fn remove_container<T, K, V>(
        &self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (), Error = Error>
    where
        T: RemoveContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let url = format!("/containers/{}", container_name);

        let req = self.build_request(
            &url,
            Builder::new().method(Method::DELETE),
            Docker::<C>::transpose_option(options.map(|o| o.into_array())),
            Ok(Body::empty()),
        );

        self.process_into_unit(req)
    }

    /// ---
    ///
    /// # Wait Container
    ///
    /// Wait for a container to stop. This is a non-blocking operation, the resulting stream will
    /// end when the container stops.
    ///
    /// # Arguments
    ///
    /// - Container name as string slice.
    /// - Optional [Wait Container Options](container/struct.WaitContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - [Wait Container Results](container/struct.WaitContainerResults.html), wrapped in a
    ///  Stream.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::WaitContainerOptions;
    ///
    /// let options = Some(WaitContainerOptions{
    ///     condition: "not-running",
    /// });
    ///
    /// docker.wait_container("hello-world", options);
    /// ```
    pub fn wait_container<T, K, V>(
        &self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Stream<Item = WaitContainerResults, Error = Error>
    where
        T: WaitContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let url = format!("/containers/{}/wait", container_name);

        let req = self.build_request(
            &url,
            Builder::new().method(Method::POST),
            Docker::<C>::transpose_option(options.map(|o| o.into_array())),
            Ok(Body::empty()),
        );

        self.process_into_stream(req)
    }

    /// ---
    ///
    /// # Restart Container
    ///
    /// Restart a container.
    ///
    /// # Arguments
    ///
    ///  - Container name as string slice.
    ///  - Optional [Restart Container Options](container/struct.RestartContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - unit type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::RestartContainerOptions;
    ///
    /// let options = Some(RestartContainerOptions{
    ///     t: 30,
    /// });
    ///
    /// docker.restart_container("postgres", options);
    /// ```
    pub fn restart_container<T, K>(
        &self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (), Error = Error>
    where
        T: RestartContainerQueryParams<K>,
        K: AsRef<str>,
    {
        let url = format!("/containers/{}/restart", container_name);

        let req = self.build_request(
            &url,
            Builder::new().method(Method::POST),
            Docker::<C>::transpose_option(options.map(|o| o.into_array())),
            Ok(Body::empty()),
        );

        self.process_into_unit(req)
    }

    /// ---
    ///
    /// # Inspect Container
    ///
    /// Inspect a container.
    ///
    /// # Arguments
    ///
    ///  - Container name as a string slice.
    ///  - Optional [Inspect Container Options](container/struct.InspectContainerOptions.struct) struct.
    ///
    /// # Returns
    ///
    ///  - [Container](container/struct.Container.html), wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    /// use bollard::container::InspectContainerOptions;
    ///
    /// let options = Some(InspectContainerOptions{
    ///     size: false,
    /// });
    ///
    /// docker.inspect_container("hello-world", options);
    /// ```
    pub fn inspect_container<T, K, V>(
        &self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = Container, Error = Error>
    where
        T: InspectContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let url = format!("/containers/{}/json", container_name);

        let req = self.build_request(
            &url,
            Builder::new().method(Method::GET),
            Docker::<C>::transpose_option(options.map(|o| o.into_array())),
            Ok(Body::empty()),
        );

        self.process_into_value(req)
    }

    /// ---
    ///
    /// # Top Processes
    ///
    /// List processes running inside a container.
    ///
    /// # Arguments
    ///
    ///  - Container name as string slice.
    ///  - Optional [Top Options](container/struct.TopOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - [TopResult](container/struct.TopResult.html), wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    /// use bollard::container::TopOptions;
    ///
    /// let options = Some(TopOptions{
    ///     ps_args: "aux",
    /// });
    ///
    /// docker.top_processes("fnichol/uhttpd", options);
    /// ```
    pub fn top_processes<T, K, V>(
        &self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = TopResult, Error = Error>
    where
        T: TopQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let url = format!("/containers/{}/top", container_name);

        let req = self.build_request(
            &url,
            Builder::new().method(Method::GET),
            Docker::<C>::transpose_option(options.map(|o| o.into_array())),
            Ok(Body::empty()),
        );

        self.process_into_value(req)
    }

    /// ---
    ///
    /// # Logs
    ///
    /// Get container logs.
    ///
    /// # Arguments
    ///
    ///  - Container name as string slice.
    ///  - Optional [Logs Options](container/struct.LogsOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - [Log Output](container/enum.LogOutput.html) enum, wrapped in a
    ///  Stream.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::LogsOptions;
    ///
    /// use std::default::Default;
    ///
    /// let options = Some(LogsOptions{
    ///     stdout: true,
    ///     ..Default::default()
    /// });
    ///
    /// docker.logs("hello-world", options);
    /// ```
    pub fn logs<T, K>(
        &self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Stream<Item = LogOutput, Error = Error>
    where
        T: LogsQueryParams<K>,
        K: AsRef<str>,
    {
        let url = format!("/containers/{}/logs", container_name);

        let req = self.build_request(
            &url,
            Builder::new().method(Method::GET),
            Docker::<C>::transpose_option(options.map(|o| o.into_array())),
            Ok(Body::empty()),
        );

        self.process_into_stream_string(req)
    }

    /// ---
    ///
    /// # Container Changes
    ///
    /// Get changes on a container's filesystem.
    ///
    /// # Arguments
    ///
    ///  - Container name as string slice.
    ///
    /// # Returns
    ///
    ///  - An Option of Vector of [Change](container/struct.Change.html) structs, wrapped in a
    ///  Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// docker.container_changes("hello-world");
    /// ```
    pub fn container_changes(
        &self,
        container_name: &str,
    ) -> impl Future<Item = Option<Vec<Change>>, Error = Error> {
        let url = format!("/containers/{}/changes", container_name);

        let req = self.build_request::<_, String, String>(
            &url,
            Builder::new().method(Method::GET),
            Ok(None::<ArrayVec<[(_, _); 0]>>),
            Ok(Body::empty()),
        );

        self.process_into_value(req)
    }

    /// ---
    ///
    /// # Stats
    ///
    /// Get container stats based on resource usage.
    ///
    /// # Arguments
    ///
    /// - Container name as string slice.
    /// - Optional [Stats Options](container/struct.StatsOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - [Stats](container/struct.Stats.html) struct, wrapped in a
    ///  Stream.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::StatsOptions;
    ///
    /// let options = Some(StatsOptions{
    ///     stream: false,
    /// });
    ///
    /// docker.stats("hello-world", options);
    /// ```
    pub fn stats<T, K, V>(
        &self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Stream<Item = Stats, Error = Error>
    where
        T: StatsQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let url = format!("/containers/{}/stats", container_name);

        let req = self.build_request(
            &url,
            Builder::new().method(Method::GET),
            Docker::<C>::transpose_option(options.map(|o| o.into_array())),
            Ok(Body::empty()),
        );

        self.process_into_stream(req)
    }

    /// ---
    ///
    /// # Kill Container
    ///
    /// Kill a container.
    ///
    /// # Arguments
    ///
    /// - Container name as string slice.
    /// - Optional [Kill Container Options](container/struct.KillContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - unit type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::KillContainerOptions;
    ///
    /// let options = Some(KillContainerOptions{
    ///     signal: "SIGINT",
    /// });
    ///
    /// docker.kill_container("postgres", options);
    /// ```
    pub fn kill_container<T, K, V>(
        &self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (), Error = Error>
    where
        T: KillContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let url = format!("/containers/{}/kill", container_name);

        let req = self.build_request(
            &url,
            Builder::new().method(Method::POST),
            Docker::<C>::transpose_option(options.map(|o| o.into_array())),
            Ok(Body::empty()),
        );

        self.process_into_unit(req)
    }

    /// ---
    ///
    /// # Update Container
    ///
    /// Update a container.
    ///
    /// # Arguments
    ///
    ///  - Container name as string slice.
    ///  - [Update Container Options](container/struct.UpdateContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - unit type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::UpdateContainerOptions;
    /// use std::default::Default;
    ///
    /// let config = UpdateContainerOptions {
    ///     memory: Some(314572800),
    ///     memory_swap: Some(314572800),
    ///     ..Default::default()
    /// };
    ///
    /// docker.update_container("postgres", config);
    /// ```
    pub fn update_container(
        &self,
        container_name: &str,
        config: UpdateContainerOptions,
    ) -> impl Future<Item = (), Error = Error> {
        let url = format!("/containers/{}/update", container_name);

        let req = self.build_request::<_, String, String>(
            &url,
            Builder::new().method(Method::POST),
            Ok(None::<ArrayVec<[(_, _); 0]>>),
            Docker::<C>::serialize_payload(Some(config)),
        );

        self.process_into_unit(req)
    }

    /// ---
    ///
    /// # Rename Container
    ///
    /// Rename a container.
    ///
    /// # Arguments
    ///
    ///  - Container name as string slice.
    ///  - [Rename Container Options](container/struct.RenameContainerOptions.html) struct
    ///
    /// # Returns
    ///
    ///  - unit type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::RenameContainerOptions;
    ///
    /// let required = RenameContainerOptions {
    ///     name: "my_new_container_name"
    /// };
    ///
    /// docker.rename_container("hello-world", required);
    /// ```
    pub fn rename_container<T, K, V>(
        &self,
        container_name: &str,
        options: T,
    ) -> impl Future<Item = (), Error = Error>
    where
        T: RenameContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        let url = format!("/containers/{}/rename", container_name);

        let req = self.build_request(
            &url,
            Builder::new().method(Method::POST),
            Docker::<C>::transpose_option(Some(options.into_array())),
            Ok(Body::empty()),
        );

        self.process_into_unit(req)
    }

    /// ---
    ///
    /// # Pause Container
    ///
    /// Use the cgroups freezer to suspend all processes in a container.
    ///
    /// # Arguments
    ///
    ///  - Container name as a string slice.
    ///
    /// # Returns
    ///
    ///  - unit type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// docker.pause_container("postgres");
    /// ```
    pub fn pause_container(&self, container_name: &str) -> impl Future<Item = (), Error = Error> {
        let url = format!("/containers/{}/pause", container_name);

        let req = self.build_request::<_, String, String>(
            &url,
            Builder::new().method(Method::POST),
            Ok(None::<ArrayVec<[(_, _); 0]>>),
            Ok(Body::empty()),
        );

        self.process_into_unit(req)
    }

    /// ---
    ///
    /// # Unpause Container
    ///
    /// Resume a container which has been paused.
    ///
    /// # Arguments
    ///
    ///  - Container name as a string slice.
    ///
    /// # Returns
    ///
    ///  - unit type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// docker.unpause_container("postgres");
    /// ```
    pub fn unpause_container(&self, container_name: &str) -> impl Future<Item = (), Error = Error> {
        let url = format!("/containers/{}/unpause", container_name);

        let req = self.build_request::<_, String, String>(
            &url,
            Builder::new().method(Method::POST),
            Ok(None::<ArrayVec<[(_, _); 0]>>),
            Ok(Body::empty()),
        );

        self.process_into_unit(req)
    }

    /// ---
    ///
    /// # Prune Containers
    ///
    /// Delete stopped containers.
    ///
    /// # Arguments
    ///
    ///  - Optional [Prune Containers Options](container/struct.PruneContainersOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - [PruneContainersResults](container/struct.PruneContainersResults.html) struct, wrapped in a
    ///  Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    /// use bollard::container::PruneContainersOptions;
    ///
    /// use std::collections::HashMap;
    ///
    /// let mut filters = HashMap::new();
    /// filters.insert("until", vec!("10m"));
    ///
    /// let options = Some(PruneContainersOptions{
    ///     filters: filters
    /// });
    ///
    /// docker.prune_containers(options);
    /// ```
    pub fn prune_containers<T, K>(
        &self,
        options: Option<T>,
    ) -> impl Future<Item = PruneContainersResults, Error = Error>
    where
        T: PruneContainersQueryParams<K>,
        K: AsRef<str> + Eq + Hash,
    {
        let url = "/containers/prune";

        let req = self.build_request(
            &url,
            Builder::new().method(Method::POST),
            Docker::<C>::transpose_option(options.map(|o| o.into_array())),
            Ok(Body::empty()),
        );

        self.process_into_value(req)
    }
}

impl<C> DockerChain<C>
where
    C: Connect + Sync + 'static,
{
    /// ---
    ///
    /// # Kill Container
    ///
    /// Kill a container. Consumes the client instance.
    ///
    /// # Arguments
    ///
    /// - Container name as string slice.
    /// - Optional [Kill Container Options](container/struct.KillContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and the unit
    ///  type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::KillContainerOptions;
    ///
    /// let options = Some(KillContainerOptions{
    ///     signal: "SIGINT",
    /// });
    ///
    /// docker.chain().kill_container("postgres", options);
    /// ```
    pub fn kill_container<T, K, V>(
        self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (DockerChain<C>, ()), Error = Error>
    where
        T: KillContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.inner
            .kill_container(container_name, options)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # Remove Container
    ///
    /// Remove a container. Consumes the instance.
    ///
    /// # Arguments
    ///
    /// - Container name as a string slice.
    /// - Optional [Remove Container Options](container/struct.RemoveContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and the unit
    ///  type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::RemoveContainerOptions;
    ///
    /// use std::default::Default;
    ///
    /// let options = Some(RemoveContainerOptions{
    ///     force: true,
    ///     ..Default::default()
    /// });
    ///
    /// docker.chain().remove_container("hello-world", options);
    /// ```
    pub fn remove_container<T, K, V>(
        self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (DockerChain<C>, ()), Error = Error>
    where
        T: RemoveContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.inner
            .remove_container(container_name, options)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # Create Container
    ///
    /// Prepares a container for a subsequent start operation. Consumes the instance.
    ///
    /// # Arguments
    ///
    ///  - Optional [Create Container Options](container/struct.CreateContainerOptions.html) struct.
    ///  - Container [Config](container/struct.Config.html) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and a
    ///  [Create Container Results](container/struct.CreateContainerResults.html), wrapped in a
    ///  Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    /// use bollard::container::{CreateContainerOptions, Config};
    ///
    /// use std::default::Default;
    ///
    /// let options = Some(CreateContainerOptions{
    ///     name: "my-new-container",
    /// });
    ///
    /// let config = Config {
    ///     image: Some("hello-world"),
    ///     cmd: Some(vec!["/hello"]),
    ///     ..Default::default()
    /// };
    ///
    /// docker.chain().create_container(options, config);
    /// ```
    pub fn create_container<T, K, V, Z>(
        self,
        options: Option<T>,
        config: Config<Z>,
    ) -> impl Future<Item = (DockerChain<C>, CreateContainerResults), Error = Error>
    where
        T: CreateContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
        Z: AsRef<str> + Eq + Hash + Serialize,
    {
        self.inner
            .create_container(options, config)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # Start Container
    ///
    /// Starts a container, after preparing it with the [Create Container
    /// API](struct.Docker.html#method.create_container). Consumes the client instance.
    ///
    /// # Arguments
    ///
    ///  - Container name as a string slice.
    ///  - Optional [Start Container Options](container/struct.StartContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and the unit
    ///  type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    /// use bollard::container::StartContainerOptions;
    ///
    /// docker.chain().start_container("hello-world", None::<StartContainerOptions<String>>);
    /// ```
    pub fn start_container<T, K, V>(
        self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (DockerChain<C>, ()), Error = Error>
    where
        T: StartContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.inner
            .start_container(container_name, options)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # Stop Container
    ///
    /// Stops a container. Consumes the client instance.
    ///
    /// # Arguments
    ///
    /// - Container name as string slice.
    /// - Optional [Stop Container Options](container/struct.StopContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and the unit
    ///  type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// use bollard::container::StopContainerOptions;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// let options = Some(StopContainerOptions{
    ///     t: 30,
    /// });
    ///
    /// docker.chain().stop_container("hello-world", options);
    /// ```
    pub fn stop_container<T, K>(
        self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (DockerChain<C>, ()), Error = Error>
    where
        T: StopContainerQueryParams<K>,
        K: AsRef<str>,
    {
        self.inner
            .stop_container(container_name, options)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # List Containers
    ///
    /// Returns a list of containers. Consumes the client instance.
    ///
    /// # Arguments
    ///
    ///  - Optional [ListContainersOptions](container/struct.ListContainersOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and a Vector
    ///  of [APIContainers](container/struct.APIContainers.html), wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    /// use bollard::container::ListContainersOptions;
    ///
    /// use std::collections::HashMap;
    /// use std::default::Default;
    ///
    /// let mut filters = HashMap::new();
    /// filters.insert("health", vec!("unhealthy"));
    ///
    /// let options = Some(ListContainersOptions{
    ///     all: true,
    ///     filters: filters,
    ///     ..Default::default()
    /// });
    ///
    /// docker.chain().list_containers(options);
    /// ```
    pub fn list_containers<T, K>(
        self,
        options: Option<T>,
    ) -> impl Future<Item = (DockerChain<C>, Vec<APIContainers>), Error = Error>
    where
        T: ListContainersQueryParams<K, String>,
        K: AsRef<str>,
    {
        self.inner
            .list_containers(options)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # Wait Container
    ///
    /// Wait for a container to stop. This is a non-blocking operation, the resulting stream will
    /// end when the container stops. Consumes the instance.
    ///
    /// # Arguments
    ///
    /// - Container name as string slice.
    /// - Optional [Wait Container Options](container/struct.WaitContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and a [Wait
    ///  Container Results](container/struct.WaitContainerResults.html), wrapped in a Stream.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::WaitContainerOptions;
    ///
    /// let options = Some(WaitContainerOptions{
    ///     condition: "not-running",
    /// });
    ///
    /// docker.chain().wait_container("hello-world", options);
    /// ```
    pub fn wait_container<T, K, V>(
        self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<
        Item = (
            DockerChain<C>,
            impl Stream<Item = WaitContainerResults, Error = Error>,
        ),
        Error = Error,
    >
    where
        T: WaitContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.inner
            .wait_container(container_name, options)
            .into_future()
            .map(|(first, rest)| match first {
                Some(head) => (self, EitherStream::A(stream::once(Ok(head)).chain(rest))),
                None => (self, EitherStream::B(stream::empty())),
            })
            .map_err(|(err, _)| err)
    }

    /// ---
    ///
    /// # Inspect Container
    ///
    /// Inspect a container. Consumes the instance.
    ///
    /// # Arguments
    ///
    ///  - Container name as a string slice.
    ///  - Optional [Inspect Container Options](container/struct.InspectContainerOptions.struct) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and a
    ///  [Container](container/struct.Container.html), wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    /// use bollard::container::InspectContainerOptions;
    ///
    /// let options = Some(InspectContainerOptions{
    ///     size: false,
    /// });
    ///
    /// docker.chain().inspect_container("hello-world", options);
    /// ```
    pub fn inspect_container<T, K, V>(
        self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (DockerChain<C>, Container), Error = Error>
    where
        T: InspectContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.inner
            .inspect_container(container_name, options)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # Restart Container
    ///
    /// Restart a container. Consumes the client instance.
    ///
    /// # Arguments
    ///
    ///  - Container name as string slice.
    ///  - Optional [Restart Container Options](container/struct.RestartContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and the unit
    ///  type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::RestartContainerOptions;
    ///
    /// let options = Some(RestartContainerOptions{
    ///     t: 30,
    /// });
    ///
    /// docker.chain().restart_container("postgres", options);
    /// ```
    pub fn restart_container<T, K>(
        self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (DockerChain<C>, ()), Error = Error>
    where
        T: RestartContainerQueryParams<K>,
        K: AsRef<str>,
    {
        self.inner
            .restart_container(container_name, options)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # Top Processes
    ///
    /// List processes running inside a container. Consumes the client instance.
    ///
    /// # Arguments
    ///
    ///  - Container name as string slice.
    ///  - Optional [Top Options](container/struct.TopOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and a
    ///  [TopResult](container/struct.TopResult.html), wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    /// use bollard::container::TopOptions;
    ///
    /// let options = Some(TopOptions{
    ///     ps_args: "aux",
    /// });
    ///
    /// docker.chain().top_processes("fnichol/uhttpd", options);
    /// ```
    pub fn top_processes<T, K, V>(
        self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (DockerChain<C>, TopResult), Error = Error>
    where
        T: TopQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.inner
            .top_processes(container_name, options)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # Logs
    ///
    /// Get container logs. Consumes the client instance.
    ///
    /// # Arguments
    ///
    ///  - Container name as string slice.
    ///  - Optional [Logs Query Params](container/struct.LogsQueryParams.html) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and a [Log
    ///  Output](container/enum.LogOutput.html) enum, wrapped in a Stream.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::LogsOptions;
    ///
    /// use std::default::Default;
    ///
    /// let options = Some(LogsOptions{
    ///     stdout: true,
    ///     ..Default::default()
    /// });
    ///
    /// docker.chain().logs("hello-world", options);
    /// ```
    pub fn logs<T, K>(
        self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (DockerChain<C>, impl Stream<Item = LogOutput, Error = Error>), Error = Error>
    where
        T: LogsQueryParams<K>,
        K: AsRef<str>,
    {
        self.inner
            .logs(container_name, options)
            .into_future()
            .map(|(first, rest)| match first {
                Some(head) => (self, EitherStream::A(stream::once(Ok(head)).chain(rest))),
                None => (self, EitherStream::B(stream::empty())),
            })
            .map_err(|(err, _)| err)
    }

    /// ---
    ///
    /// # Container Changes
    ///
    /// Get changes on a container's filesystem. Consumes the client instance.
    ///
    /// # Arguments
    ///
    ///  - Container name as string slice.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and an
    ///  Option of Vector of [Change](container/struct.Change.html) structs, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// docker.chain().container_changes("hello-world");
    /// ```
    pub fn container_changes(
        self,
        container_name: &str,
    ) -> impl Future<Item = (DockerChain<C>, Option<Vec<Change>>), Error = Error> {
        self.inner
            .container_changes(container_name)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # Stats
    ///
    /// Get container stats based on resource usage. Consumes the client instance.
    ///
    /// # Arguments
    ///
    /// - Container name as string slice.
    /// - Optional [Stats Options](container/struct.StatsOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and a
    ///  [Stats](container/struct.Stats.html) struct, wrapped in a Stream.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::StatsOptions;
    ///
    /// let options = Some(StatsOptions{
    ///     stream: false,
    /// });
    ///
    /// docker.chain().stats("hello-world", options);
    /// ```
    pub fn stats<T, K, V>(
        self,
        container_name: &str,
        options: Option<T>,
    ) -> impl Future<Item = (DockerChain<C>, impl Stream<Item = Stats, Error = Error>), Error = Error>
    where
        T: StatsQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.inner
            .stats(container_name, options)
            .into_future()
            .map(|(first, rest)| match first {
                Some(head) => (self, EitherStream::A(stream::once(Ok(head)).chain(rest))),
                None => (self, EitherStream::B(stream::empty())),
            })
            .map_err(|(err, _)| err)
    }

    /// ---
    ///
    /// # Update Container
    ///
    /// Update a container. Consumes the client instance.
    ///
    /// # Arguments
    ///
    ///  - Container name as string slice.
    ///  - [Update Container Options](container/struct.UpdateContainerOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and the unit
    ///  type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::UpdateContainerOptions;
    /// use std::default::Default;
    ///
    /// let config = UpdateContainerOptions {
    ///     memory: Some(314572800),
    ///     memory_swap: Some(314572800),
    ///     ..Default::default()
    /// };
    ///
    /// docker.chain().update_container("postgres", config);
    /// ```
    pub fn update_container(
        self,
        container_name: &str,
        config: UpdateContainerOptions,
    ) -> impl Future<Item = (DockerChain<C>, ()), Error = Error> {
        self.inner
            .update_container(container_name, config)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # Rename Container
    ///
    /// Rename a container. Consumes the client instance.
    ///
    /// # Arguments
    ///
    ///  - Container name as string slice.
    ///  - [Rename Container Options](container/struct.RenameContainerOptions.html) struct
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and the unit
    ///  type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::RenameContainerOptions;
    ///
    /// let required = RenameContainerOptions {
    ///     name: "my_new_container_name"
    /// };
    ///
    /// docker.chain().rename_container("hello-world", required);
    /// ```
    pub fn rename_container<T, K, V>(
        self,
        container_name: &str,
        options: T,
    ) -> impl Future<Item = (DockerChain<C>, ()), Error = Error>
    where
        T: RenameContainerQueryParams<K, V>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        self.inner
            .rename_container(container_name, options)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # Pause Container
    ///
    /// Use the cgroups freezer to suspend all processes in a container. Consumes the client
    /// instance.
    ///
    /// # Arguments
    ///
    ///  - Container name as a string slice.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and the unit
    ///  type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// docker.chain().pause_container("postgres");
    /// ```
    pub fn pause_container(
        self,
        container_name: &str,
    ) -> impl Future<Item = (DockerChain<C>, ()), Error = Error> {
        self.inner
            .pause_container(container_name)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # Unpause Container
    ///
    /// Resume a container which has been paused. Consumes the client instance.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and the unit
    ///  type `()`, wrapped in a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// docker.chain().unpause_container("postgres");
    /// ```
    pub fn unpause_container(
        self,
        container_name: &str,
    ) -> impl Future<Item = (DockerChain<C>, ()), Error = Error> {
        self.inner
            .unpause_container(container_name)
            .map(|result| (self, result))
    }

    /// ---
    ///
    /// # Prune Containers
    ///
    /// Delete stopped containers. Consumes the client instance.
    ///
    /// # Arguments
    ///
    ///  - Optional [Prune Containers Options](container/struct.PruneContainersOptions.html) struct.
    ///
    /// # Returns
    ///
    ///  - A Tuple containing the original [DockerChain](struct.Docker.html) instance, and a
    ///  [PruneContainersResults](container/struct.PruneContainersResults.html) struct, wrapped in
    ///  a Future.
    ///
    /// # Examples
    ///
    /// ```rust,norun
    /// # use bollard::Docker;
    /// # let docker = Docker::connect_with_http_defaults().unwrap();
    ///
    /// use bollard::container::PruneContainersOptions;
    ///
    /// use std::collections::HashMap;
    ///
    /// let mut filters = HashMap::new();
    /// filters.insert("until", vec!("10m"));
    ///
    /// let options = Some(PruneContainersOptions {
    ///   filters: filters
    /// });
    ///
    /// docker.chain().prune_containers(options);
    /// ```
    pub fn prune_containers<T, K>(
        self,
        options: Option<T>,
    ) -> impl Future<Item = (DockerChain<C>, PruneContainersResults), Error = Error>
    where
        T: PruneContainersQueryParams<K>,
        K: AsRef<str> + Eq + Hash,
    {
        self.inner
            .prune_containers(options)
            .map(|result| (self, result))
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use hyper_mock::HostToReplyConnector;
    use tokio::runtime::Runtime;

    #[test]
    fn test_create_container() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();
        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 89\r\n\r\n{\"Id\":\"696ce476e95d5122486cac5a446280c56aa0b02617690936e25243195992d3cc\",\"Warnings\":null}\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let options = Some(CreateContainerOptions {
            name: "unit-test".to_string(),
        });

        let config = Config {
            image: Some("hello-world"),
            ..Default::default()
        };

        let results = docker.create_container(options, config);

        let future = results.map(|result| {
            assert_eq!(
                result.id,
                "696ce476e95d5122486cac5a446280c56aa0b02617690936e25243195992d3cc".to_string()
            )
        });

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_start_container() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();
        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 0\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let results = docker.start_container("hello-world", None::<StartContainerOptions<String>>);

        let future = results.map(|_| assert!(true));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_stop_container() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();
        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 0\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let results = docker.stop_container("hello-world", None::<StopContainerOptions>);

        let future = results
            .map_err(|e| panic!("error = {:?}", e))
            .map(|_| assert!(true));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_remove_container() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();
        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 0\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let options = Some(RemoveContainerOptions {
            force: true,
            ..Default::default()
        });

        let results = docker.remove_container("hello-world", options);

        let future = results.map(|_| assert!(true));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_wait_container() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();
        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 33\r\n\r\n{\"Error\":null,\"StatusCode\":0}\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let options = Some(WaitContainerOptions {
            condition: String::from("not-running"),
        });

        let stream = docker.wait_container("hello-world", options);

        let future = stream
            .into_future()
            .map(|result| assert_eq!(0, result.0.unwrap().status_code));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e.0);
                Err(e.0)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_restart_container() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();
        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 0\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let options = Some(RestartContainerOptions { t: 30 });

        let results = docker.restart_container("hello-world", options);

        let future = results.map(|_| assert!(true));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_inspect_container() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();

        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 2596\r\n\r\n{\"Id\":\"156ffa6b4233d93b91dc3185b9de7225c22350d55a6db250549039a7e53efda7\",\"Created\":\"2018-10-06T15:15:43.525300512Z\",\"Path\":\"/usr/sbin/run_uhttpd\",\"Args\":[],\"State\":{\"Status\":\"running\",\"Running\":true,\"Paused\":false,\"Restarting\":false,\"OOMKilled\":false,\"Dead\":false,\"Pid\":28837,\"ExitCode\":0,\"Error\":\"\",\"StartedAt\":\"2018-10-06T15:15:54.444625149Z\",\"FinishedAt\":\"2018-10-06T15:15:53.958358249Z\"},\"Image\":\"sha256:df0db1779d4d71e169756bbcc7757f3d3d8b99032f4022c44509bf9b8f297997\",\"ResolvConfPath\":\"/home/docker/containers/156ffa6b4233d93b91dc3185b9de7225c22350d55a6db250549039a7e53efda7/resolv.conf\",\"HostnamePath\":\"/home/docker/containers/156ffa6b4233d93b91dc3185b9de7225c22350d55a6db250549039a7e53efda7/hostname\",\"HostsPath\":\"/home/docker/containers/156ffa6b4233d93b91dc3185b9de7225c22350d55a6db250549039a7e53efda7/hosts\",\"LogPath\":\"/home/docker/containers/156ffa6b4233d93b91dc3185b9de7225c22350d55a6db250549039a7e53efda7/156ffa6b4233d93b91dc3185b9de7225c22350d55a6db250549039a7e53efda7-json.log\",\"Name\":\"/integration_test_restart_container\",\"RestartCount\":0,\"Driver\":\"overlay2\",\"Platform\":\"linux\",\"MountLabel\":\"\",\"ProcessLabel\":\"\",\"AppArmorProfile\":\"docker-default\",\"ExecIDs\":null,\"HostConfig\":{},\"GraphDriver\":{\"Data\":null,\"Name\":\"overlay2\"},\"Mounts\":[],\"Config\":{\"Hostname\":\"156ffa6b4233\",\"Domainname\":\"\",\"User\":\"\",\"AttachStdin\":false,\"AttachStdout\":false,\"AttachStderr\":false,\"ExposedPorts\":{\"80/tcp\":{}},\"Tty\":false,\"OpenStdin\":false,\"StdinOnce\":false,\"Env\":[],\"Cmd\":null,\"Image\":\"fnichol/uhttpd\",\"Volumes\":{\"/www\":{}},\"WorkingDir\":\"\",\"Entrypoint\":[\"/usr/sbin/run_uhttpd\",\"-f\",\"-p\",\"80\",\"-h\",\"/www\"],\"OnBuild\":null,\"Labels\":{}},\"NetworkSettings\":{\"Bridge\":\"\",\"SandboxID\":\"20cd513ef83bc14934be89953d22aab5a54c7769b07c8e93e90f0227d0aba96b\",\"HairpinMode\":false,\"LinkLocalIPv6Address\":\"\",\"LinkLocalIPv6PrefixLen\":0,\"Ports\":{\"80/tcp\":null},\"SandboxKey\":\"/var/run/docker/netns/20cd513ef83b\",\"SecondaryIPAddresses\":null,\"SecondaryIPv6Addresses\":null,\"EndpointID\":\"992f7e94fd721f627d9d1611c27b477d39b959c209286c38426215ea764f6d63\",\"Gateway\":\"172.17.0.1\",\"GlobalIPv6Address\":\"\",\"GlobalIPv6PrefixLen\":0,\"IPAddress\":\"172.17.0.3\",\"IPPrefixLen\":16,\"IPv6Gateway\":\"\",\"MacAddress\":\"02:42:ac:11:00:03\",\"Networks\":{\"bridge\":{\"IPAMConfig\":null,\"Links\":null,\"Aliases\":null,\"NetworkID\":\"424a1638d72f8984c670bc8bf269102360f24bd356188635ab359cb0b0792b20\",\"EndpointID\":\"992f7e94fd721f627d9d1611c27b477d39b959c209286c38426215ea764f6d63\",\"Gateway\":\"172.17.0.1\",\"IPAddress\":\"172.17.0.3\",\"IPPrefixLen\":16,\"IPv6Gateway\":\"\",\"GlobalIPv6Address\":\"\",\"GlobalIPv6PrefixLen\":0,\"MacAddress\":\"02:42:ac:11:00:03\",\"DriverOpts\":null}}}}\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let results = docker.inspect_container("uhttpd", None::<InspectContainerOptions>);

        let future =
            results.map(|result| assert_eq!(result.path, "/usr/sbin/run_uhttpd".to_string()));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_top_processes() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();

        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 243\r\n\r\n{\"Processes\":[[\"root\",\"3773\",\"0.0\",\"0.0\",\"11056\",\"348\",\"?\",\"Ss\",\"19:42\",\"0:00\",\"/usr/sbin/uhttpd -f -p 80 -h /www /usr/sbin/run_uhttpd -f -p 80 -h /www\"]],\"Titles\":[\"USER\",\"PID\",\"%CPU\",\"%MEM\",\"VSZ\",\"RSS\",\"TTY\",\"STAT\",\"START\",\"TIME\",\"COMMAND\"]}\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let results = docker.top_processes(
            "uhttpd",
            Some(TopOptions {
                ps_args: "aux".to_string(),
            }),
        );

        let future = results.map(|result| assert_eq!(result.titles[0], "USER".to_string()));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_logs() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();

        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 28\r\n\r\n\u{1}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{13}Hello from Docker!\n\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let stream = docker.logs(
            "hello-world",
            Some(LogsOptions {
                stdout: true,
                ..Default::default()
            }),
        );

        let future = stream.into_future().map(|result| {
            assert_eq!(
                format!("{}", result.0.unwrap()),
                "Hello from Docker!".to_string()
            )
        });

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e.0);
                Err(e.0)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_container_changes() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();

        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 4\r\n\r\nnull\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let result = docker.container_changes("hello-world");

        let future = result.map(|result| assert!(result.is_none()));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_stats() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();

        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 1879\r\n\r\n{\"read\":\"2018-10-19T06:11:22.220728356Z\",\"preread\":\"2018-10-19T06:11:21.218466258Z\",\"pids_stats\":{\"current\":1,\"limit\":1000},\"blkio_stats\":{\"io_service_bytes_recursive\":[],\"io_serviced_recursive\":[],\"io_queue_recursive\":[],\"io_service_time_recursive\":[],\"io_wait_time_recursive\":[],\"io_merged_recursive\":[],\"io_time_recursive\":[],\"sectors_recursive\":[]},\"num_procs\":0,\"storage_stats\":{},\"cpu_stats\":{\"cpu_usage\":{\"total_usage\":23097208,\"percpu_usage\":[709093,1595689,5032998,15759428],\"usage_in_kernelmode\":0,\"usage_in_usermode\":10000000},\"system_cpu_usage\":4447677200000000,\"online_cpus\":4,\"throttling_data\":{\"periods\":0,\"throttled_periods\":0,\"throttled_time\":0}},\"precpu_stats\":{\"cpu_usage\":{\"total_usage\":23097208,\"percpu_usage\":[709093,1595689,5032998,15759428],\"usage_in_kernelmode\":0,\"usage_in_usermode\":10000000},\"system_cpu_usage\":4447673150000000,\"online_cpus\":4,\"throttling_data\":{\"periods\":0,\"throttled_periods\":0,\"throttled_time\":0}},\"memory_stats\":{\"usage\":962560,\"max_usage\":5406720,\"stats\":{\"active_anon\":86016,\"active_file\":0,\"cache\":0,\"dirty\":0,\"hierarchical_memory_limit\":9223372036854771712,\"hierarchical_memsw_limit\":0,\"inactive_anon\":0,\"inactive_file\":0,\"mapped_file\":0,\"pgfault\":1485,\"pgmajfault\":0,\"pgpgin\":1089,\"pgpgout\":1084,\"rss\":0,\"rss_huge\":0,\"total_active_anon\":86016,\"total_active_file\":0,\"total_cache\":0,\"total_dirty\":0,\"total_inactive_anon\":0,\"total_inactive_file\":0,\"total_mapped_file\":0,\"total_pgfault\":1485,\"total_pgmajfault\":0,\"total_pgpgin\":1089,\"total_pgpgout\":1084,\"total_rss\":0,\"total_rss_huge\":0,\"total_unevictable\":0,\"total_writeback\":0,\"unevictable\":0,\"writeback\":0},\"limit\":16750219264},\"name\":\"/integration_test_stats\",\"id\":\"66667eab5737dda2da2f578e9496e45c074d1bc5badc0484314f1c3afccfaeb0\",\"networks\":{\"eth0\":{\"rx_bytes\":1635,\"rx_packets\":14,\"rx_errors\":0,\"rx_dropped\":0,\"tx_bytes\":0,\"tx_packets\":0,\"tx_errors\":0,\"tx_dropped\":0}}}\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let stream = docker.stats("hello-world", Some(StatsOptions { stream: false }));

        let future = stream
            .into_future()
            .map(|result| assert_eq!(result.0.unwrap().pids_stats.current.unwrap(), 1));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e.0);
                Err(e.0)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_kill_container() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();
        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 0\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let options = Some(KillContainerOptions {
            signal: "SIGKILL".to_string(),
        });

        let results = docker.kill_container("postgres", options);

        let future = results.map(|_| assert!(true));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_update_container() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();
        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 0\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let config = UpdateContainerOptions {
            memory: Some(314572800),
            memory_swap: Some(314572800),
            ..Default::default()
        };

        let results = docker.update_container("postgres", config);

        let future = results.map(|_| assert!(true));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_rename_container() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();
        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 0\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let options = RenameContainerOptions {
            name: "my_new_container_name".to_string(),
        };

        let results = docker.rename_container("postgres", options);

        let future = results.map(|_| assert!(true));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_pause_container() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();
        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 0\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let results = docker.pause_container("postgres");

        let future = results.map(|_| assert!(true));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_unpause_container() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();
        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 0\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let results = docker.unpause_container("postgres");

        let future = results.map(|_| assert!(true));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }

    #[test]
    fn test_prune_containers() {
        let mut rt = Runtime::new().unwrap();
        let mut connector = HostToReplyConnector::default();
        connector.m.insert(
            format!("{}://5f", if cfg!(windows) { "net.pipe" } else { "unix" }),
            "HTTP/1.1 200 OK\r\nServer: mock1\r\nContent-Type: application/json\r\nContent-Length: 45\r\n\r\n{\"ContainersDeleted\":null,\"SpaceReclaimed\":0}\r\n\r\n".to_string()
        );

        let docker = Docker::connect_with(connector, "_".to_string(), 5).unwrap();

        let results = docker.prune_containers(None::<PruneContainersOptions<String>>);

        let future = results.map(|_| assert!(true));

        rt.block_on(future)
            .or_else(|e| {
                println!("{:?}", e);
                Err(e)
            })
            .unwrap();

        rt.shutdown_now().wait().unwrap();
    }
}