/
docker.cpp
1376 lines (1082 loc) · 39.3 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 <list>
#include <map>
#include <string>
#include <vector>
#include <process/check.hpp>
#include <process/defer.hpp>
#include <process/delay.hpp>
#include <process/io.hpp>
#include <process/reap.hpp>
#include <process/subprocess.hpp>
#include <stout/fs.hpp>
#include <stout/hashmap.hpp>
#include <stout/hashset.hpp>
#include <stout/os.hpp>
#include "common/status_utils.hpp"
#include "docker/docker.hpp"
#ifdef __linux__
#include "linux/cgroups.hpp"
#endif // __linux__
#include "slave/paths.hpp"
#include "slave/slave.hpp"
#include "slave/containerizer/containerizer.hpp"
#include "slave/containerizer/docker.hpp"
#include "slave/containerizer/fetcher.hpp"
#include "slave/containerizer/isolators/cgroups/constants.hpp"
#include "usage/usage.hpp"
using std::list;
using std::map;
using std::string;
using std::vector;
using namespace process;
namespace mesos {
namespace internal {
namespace slave {
using state::SlaveState;
using state::FrameworkState;
using state::ExecutorState;
using state::RunState;
// Declared in header, see explanation there.
// TODO(benh): At some point to run multiple slaves we'll need to make
// the Docker container name creation include the slave ID.
const string DOCKER_NAME_PREFIX = "mesos-";
// Declared in header, see explanation there.
const string DOCKER_SYMLINK_DIRECTORY = "docker/links";
// Parse the ContainerID from a Docker container and return None if
// the container was not launched from Mesos.
Option<ContainerID> parse(const Docker::Container& container)
{
Option<string> name = None();
if (strings::startsWith(container.name, DOCKER_NAME_PREFIX)) {
name = strings::remove(
container.name, DOCKER_NAME_PREFIX, strings::PREFIX);
} else if (strings::startsWith(container.name, "/" + DOCKER_NAME_PREFIX)) {
name = strings::remove(
container.name, "/" + DOCKER_NAME_PREFIX, strings::PREFIX);
}
if (name.isSome()) {
ContainerID id;
id.set_value(name.get());
return id;
}
return None();
}
Try<DockerContainerizer*> DockerContainerizer::create(
const Flags& flags,
Fetcher* fetcher)
{
Try<Docker*> docker = Docker::create(flags.docker);
if (docker.isError()) {
return Error(docker.error());
}
return new DockerContainerizer(
flags,
fetcher,
Shared<Docker>(docker.get()));
}
DockerContainerizer::DockerContainerizer(
const Owned<DockerContainerizerProcess>& _process)
: process(_process)
{
spawn(process.get());
}
DockerContainerizer::DockerContainerizer(
const Flags& flags,
Fetcher* fetcher,
Shared<Docker> docker)
: process(new DockerContainerizerProcess(flags, fetcher, docker))
{
spawn(process.get());
}
DockerContainerizer::~DockerContainerizer()
{
terminate(process.get());
process::wait(process.get());
}
Try<DockerContainerizerProcess::Container*>
DockerContainerizerProcess::Container::create(
const ContainerID& id,
const Option<TaskInfo>& taskInfo,
const ExecutorInfo& executorInfo,
const string& directory,
const Option<string>& user,
const SlaveID& slaveId,
const PID<Slave>& slavePid,
bool checkpoint,
const Flags& flags)
{
// Before we do anything else we first make sure the stdout/stderr
// files exist and have the right file ownership.
Try<Nothing> touch = os::touch(path::join(directory, "stdout"));
if (touch.isError()) {
return Error("Failed to touch 'stdout': " + touch.error());
}
touch = os::touch(path::join(directory, "stderr"));
if (touch.isError()) {
return Error("Failed to touch 'stderr': " + touch.error());
}
if (user.isSome()) {
Try<Nothing> chown = os::chown(user.get(), directory);
if (chown.isError()) {
return Error("Failed to chown: " + chown.error());
}
}
string dockerSymlinkPath = path::join(
paths::getSlavePath(flags.work_dir, slaveId),
DOCKER_SYMLINK_DIRECTORY);
if (!os::exists(dockerSymlinkPath)) {
Try<Nothing> mkdir = os::mkdir(dockerSymlinkPath);
if (mkdir.isError()) {
return Error("Unable to create symlink folder for docker " +
dockerSymlinkPath + ": " + mkdir.error());
}
}
bool symlinked = false;
string containerWorkdir = directory;
// We need to symlink the sandbox directory if the directory
// path has a colon, as Docker CLI uses the colon as a seperator.
if (strings::contains(directory, ":")) {
containerWorkdir = path::join(dockerSymlinkPath, id.value());
Try<Nothing> symlink = ::fs::symlink(directory, containerWorkdir);
if (symlink.isError()) {
return Error("Failed to symlink directory '" + directory +
"' to '" + containerWorkdir + "': " + symlink.error());
}
symlinked = true;
}
return new Container(
id,
taskInfo,
executorInfo,
containerWorkdir,
user,
slaveId,
slavePid,
checkpoint,
symlinked,
flags);
}
Future<Nothing> DockerContainerizerProcess::fetch(
const ContainerID& containerId)
{
CHECK(containers_.contains(containerId));
Container* container = containers_[containerId];
return fetcher->fetch(
containerId,
container->command(),
container->directory,
None(),
flags);
}
Future<Nothing> DockerContainerizerProcess::pull(
const ContainerID& containerId,
const string& directory,
const string& image,
bool forcePullImage)
{
Future<Docker::Image> future = docker->pull(directory, image, forcePullImage);
containers_[containerId]->pull = future;
return future.then(defer(self(), &Self::_pull, image));
}
Future<Nothing> DockerContainerizerProcess::_pull(const string& image)
{
VLOG(1) << "Docker pull " << image << " completed";
return Nothing();
}
Try<Nothing> DockerContainerizerProcess::checkpoint(
const ContainerID& containerId,
pid_t pid)
{
CHECK(containers_.contains(containerId));
Container* container = containers_[containerId];
container->executorPid = pid;
if (container->checkpoint) {
const string& path =
slave::paths::getForkedPidPath(
slave::paths::getMetaRootDir(flags.work_dir),
container->slaveId,
container->executor.framework_id(),
container->executor.executor_id(),
containerId);
LOG(INFO) << "Checkpointing pid " << pid << " to '" << path << "'";
return slave::state::checkpoint(path, stringify(pid));
}
return Nothing();
}
Future<Nothing> DockerContainerizer::recover(
const Option<SlaveState>& state)
{
return dispatch(process.get(), &DockerContainerizerProcess::recover, state);
}
Future<bool> DockerContainerizer::launch(
const ContainerID& containerId,
const ExecutorInfo& executorInfo,
const string& directory,
const Option<string>& user,
const SlaveID& slaveId,
const PID<Slave>& slavePid,
bool checkpoint)
{
return dispatch(
process.get(),
&DockerContainerizerProcess::launch,
containerId,
executorInfo,
directory,
user,
slaveId,
slavePid,
checkpoint);
}
Future<bool> DockerContainerizer::launch(
const ContainerID& containerId,
const TaskInfo& taskInfo,
const ExecutorInfo& executorInfo,
const string& directory,
const Option<string>& user,
const SlaveID& slaveId,
const PID<Slave>& slavePid,
bool checkpoint)
{
return dispatch(
process.get(),
&DockerContainerizerProcess::launch,
containerId,
taskInfo,
executorInfo,
directory,
user,
slaveId,
slavePid,
checkpoint);
}
Future<Nothing> DockerContainerizer::update(
const ContainerID& containerId,
const Resources& resources)
{
return dispatch(
process.get(),
&DockerContainerizerProcess::update,
containerId,
resources);
}
Future<ResourceStatistics> DockerContainerizer::usage(
const ContainerID& containerId)
{
return dispatch(
process.get(),
&DockerContainerizerProcess::usage,
containerId);
}
Future<containerizer::Termination> DockerContainerizer::wait(
const ContainerID& containerId)
{
return dispatch(
process.get(),
&DockerContainerizerProcess::wait,
containerId);
}
void DockerContainerizer::destroy(const ContainerID& containerId)
{
dispatch(
process.get(),
&DockerContainerizerProcess::destroy,
containerId, true);
}
Future<hashset<ContainerID>> DockerContainerizer::containers()
{
return dispatch(process.get(), &DockerContainerizerProcess::containers);
}
// A Subprocess async-safe "setup" helper used by
// DockerContainerizerProcess when launching the mesos-executor that
// does a 'setsid' and then synchronizes with the parent.
static int setup(const string& directory)
{
// Put child into its own process session to prevent slave suicide
// on child process SIGKILL/SIGTERM.
if (::setsid() == -1) {
return errno;
}
// Run the process in the specified directory.
if (!directory.empty()) {
if (::chdir(directory.c_str()) == -1) {
return errno;
}
}
// Synchronize with parent process by reading a byte from stdin.
char c;
ssize_t length;
while ((length = read(STDIN_FILENO, &c, sizeof(c))) == -1 && errno == EINTR);
if (length != sizeof(c)) {
// This will occur if the slave terminates during executor launch.
// There's a reasonable probability this will occur during slave
// restarts across a large/busy cluster.
ABORT("Failed to synchronize with slave (it has probably exited)");
}
return 0;
}
Future<Nothing> DockerContainerizerProcess::recover(
const Option<SlaveState>& state)
{
LOG(INFO) << "Recovering Docker containers";
if (state.isSome()) {
// Collection of pids that we've started reaping in order to
// detect very unlikely duplicate scenario (see below).
hashmap<ContainerID, pid_t> pids;
foreachvalue (const FrameworkState& framework, state.get().frameworks) {
foreachvalue (const ExecutorState& executor, framework.executors) {
if (executor.info.isNone()) {
LOG(WARNING) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its info could not be recovered";
continue;
}
if (executor.latest.isNone()) {
LOG(WARNING) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its latest run could not be recovered";
continue;
}
// We are only interested in the latest run of the executor!
const ContainerID& containerId = executor.latest.get();
Option<RunState> run = executor.runs.get(containerId);
CHECK_SOME(run);
CHECK_SOME(run.get().id);
CHECK_EQ(containerId, run.get().id.get());
// We need the pid so the reaper can monitor the executor so
// skip this executor if it's not present. This is not an
// error because the slave will try to wait on the container
// which will return a failed Termination and everything will
// get cleaned up.
if (!run.get().forkedPid.isSome()) {
continue;
}
if (run.get().completed) {
VLOG(1) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its latest run "
<< containerId << " is completed";
continue;
}
LOG(INFO) << "Recovering container '" << containerId
<< "' for executor '" << executor.id
<< "' of framework " << framework.id;
// Create and store a container.
Container* container = new Container(containerId);
containers_[containerId] = container;
container->state = Container::RUNNING;
pid_t pid = run.get().forkedPid.get();
container->status.set(process::reap(pid));
container->status.future().get()
.onAny(defer(self(), &Self::reaped, containerId));
if (pids.containsValue(pid)) {
// This should (almost) never occur. There is the
// possibility that a new executor is launched with the same
// pid as one that just exited (highly unlikely) and the
// slave dies after the new executor is launched but before
// it hears about the termination of the earlier executor
// (also unlikely).
return Failure(
"Detected duplicate pid " + stringify(pid) +
" for container " + stringify(containerId));
}
pids.put(containerId, pid);
}
}
}
// Get the list of all Docker containers (running and exited) in
// order to remove any orphans.
return docker->ps(true, DOCKER_NAME_PREFIX)
.then(defer(self(), &Self::_recover, lambda::_1));
}
Future<Nothing> DockerContainerizerProcess::_recover(
const list<Docker::Container>& _containers)
{
foreach (const Docker::Container& container, _containers) {
VLOG(1) << "Checking if Docker container named '"
<< container.name << "' was started by Mesos";
Option<ContainerID> id = parse(container);
// Ignore containers that Mesos didn't start.
if (id.isNone()) {
continue;
}
VLOG(1) << "Checking if Mesos container with ID '"
<< stringify(id.get()) << "' has been orphaned";
// Check if we're watching an executor for this container ID and
// if not, rm -f the Docker container.
if (!containers_.contains(id.get())) {
// TODO(tnachen): Consider using executor_shutdown_grace_period.
docker->stop(container.id, flags.docker_stop_timeout, true);
}
}
return Nothing();
}
Future<bool> DockerContainerizerProcess::launch(
const ContainerID& containerId,
const TaskInfo& taskInfo,
const ExecutorInfo& executorInfo,
const string& directory,
const Option<string>& user,
const SlaveID& slaveId,
const PID<Slave>& slavePid,
bool checkpoint)
{
if (containers_.contains(containerId)) {
return Failure("Container already started");
}
if (!taskInfo.has_container()) {
LOG(INFO) << "No container info found, skipping launch";
return false;
}
ContainerInfo containerInfo = taskInfo.container();
if (containerInfo.type() != ContainerInfo::DOCKER) {
LOG(INFO) << "Skipping non-docker container";
return false;
}
Try<Container*> container = Container::create(
containerId,
taskInfo,
executorInfo,
directory,
user,
slaveId,
slavePid,
checkpoint,
flags);
if (container.isError()) {
return Failure("Failed to create container: " + container.error());
}
containers_[containerId] = container.get();
LOG(INFO) << "Starting container '" << containerId
<< "' for task '" << taskInfo.task_id()
<< "' (and executor '" << executorInfo.executor_id()
<< "') of framework '" << executorInfo.framework_id() << "'";
return fetch(containerId)
.then(defer(self(), &Self::_launch, containerId))
.then(defer(self(), &Self::__launch, containerId))
.then(defer(self(), &Self::___launch, containerId))
.then(defer(self(), &Self::______launch, containerId, lambda::_1))
.onFailed(defer(self(), &Self::destroy, containerId, true));
}
Future<Nothing> DockerContainerizerProcess::_launch(
const ContainerID& containerId)
{
// Doing the fetch might have succeded but we were actually asked to
// destroy the container, which we did, so don't continue.
if (!containers_.contains(containerId)) {
return Failure("Container was destroyed while launching");
}
Container* container = containers_[containerId];
container->state = Container::PULLING;
return pull(
containerId,
container->directory,
container->image(),
container->forcePullImage());
}
Future<Nothing> DockerContainerizerProcess::__launch(
const ContainerID& containerId)
{
if (!containers_.contains(containerId)) {
return Failure("Container was destroyed while pulling image");
}
Container* container = containers_[containerId];
container->state = Container::RUNNING;
// Try and start the Docker container.
return container->run = docker->run(
container->container(),
container->command(),
container->name(),
container->directory,
flags.docker_sandbox_directory,
container->resources,
container->environment());
}
Future<pid_t> DockerContainerizerProcess::___launch(
const ContainerID& containerId)
{
// After we do Docker::run we shouldn't remove a container until
// after we set Container::status.
CHECK(containers_.contains(containerId));
Container* container = containers_[containerId];
// Prepare environment variables for the executor.
map<string, string> environment = executorEnvironment(
container->executor,
container->directory,
container->slaveId,
container->slavePid,
container->checkpoint,
flags.recovery_timeout);
// Include any enviroment variables from ExecutorInfo.
foreach (const Environment::Variable& variable,
container->executor.command().environment().variables()) {
environment[variable.name()] = variable.value();
}
// Construct the mesos-executor "override" to do a 'docker wait'
// using the "name" we gave the container (to distinguish it from
// Docker containers not created by Mesos). Note, however, that we
// don't want the exit status from 'docker wait' but rather the exit
// status from the container, hence the use of /bin/bash.
string override =
"/bin/sh -c 'exit `" + flags.docker + " wait " + container->name() + "`'";
Try<Subprocess> s = subprocess(
container->executor.command().value() + " --override " + override,
Subprocess::PIPE(),
Subprocess::PATH(path::join(container->directory, "stdout")),
Subprocess::PATH(path::join(container->directory, "stderr")),
environment,
lambda::bind(&setup, container->directory));
if (s.isError()) {
return Failure("Failed to fork executor: " + s.error());
}
// Checkpoint the executor's pid (if necessary).
Try<Nothing> checkpointed = checkpoint(containerId, s.get().pid());
if (checkpointed.isError()) {
// Close the subprocess's stdin so that it aborts.
CHECK_SOME(s.get().in());
os::close(s.get().in().get());
return Failure(
"Failed to checkpoint executor's pid: " + checkpointed.error());
}
// Checkpoing complete, now synchronize with the process so that it
// can continue to execute.
CHECK_SOME(s.get().in());
char c;
ssize_t length;
while ((length = write(s.get().in().get(), &c, sizeof(c))) == -1 &&
errno == EINTR);
if (length != sizeof(c)) {
string error = string(strerror(errno));
os::close(s.get().in().get());
return Failure("Failed to synchronize with child process: " + error);
}
return s.get().pid();
}
Future<bool> DockerContainerizerProcess::launch(
const ContainerID& containerId,
const ExecutorInfo& executorInfo,
const string& directory,
const Option<string>& user,
const SlaveID& slaveId,
const PID<Slave>& slavePid,
bool checkpoint)
{
if (containers_.contains(containerId)) {
return Failure("Container already started");
}
if (!executorInfo.has_container()) {
LOG(INFO) << "No container info found, skipping launch";
return false;
}
ContainerInfo containerInfo = executorInfo.container();
if (containerInfo.type() != ContainerInfo::DOCKER) {
LOG(INFO) << "Skipping non-docker container";
return false;
}
Try<Container*> container = Container::create(
containerId,
None(),
executorInfo,
directory,
user,
slaveId,
slavePid,
checkpoint,
flags);
if (container.isError()) {
return Failure("Failed to create container: " + container.error());
}
containers_[containerId] = container.get();
LOG(INFO) << "Starting container '" << containerId
<< "' for executor '" << executorInfo.executor_id()
<< "' and framework '" << executorInfo.framework_id() << "'";
return fetch(containerId)
.then(defer(self(), &Self::_launch, containerId))
.then(defer(self(), &Self::__launch, containerId))
.then(defer(self(), &Self::____launch, containerId))
.then(defer(self(), &Self::_____launch, containerId, lambda::_1))
.then(defer(self(), &Self::______launch, containerId, lambda::_1))
.onFailed(defer(self(), &Self::destroy, containerId, true));
}
Future<Docker::Container> DockerContainerizerProcess::____launch(
const ContainerID& containerId)
{
// After we do Docker::run we shouldn't remove a container until
// after we set Container::status.
CHECK(containers_.contains(containerId));
Container* container = containers_[containerId];
return docker->inspect(container->name());
}
Future<pid_t> DockerContainerizerProcess::_____launch(
const ContainerID& containerId,
const Docker::Container& container)
{
// After we do Docker::run we shouldn't remove a container until
// after we set Container::status.
CHECK(containers_.contains(containerId));
Option<int> pid = container.pid;
if (!pid.isSome()) {
return Failure("Unable to get executor pid after launch");
}
// TODO(tnachen): We might not be able to checkpoint if the slave
// dies before it can checkpoint while the executor is still
// running. Optinally we can consider recording the slave id and
// executor id as part of the docker container name so we can
// recover from this.
Try<Nothing> checkpointed = checkpoint(containerId, pid.get());
if (checkpointed.isError()) {
return Failure(
"Failed to checkpoint executor's pid: " + checkpointed.error());
}
return pid.get();
}
Future<bool> DockerContainerizerProcess::______launch(
const ContainerID& containerId,
pid_t pid)
{
// After we do Docker::run we shouldn't remove a container until
// after we set 'status', which we do in this function.
CHECK(containers_.contains(containerId));
Container* container = containers_[containerId];
// And finally watch for when the container gets reaped.
container->status.set(process::reap(pid));
container->status.future().get()
.onAny(defer(self(), &Self::reaped, containerId));
// TODO(benh): Check failure of Docker::logs.
docker->logs(container->name(), container->directory);
return true;
}
Future<Nothing> DockerContainerizerProcess::update(
const ContainerID& containerId,
const Resources& _resources)
{
if (!containers_.contains(containerId)) {
LOG(WARNING) << "Ignoring updating unknown container: "
<< containerId;
return Nothing();
}
Container* container = containers_[containerId];
if (container->state == Container::DESTROYING) {
LOG(INFO) << "Ignoring updating container '" << containerId
<< "' that is being destroyed";
return Nothing();
}
if (container->resources == _resources) {
LOG(INFO) << "Ignoring updating container '" << containerId
<< "' with resources passed to update is identical to "
<< "existing resources";
return Nothing();
}
// Store the resources for usage().
container->resources = _resources;
#ifdef __linux__
if (!_resources.cpus().isSome() && !_resources.mem().isSome()) {
LOG(WARNING) << "Ignoring update as no supported resources are present";
return Nothing();
}
// Skip inspecting the docker container if we already have the pid.
if (container->pid.isSome()) {
return __update(containerId, _resources, container->pid.get());
}
return docker->inspect(containers_[containerId]->name())
.then(defer(self(), &Self::_update, containerId, _resources, lambda::_1));
#else
return Nothing();
#endif // __linux__
}
Future<Nothing> DockerContainerizerProcess::_update(
const ContainerID& containerId,
const Resources& _resources,
const Docker::Container& container)
{
if (container.pid.isNone()) {
return Nothing();
}
if (!containers_.contains(containerId)) {
LOG(INFO) << "Container has been removed after docker inspect, "
<< "skipping update";
return Nothing();
}
containers_[containerId]->pid = container.pid.get();
return __update(containerId, _resources, container.pid.get());
}
Future<Nothing> DockerContainerizerProcess::__update(
const ContainerID& containerId,
const Resources& _resources,
pid_t pid)
{
#ifdef __linux__
// Determine the the cgroups hierarchies where the 'cpu' and
// 'memory' subsystems are mounted (they may be the same). Note that
// we make these static so we can reuse the result for subsequent
// calls.
static Result<string> cpuHierarchy = cgroups::hierarchy("cpu");
static Result<string> memoryHierarchy = cgroups::hierarchy("memory");
if (cpuHierarchy.isError()) {
return Failure("Failed to determine the cgroup hierarchy "
"where the 'cpu' subsystem is mounted: " +
cpuHierarchy.error());
}
if (memoryHierarchy.isError()) {
return Failure("Failed to determine the cgroup hierarchy "
"where the 'memory' subsystem is mounted: " +
memoryHierarchy.error());
}
// We need to find the cgroup(s) this container is currently running
// in for both the hierarchy with the 'cpu' subsystem attached and
// the hierarchy with the 'memory' subsystem attached so we can
// update the proper cgroup control files.
// Determine the cgroup for the 'cpu' subsystem (based on the
// container's pid).
Result<string> cpuCgroup = cgroups::cpu::cgroup(pid);
if (cpuCgroup.isError()) {
return Failure("Failed to determine cgroup for the 'cpu' subsystem: " +
cpuCgroup.error());
} else if (cpuCgroup.isNone()) {
LOG(WARNING) << "Container " << containerId
<< " does not appear to be a member of a cgroup "
<< "where the 'cpu' subsystem is mounted";
}
// And update the CPU shares (if applicable).
if (cpuHierarchy.isSome() &&
cpuCgroup.isSome() &&
_resources.cpus().isSome()) {
double cpuShares = _resources.cpus().get();
uint64_t shares =
std::max((uint64_t) (CPU_SHARES_PER_CPU * cpuShares), MIN_CPU_SHARES);
Try<Nothing> write =
cgroups::cpu::shares(cpuHierarchy.get(), cpuCgroup.get(), shares);
if (write.isError()) {
return Failure("Failed to update 'cpu.shares': " + write.error());
}
LOG(INFO) << "Updated 'cpu.shares' to " << shares
<< " at " << path::join(cpuHierarchy.get(), cpuCgroup.get())
<< " for container " << containerId;
}
// Now determine the cgroup for the 'memory' subsystem.
Result<string> memoryCgroup = cgroups::memory::cgroup(pid);
if (memoryCgroup.isError()) {
return Failure("Failed to determine cgroup for the 'memory' subsystem: " +
memoryCgroup.error());
} else if (memoryCgroup.isNone()) {
LOG(WARNING) << "Container " << containerId
<< " does not appear to be a member of a cgroup "
<< "where the 'memory' subsystem is mounted";
}
// And update the memory limits (if applicable).
if (memoryHierarchy.isSome() &&
memoryCgroup.isSome() &&
_resources.mem().isSome()) {
// TODO(tnachen): investigate and handle OOM with docker.
Bytes mem = _resources.mem().get();
Bytes limit = std::max(mem, MIN_MEMORY);
// Always set the soft limit.
Try<Nothing> write =
cgroups::memory::soft_limit_in_bytes(
memoryHierarchy.get(), memoryCgroup.get(), limit);
if (write.isError()) {
return Failure("Failed to set 'memory.soft_limit_in_bytes': " +
write.error());
}