/
docker.cpp
executable file
·1481 lines (1192 loc) · 41.9 KB
/
docker.cpp
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <map>
#include <vector>
#include <stout/error.hpp>
#include <stout/foreach.hpp>
#include <stout/json.hpp>
#include <stout/lambda.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/result.hpp>
#include <stout/strings.hpp>
#include <stout/stringify.hpp>
#include <stout/os/killtree.hpp>
#include <stout/os/read.hpp>
#include <process/check.hpp>
#include <process/collect.hpp>
#include <process/io.hpp>
#include "common/status_utils.hpp"
#include "docker/docker.hpp"
#ifdef __linux__
#include "linux/cgroups.hpp"
#endif // __linux__
#include "slave/containerizer/mesos/isolators/cgroups/cpushare.hpp"
#include "slave/containerizer/mesos/isolators/cgroups/mem.hpp"
#include "slave/constants.hpp"
using namespace mesos;
using namespace mesos::internal::slave;
using namespace process;
using std::list;
using std::map;
using std::string;
using std::vector;
template <typename T>
static Future<T> failure(
const string& cmd,
int status,
const string& err)
{
return Failure(
"Failed to run '" + cmd + "': " + WSTRINGIFY(status) +
"; stderr='" + err + "'");
}
static Future<Nothing> _checkError(const string& cmd, const Subprocess& s)
{
Option<int> status = s.status().get();
if (status.isNone()) {
return Failure("No status found for '" + cmd + "'");
}
if (status.get() != 0) {
// TODO(tnachen): Consider returning stdout as well.
CHECK_SOME(s.err());
return io::read(s.err().get())
.then(lambda::bind(failure<Nothing>, cmd, status.get(), lambda::_1));
}
return Nothing();
}
// Returns a failure if no status or non-zero status returned from
// subprocess.
static Future<Nothing> checkError(const string& cmd, const Subprocess& s)
{
return s.status()
.then(lambda::bind(_checkError, cmd, s));
}
Try<Owned<Docker>> Docker::create(
const string& path,
const string& socket,
bool validate,
const Option<JSON::Object>& config)
{
if (!strings::startsWith(socket, "/")) {
return Error("Invalid Docker socket path: " + socket);
}
Owned<Docker> docker(new Docker(path, socket, config));
if (!validate) {
return docker;
}
#ifdef __linux__
// Make sure that cgroups are mounted, and at least the 'cpu'
// subsystem is attached.
Result<string> hierarchy = cgroups::hierarchy("cpu");
if (hierarchy.isNone()) {
return Error("Failed to find a mounted cgroups hierarchy "
"for the 'cpu' subsystem; you probably need "
"to mount cgroups manually");
}
#endif // __linux__
Try<Nothing> validateVersion = docker->validateVersion(Version(1, 0, 0));
if (validateVersion.isError()) {
return Error(validateVersion.error());
}
return docker;
}
void commandDiscarded(const Subprocess& s, const string& cmd)
{
VLOG(1) << "'" << cmd << "' is being discarded";
os::killtree(s.pid(), SIGKILL);
}
Future<Version> Docker::version() const
{
string cmd = path + " -H " + socket + " --version";
Try<Subprocess> s = subprocess(
cmd,
Subprocess::PATH("/dev/null"),
Subprocess::PIPE(),
Subprocess::PIPE());
if (s.isError()) {
return Failure("Failed to create subprocess '" + cmd + "': " + s.error());
}
return s.get().status()
.then(lambda::bind(&Docker::_version, cmd, s.get()));
}
Future<Version> Docker::_version(const string& cmd, const Subprocess& s)
{
const Option<int>& status = s.status().get();
if (status.isNone() || status.get() != 0) {
string msg = "Failed to execute '" + cmd + "': ";
if (status.isSome()) {
msg += WSTRINGIFY(status.get());
} else {
msg += "unknown exit status";
}
return Failure(msg);
}
CHECK_SOME(s.out());
return io::read(s.out().get())
.then(lambda::bind(&Docker::__version, lambda::_1));
}
Future<Version> Docker::__version(const Future<string>& output)
{
vector<string> parts = strings::split(output.get(), ",");
if (!parts.empty()) {
vector<string> subParts = strings::split(parts.front(), " ");
if (!subParts.empty()) {
// Docker version output in Fedora 22 is "x.x.x.fc22" which does not match
// the Semantic Versioning specification(<major>[.<minor>[.<patch>]]). We
// remove the overflow components here before parsing the docker version
// output to a Version struct.
string versionString = subParts.back();
vector<string> components = strings::split(versionString, ".");
if (components.size() > 3) {
components.erase(components.begin() + 3, components.end());
}
versionString = strings::join(".", components);
Try<Version> version = Version::parse(versionString);
if (version.isError()) {
return Failure("Failed to parse docker version: " +
version.error());
}
return version;
}
}
return Failure("Unable to find docker version in output");
}
Try<Nothing> Docker::validateVersion(const Version& minVersion) const
{
// Validate the version (and that we can use Docker at all).
Future<Version> version = this->version();
if (!version.await(DOCKER_VERSION_WAIT_TIMEOUT)) {
return Error("Timed out getting docker version");
}
if (version.isFailed()) {
return Error("Failed to get docker version: " + version.failure());
}
if (version.get() < minVersion) {
string msg = "Insufficient version '" + stringify(version.get()) +
"' of Docker. Please upgrade to >=' " +
stringify(minVersion) + "'";
return Error(msg);
}
return Nothing();
}
// TODO(josephw): Parse this string with a protobuf.
Try<Docker::Container> Docker::Container::create(const string& output)
{
Try<JSON::Array> parse = JSON::parse<JSON::Array>(output);
if (parse.isError()) {
return Error("Failed to parse JSON: " + parse.error());
}
// TODO(benh): Handle the case where the short container ID was
// not sufficiently unique and 'array.values.size() > 1'.
JSON::Array array = parse.get();
if (array.values.size() != 1) {
return Error("Failed to find container");
}
CHECK(array.values.front().is<JSON::Object>());
JSON::Object json = array.values.front().as<JSON::Object>();
Result<JSON::String> idValue = json.find<JSON::String>("Id");
if (idValue.isNone()) {
return Error("Unable to find Id in container");
} else if (idValue.isError()) {
return Error("Error finding Id in container: " + idValue.error());
}
string id = idValue.get().value;
Result<JSON::String> nameValue = json.find<JSON::String>("Name");
if (nameValue.isNone()) {
return Error("Unable to find Name in container");
} else if (nameValue.isError()) {
return Error("Error finding Name in container: " + nameValue.error());
}
string name = nameValue.get().value;
Result<JSON::Object> stateValue = json.find<JSON::Object>("State");
if (stateValue.isNone()) {
return Error("Unable to find State in container");
} else if (stateValue.isError()) {
return Error("Error finding State in container: " + stateValue.error());
}
Result<JSON::Number> pidValue = stateValue.get().find<JSON::Number>("Pid");
if (pidValue.isNone()) {
return Error("Unable to find Pid in State");
} else if (pidValue.isError()) {
return Error("Error finding Pid in State: " + pidValue.error());
}
pid_t pid = pid_t(pidValue.get().as<int64_t>());
Option<pid_t> optionalPid;
if (pid != 0) {
optionalPid = pid;
}
Result<JSON::String> startedAtValue =
stateValue.get().find<JSON::String>("StartedAt");
if (startedAtValue.isNone()) {
return Error("Unable to find StartedAt in State");
} else if (startedAtValue.isError()) {
return Error("Error finding StartedAt in State: " + startedAtValue.error());
}
bool started = startedAtValue.get().value != "0001-01-01T00:00:00Z";
Option<string> ipAddress;
bool findDeprecatedIP = false;
Result<JSON::String> networkMode =
json.find<JSON::String>("HostConfig.NetworkMode");
if (!networkMode.isSome()) {
// We need to fail back to the old field as Docker added NetworkMode
// since Docker remote API 1.15.
VLOG(1) << "Unable to detect HostConfig.NetworkMode, "
<< "attempting deprecated IP field";
findDeprecatedIP = true;
} else {
// We currently rely on the fact that we always set --net when
// we shell out to docker run, and therefore the network mode
// matches what --net is. Without --net, the network mode would be set
// to 'default' and we won't be able to find the IP address as
// it will be in 'Networks.bridge' key.
string addressLocation = "NetworkSettings.Networks." +
networkMode->value + ".IPAddress";
Result<JSON::String> ipAddressValue =
json.find<JSON::String>(addressLocation);
if (!ipAddressValue.isSome()) {
// We also need to failback to the old field as the IP Address
// field location also changed since Docker remote API 1.20.
VLOG(1) << "Unable to detect IP Address at '" << addressLocation << "',"
<< " attempting deprecated field";
findDeprecatedIP = true;
} else if (!ipAddressValue->value.empty()) {
ipAddress = ipAddressValue->value;
}
}
if (findDeprecatedIP) {
Result<JSON::String> ipAddressValue =
json.find<JSON::String>("NetworkSettings.IPAddress");
if (ipAddressValue.isNone()) {
return Error("Unable to find NetworkSettings.IPAddress in container");
} else if (ipAddressValue.isError()) {
return Error(
"Error finding NetworkSettings.IPAddress in container: " +
ipAddressValue.error());
} else if (!ipAddressValue->value.empty()) {
ipAddress = ipAddressValue->value;
}
}
vector<Device> devices;
Result<JSON::Array> devicesArray =
json.find<JSON::Array>("HostConfig.Devices");
if (devicesArray.isError()) {
return Error("Failed to parse HostConfig.Devices: " + devicesArray.error());
}
if (devicesArray.isSome()) {
foreach (const JSON::Value& entry, devicesArray->values) {
if (!entry.is<JSON::Object>()) {
return Error("Malformed HostConfig.Devices"
" entry '" + stringify(entry) + "'");
}
JSON::Object object = entry.as<JSON::Object>();
Result<JSON::String> hostPath =
object.at<JSON::String>("PathOnHost");
Result<JSON::String> containerPath =
object.at<JSON::String>("PathInContainer");
Result<JSON::String> permissions =
object.at<JSON::String>("CgroupPermissions");
if (!hostPath.isSome() ||
!containerPath.isSome() ||
!permissions.isSome()) {
return Error("Malformed HostConfig.Devices entry"
" '" + stringify(object) + "'");
}
Device device;
device.hostPath = Path(hostPath->value);
device.containerPath = Path(containerPath->value);
device.access.read = strings::contains(permissions->value, "r");
device.access.write = strings::contains(permissions->value, "w");
device.access.mknod = strings::contains(permissions->value, "m");
devices.push_back(device);
}
}
return Container(output, id, name, optionalPid, started, ipAddress, devices);
}
Try<Docker::Image> Docker::Image::create(const JSON::Object& json)
{
Result<JSON::Value> entrypoint =
json.find<JSON::Value>("ContainerConfig.Entrypoint");
if (entrypoint.isError()) {
return Error("Failed to find 'ContainerConfig.Entrypoint': " +
entrypoint.error());
} else if (entrypoint.isNone()) {
return Error("Unable to find 'ContainerConfig.Entrypoint'");
}
Option<vector<string>> entrypointOption = None();
if (!entrypoint.get().is<JSON::Null>()) {
if (!entrypoint.get().is<JSON::Array>()) {
return Error("Unexpected type found for 'ContainerConfig.Entrypoint'");
}
const vector<JSON::Value>& values =
entrypoint.get().as<JSON::Array>().values;
if (values.size() != 0) {
vector<string> result;
foreach (const JSON::Value& value, values) {
if (!value.is<JSON::String>()) {
return Error("Expecting entrypoint value to be type string");
}
result.push_back(value.as<JSON::String>().value);
}
entrypointOption = result;
}
}
Result<JSON::Value> env =
json.find<JSON::Value>("ContainerConfig.Env");
if (env.isError()) {
return Error("Failed to find 'ContainerConfig.Env': " +
env.error());
} else if (env.isNone()) {
return Error("Unable to find 'ContainerConfig.Env'");
}
Option<map<string, string>> envOption = None();
if (!env.get().is<JSON::Null>()) {
if (!env.get().is<JSON::Array>()) {
return Error("Unexpected type found for 'ContainerConfig.Env'");
}
const vector<JSON::Value>& values = env.get().as<JSON::Array>().values;
if (values.size() != 0) {
map<string, string> result;
foreach (const JSON::Value& value, values) {
if (!value.is<JSON::String>()) {
return Error("Expecting environment value to be type string");
}
const vector<string> tokens =
strings::split(value.as<JSON::String>().value, "=", 2);
if (tokens.size() != 2) {
return Error("Unexpected Env format for 'ContainerConfig.Env'");
}
if (result.count(tokens[0])) {
return Error("Unexpected duplicate environment variables '"
+ tokens[0] + "'");
}
result[tokens[0]] = tokens[1];
}
envOption = result;
}
}
return Docker::Image(entrypointOption, envOption);
}
Future<Option<int>> Docker::run(
const ContainerInfo& containerInfo,
const CommandInfo& commandInfo,
const string& name,
const string& sandboxDirectory,
const string& mappedDirectory,
const Option<Resources>& resources,
const Option<map<string, string>>& env,
const Option<vector<Device>>& devices,
const process::Subprocess::IO& _stdout,
const process::Subprocess::IO& _stderr) const
{
if (!containerInfo.has_docker()) {
return Failure("No docker info found in container info");
}
const ContainerInfo::DockerInfo& dockerInfo = containerInfo.docker();
vector<string> argv;
argv.push_back(path);
argv.push_back("-H");
argv.push_back(socket);
argv.push_back("run");
if (dockerInfo.privileged()) {
argv.push_back("--privileged");
}
if (resources.isSome()) {
// TODO(yifan): Support other resources (e.g. disk).
Option<double> cpus = resources.get().cpus();
if (cpus.isSome()) {
uint64_t cpuShare =
std::max((uint64_t) (CPU_SHARES_PER_CPU * cpus.get()), MIN_CPU_SHARES);
argv.push_back("--cpu-shares");
argv.push_back(stringify(cpuShare));
}
Option<Bytes> mem = resources.get().mem();
if (mem.isSome()) {
Bytes memLimit = std::max(mem.get(), MIN_MEMORY);
argv.push_back("--memory");
argv.push_back(stringify(memLimit.bytes()));
}
}
if (env.isSome()) {
foreachpair (string key, string value, env.get()) {
argv.push_back("-e");
argv.push_back(key + "=" + value);
}
}
foreach (const Environment::Variable& variable,
commandInfo.environment().variables()) {
if (env.isSome() &&
env.get().find(variable.name()) != env.get().end()) {
// Skip to avoid duplicate environment variables.
continue;
}
argv.push_back("-e");
argv.push_back(variable.name() + "=" + variable.value());
}
argv.push_back("-e");
argv.push_back("MESOS_SANDBOX=" + mappedDirectory);
argv.push_back("-e");
argv.push_back("MESOS_CONTAINER_NAME=" + name);
Option<string> volumeDriver;
foreach (const Volume& volume, containerInfo.volumes()) {
// The 'container_path' can be either an absolute path or a
// relative path. If it is a relative path, it would be prefixed
// with the container sandbox directory.
string volumeConfig = strings::startsWith(volume.container_path(), "/")
? volume.container_path()
: path::join(mappedDirectory, volume.container_path());
// TODO(gyliu513): Set `host_path` as source.
if (volume.has_host_path()) {
// If both 'host_path' and 'container_path' are relative paths,
// return a failure because the user can just directly access the
// volume in the sandbox.
if (!strings::startsWith(volume.host_path(), "/") &&
!strings::startsWith(volume.container_path(), "/")) {
return Failure(
"Both 'host_path' and 'container_path' of a volume are relative");
}
if (!strings::startsWith(volume.host_path(), "/") &&
!dockerInfo.has_volume_driver()) {
// When volume dirver is empty and host path is a relative path, mapping
// host path from the sandbox.
volumeConfig =
path::join(sandboxDirectory, volume.host_path()) + ":" + volumeConfig;
} else {
volumeConfig = volume.host_path() + ":" + volumeConfig;
}
switch (volume.mode()) {
case Volume::RW: volumeConfig += ":rw"; break;
case Volume::RO: volumeConfig += ":ro"; break;
default: return Failure("Unsupported volume mode");
}
} else if (volume.has_source()) {
if (volume.source().type() != Volume::Source::DOCKER_VOLUME) {
VLOG(1) << "Ignored volume type '" << volume.source().type()
<< "' for container '" << name << "' as only "
<< "'DOCKER_VOLUME' was supported by docker";
continue;
}
volumeConfig = volume.source().docker_volume().name() +
":" + volumeConfig;
if (volume.source().docker_volume().has_driver()) {
const string& currentDriver = volume.source().docker_volume().driver();
if (volumeDriver.isSome() &&
volumeDriver.get() != currentDriver) {
return Failure("Only one volume driver is supported");
}
volumeDriver = currentDriver;
}
switch (volume.mode()) {
case Volume::RW: volumeConfig += ":rw"; break;
case Volume::RO: volumeConfig += ":ro"; break;
default: return Failure("Unsupported volume mode");
}
} else {
return Failure("Host path or volume source is required");
}
argv.push_back("-v");
argv.push_back(volumeConfig);
}
// Mapping sandbox directory into the container mapped directory.
argv.push_back("-v");
argv.push_back(sandboxDirectory + ":" + mappedDirectory);
// TODO(gyliu513): Deprecate this after the release cycle of 1.0.
// It will be replaced by Volume.Source.DockerVolume.driver.
if (dockerInfo.has_volume_driver()) {
if (volumeDriver.isSome() &&
volumeDriver.get() != dockerInfo.volume_driver()) {
return Failure("Only one volume driver per task is supported");
}
volumeDriver = dockerInfo.volume_driver();
}
if (volumeDriver.isSome()) {
argv.push_back("--volume-driver=" + volumeDriver.get());
}
const string& image = dockerInfo.image();
argv.push_back("--net");
string network;
switch (dockerInfo.network()) {
case ContainerInfo::DockerInfo::HOST: network = "host"; break;
case ContainerInfo::DockerInfo::BRIDGE: network = "bridge"; break;
case ContainerInfo::DockerInfo::NONE: network = "none"; break;
case ContainerInfo::DockerInfo::USER: {
// User defined networks require docker version >= 1.9.0.
Try<Nothing> validateVer = validateVersion(Version(1, 9, 0));
if (validateVer.isError()) {
return Failure("User defined networks require Docker "
"version 1.9.0 or higher");
}
if (containerInfo.network_infos_size() == 0) {
return Failure("No network info found in container info");
}
if (containerInfo.network_infos_size() > 1) {
return Failure("Only a single network can be defined in Docker run");
}
const NetworkInfo& networkInfo = containerInfo.network_infos(0);
if(!networkInfo.has_name()){
return Failure("No network name found in network info");
}
network = networkInfo.name();
break;
}
default: return Failure("Unsupported Network mode: " +
stringify(dockerInfo.network()));
}
argv.push_back(network);
if (containerInfo.has_hostname()) {
if (network == "host") {
return Failure("Unable to set hostname with host network mode");
}
argv.push_back("--hostname");
argv.push_back(containerInfo.hostname());
}
foreach (const Parameter& parameter, dockerInfo.parameters()) {
argv.push_back("--" + parameter.key() + "=" + parameter.value());
}
if (dockerInfo.port_mappings().size() > 0) {
if (network == "host" || network == "none" ) {
return Failure("Port mappings are only supported for bridge and "
"user-defined networks");
}
if (!resources.isSome()) {
return Failure("Port mappings require resources");
}
Option<Value::Ranges> portRanges = resources.get().ports();
if (!portRanges.isSome()) {
return Failure("Port mappings require port resources");
}
foreach (const ContainerInfo::DockerInfo::PortMapping& mapping,
dockerInfo.port_mappings()) {
bool found = false;
foreach (const Value::Range& range, portRanges.get().range()) {
if (mapping.host_port() >= range.begin() &&
mapping.host_port() <= range.end()) {
found = true;
break;
}
}
if (!found) {
return Failure("Port [" + stringify(mapping.host_port()) + "] not " +
"included in resources");
}
string portMapping = stringify(mapping.host_port()) + ":" +
stringify(mapping.container_port());
if (mapping.has_protocol()) {
portMapping += "/" + strings::lower(mapping.protocol());
}
argv.push_back("-p");
argv.push_back(portMapping);
}
}
if (devices.isSome()) {
foreach (const Device& device, devices.get()) {
if (!device.hostPath.absolute()) {
return Failure("Device path '" + device.hostPath.string() + "'"
" is not an absolute path");
}
string permissions;
permissions += device.access.read ? "r" : "";
permissions += device.access.write ? "w" : "";
permissions += device.access.mknod ? "m" : "";
// Docker doesn't handle this case (it fails by saying
// that an absolute path is not being provided).
if (permissions.empty()) {
return Failure("At least one access required for --devices:"
" none specified for"
" '" + device.hostPath.string() + "'");
}
// Note that docker silently does not handle default devices
// passed in with restricted permissions (e.g. /dev/null), so
// we don't bother checking this case either.
argv.push_back("--device=" +
device.hostPath.string() + ":" +
device.containerPath.string() + ":" +
permissions);
}
}
if (commandInfo.shell()) {
// We override the entrypoint if shell is enabled because we
// assume the user intends to run the command within /bin/sh
// and not the default entrypoint of the image. View MESOS-1770
// for more details.
argv.push_back("--entrypoint");
argv.push_back("/bin/sh");
}
argv.push_back("--name");
argv.push_back(name);
argv.push_back(image);
if (commandInfo.shell()) {
if (!commandInfo.has_value()) {
return Failure("Shell specified but no command value provided");
}
// Adding -c here because Docker cli only supports a single word
// for overriding entrypoint, so adding the -c flag for /bin/sh
// as part of the command.
argv.push_back("-c");
argv.push_back(commandInfo.value());
} else {
if (commandInfo.has_value()) {
argv.push_back(commandInfo.value());
}
foreach (const string& argument, commandInfo.arguments()) {
argv.push_back(argument);
}
}
string cmd = strings::join(" ", argv);
LOG(INFO) << "Running " << cmd;
map<string, string> environment = os::environment();
// NOTE: This is non-relevant to pick up a docker config file,
// which is necessary for private registry.
environment["HOME"] = sandboxDirectory;
Try<Subprocess> s = subprocess(
path,
argv,
Subprocess::PATH("/dev/null"),
_stdout,
_stderr,
NO_SETSID,
None(),
environment);
if (s.isError()) {
return Failure("Failed to create subprocess '" + cmd + "': " + s.error());
}
s->status()
.onDiscard(lambda::bind(&commandDiscarded, s.get(), cmd));
// Ideally we could capture the stderr when docker itself fails,
// however due to the stderr redirection used here we cannot.
//
// TODO(bmahler): Determine a way to redirect stderr while still
// capturing the stderr when 'docker run' itself fails. E.g. we
// could use 'docker logs' in conjuction with a "detached" form
// of 'docker run' to isolate 'docker run' failure messages from
// the container stderr.
return s->status();
}
Future<Nothing> Docker::stop(
const string& containerName,
const Duration& timeout,
bool remove) const
{
int timeoutSecs = (int) timeout.secs();
if (timeoutSecs < 0) {
return Failure("A negative timeout can not be applied to docker stop: " +
stringify(timeoutSecs));
}
string cmd = path + " -H " + socket + " stop -t " + stringify(timeoutSecs) +
" " + containerName;
VLOG(1) << "Running " << cmd;
Try<Subprocess> s = subprocess(
cmd,
Subprocess::PATH("/dev/null"),
Subprocess::PATH("/dev/null"),
Subprocess::PIPE());
if (s.isError()) {
return Failure("Failed to create subprocess '" + cmd + "': " + s.error());
}
return s.get().status()
.then(lambda::bind(
&Docker::_stop,
*this,
containerName,
cmd,
s.get(),
remove));
}
Future<Nothing> Docker::_stop(
const Docker& docker,
const string& containerName,
const string& cmd,
const Subprocess& s,
bool remove)
{
Option<int> status = s.status().get();
if (remove) {
bool force = !status.isSome() || status.get() != 0;
return docker.rm(containerName, force);
}
return checkError(cmd, s);
}
Future<Nothing> Docker::kill(
const string& containerName,
int signal) const
{
const string cmd =
path + " -H " + socket +
" kill --signal=" + stringify(signal) + " " + containerName;
VLOG(1) << "Running " << cmd;
Try<Subprocess> s = subprocess(
cmd,
Subprocess::PATH("/dev/null"),
Subprocess::PATH("/dev/null"),
Subprocess::PIPE());
if (s.isError()) {
return Failure("Failed to create subprocess '" + cmd + "': " + s.error());
}
return checkError(cmd, s.get());
}
Future<Nothing> Docker::rm(
const string& containerName,
bool force) const
{
// The `-v` flag removes Docker volumes that may be present.
const string cmd =
path + " -H " + socket +
(force ? " rm -f -v " : " rm -v ") + containerName;
VLOG(1) << "Running " << cmd;
Try<Subprocess> s = subprocess(
cmd,
Subprocess::PATH("/dev/null"),
Subprocess::PATH("/dev/null"),
Subprocess::PIPE());
if (s.isError()) {
return Failure("Failed to create subprocess '" + cmd + "': " + s.error());
}
return checkError(cmd, s.get());
}
Future<Docker::Container> Docker::inspect(
const string& containerName,
const Option<Duration>& retryInterval) const
{
Owned<Promise<Docker::Container>> promise(new Promise<Docker::Container>());
const string cmd = path + " -H " + socket + " inspect " + containerName;
_inspect(cmd, promise, retryInterval);
return promise->future();
}
void Docker::_inspect(
const string& cmd,
const Owned<Promise<Docker::Container>>& promise,
const Option<Duration>& retryInterval)
{
if (promise->future().hasDiscard()) {
promise->discard();
return;
}
VLOG(1) << "Running " << cmd;
Try<Subprocess> s = subprocess(
cmd,
Subprocess::PATH("/dev/null"),
Subprocess::PIPE(),
Subprocess::PIPE());
if (s.isError()) {
promise->fail("Failed to create subprocess '" + cmd + "': " + s.error());
return;
}
// Start reading from stdout so writing to the pipe won't block
// to handle cases where the output is larger than the pipe
// capacity.
const Future<string> output = io::read(s.get().out().get());
s.get().status()
.onAny([=]() { __inspect(cmd, promise, retryInterval, output, s.get()); });
}
void Docker::__inspect(
const string& cmd,
const Owned<Promise<Docker::Container>>& promise,
const Option<Duration>& retryInterval,
Future<string> output,
const Subprocess& s)