-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
containerizer.cpp
1961 lines (1604 loc) · 61.2 KB
/
containerizer.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 <set>
#include <mesos/module/isolator.hpp>
#include <mesos/slave/container_logger.hpp>
#include <mesos/slave/isolator.hpp>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/io.hpp>
#include <process/owned.hpp>
#include <process/reap.hpp>
#include <process/subprocess.hpp>
#include <process/metrics/metrics.hpp>
#include <stout/adaptor.hpp>
#include <stout/foreach.hpp>
#include <stout/fs.hpp>
#include <stout/hashmap.hpp>
#include <stout/lambda.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/strings.hpp>
#include "common/protobuf_utils.hpp"
#include "hook/manager.hpp"
#include "module/manager.hpp"
#include "slave/paths.hpp"
#include "slave/slave.hpp"
#include "slave/containerizer/containerizer.hpp"
#include "slave/containerizer/fetcher.hpp"
#include "slave/containerizer/mesos/launcher.hpp"
#ifdef __linux__
#include "slave/containerizer/mesos/linux_launcher.hpp"
#endif // __linux__
#include "slave/containerizer/mesos/isolators/posix.hpp"
#ifdef __WINDOWS__
#include "slave/containerizer/mesos/isolators/windows.hpp"
#endif // __WINDOWS__
#include "slave/containerizer/mesos/isolators/posix/disk.hpp"
#if ENABLE_XFS_DISK_ISOLATOR
#include "slave/containerizer/mesos/isolators/xfs/disk.hpp"
#endif
#ifdef __linux__
#include "slave/containerizer/mesos/isolators/cgroups/cpushare.hpp"
#include "slave/containerizer/mesos/isolators/cgroups/devices.hpp"
#include "slave/containerizer/mesos/isolators/cgroups/mem.hpp"
#include "slave/containerizer/mesos/isolators/cgroups/net_cls.hpp"
#include "slave/containerizer/mesos/isolators/cgroups/perf_event.hpp"
#endif // __linux__
#ifdef __linux__
#include "slave/containerizer/mesos/isolators/docker/runtime.hpp"
#endif // __linux__
#ifdef __linux__
#include "slave/containerizer/mesos/isolators/docker/volume/isolator.hpp"
#endif // __linux__
#ifdef __linux__
#include "slave/containerizer/mesos/isolators/filesystem/linux.hpp"
#endif // __linux__
#include "slave/containerizer/mesos/isolators/filesystem/posix.hpp"
#ifdef __WINDOWS__
#include "slave/containerizer/mesos/isolators/filesystem/windows.hpp"
#endif // __WINDOWS__
#ifdef __linux__
#include "slave/containerizer/mesos/isolators/filesystem/shared.hpp"
#endif // __linux__
#include "slave/containerizer/mesos/isolators/gpu/nvidia.hpp"
#ifdef __linux__
#include "slave/containerizer/mesos/isolators/namespaces/pid.hpp"
#include "slave/containerizer/mesos/isolators/network/cni/cni.hpp"
#endif
#ifdef WITH_NETWORK_ISOLATOR
#include "slave/containerizer/mesos/isolators/network/port_mapping.hpp"
#endif
#include "slave/containerizer/mesos/constants.hpp"
#include "slave/containerizer/mesos/containerizer.hpp"
#include "slave/containerizer/mesos/launch.hpp"
#include "slave/containerizer/mesos/provisioner/provisioner.hpp"
using std::list;
using std::map;
using std::set;
using std::string;
using std::vector;
using namespace process;
namespace mesos {
namespace internal {
namespace slave {
using mesos::modules::ModuleManager;
using mesos::slave::ContainerConfig;
using mesos::slave::ContainerLaunchInfo;
using mesos::slave::ContainerLimitation;
using mesos::slave::ContainerLogger;
using mesos::slave::ContainerState;
using mesos::slave::Isolator;
using state::SlaveState;
using state::FrameworkState;
using state::ExecutorState;
using state::RunState;
Try<MesosContainerizer*> MesosContainerizer::create(
const Flags& flags,
bool local,
Fetcher* fetcher,
const Option<NvidiaComponents>& nvidia)
{
// Modify `flags` based on the deprecated `isolation` flag (and then
// use `flags_` in the rest of this function).
Flags flags_ = flags;
if (flags.isolation == "process") {
LOG(WARNING) << "The 'process' isolation flag is deprecated, "
<< "please update your flags to"
<< " '--isolation=posix/cpu,posix/mem'.";
flags_.isolation = "posix/cpu,posix/mem";
} else if (flags.isolation == "cgroups") {
LOG(WARNING) << "The 'cgroups' isolation flag is deprecated, "
<< "please update your flags to"
<< " '--isolation=cgroups/cpu,cgroups/mem'.";
flags_.isolation = "cgroups/cpu,cgroups/mem";
}
// One and only one filesystem isolator is required. The filesystem
// isolator is responsible for preparing the filesystems for
// containers (e.g., prepare filesystem roots, volumes, etc.). If
// the user does not specify one, 'filesystem/posix' will be used.
//
// TODO(jieyu): Check that only one filesystem isolator is used.
if (!strings::contains(flags_.isolation, "filesystem/")) {
flags_.isolation += ",filesystem/posix";
}
if (strings::contains(flags_.isolation, "posix/disk")) {
LOG(WARNING) << "'posix/disk' has been renamed as 'disk/du', "
<< "please update your --isolation flag to use 'disk/du'";
if (strings::contains(flags_.isolation, "disk/du")) {
return Error(
"Using 'posix/disk' and 'disk/du' simultaneously is disallowed");
}
}
#ifdef __linux__
// One and only one `network` isolator is required. The network
// isolator is responsible for preparing the network namespace for
// containers. If the user does not specify one, 'network/cni'
// isolator will be used.
// TODO(jieyu): Check that only one network isolator is used.
if (!strings::contains(flags_.isolation, "network/")) {
flags_.isolation += ",network/cni";
}
#endif
LOG(INFO) << "Using isolation: " << flags_.isolation;
// Create the container logger for the MesosContainerizer.
Try<ContainerLogger*> logger =
ContainerLogger::create(flags_.container_logger);
if (logger.isError()) {
return Error("Failed to create container logger: " + logger.error());
}
// Create the launcher for the MesosContainerizer.
Try<Launcher*> launcher = [&flags_]() -> Try<Launcher*> {
#ifdef __linux__
if (flags_.launcher.isSome()) {
// If the user has specified the launcher, use it.
if (flags_.launcher.get() == "linux") {
return LinuxLauncher::create(flags_);
} else if (flags_.launcher.get() == "posix") {
return PosixLauncher::create(flags_);
} else {
return Error(
"Unknown or unsupported launcher: " + flags_.launcher.get());
}
}
// Use Linux launcher if it is available, POSIX otherwise.
return LinuxLauncher::available()
? LinuxLauncher::create(flags_)
: PosixLauncher::create(flags_);
#elif __WINDOWS__
// NOTE: Because the most basic launcher historically has been "posix", we
// accept this flag on Windows, but map it to the `WindowsLauncher`.
if (flags_.launcher.isSome() && !(flags_.launcher.get() == "posix" ||
flags_.launcher.get() == "windows")) {
return Error("Unsupported launcher: " + flags_.launcher.get());
}
return WindowsLauncher::create(flags_);
#else
if (flags_.launcher.isSome() && flags_.launcher.get() != "posix") {
return Error("Unsupported launcher: " + flags_.launcher.get());
}
return PosixLauncher::create(flags_);
#endif // __linux__
}();
if (launcher.isError()) {
return Error("Failed to create launcher: " + launcher.error());
}
Try<Owned<Provisioner>> provisioner = Provisioner::create(flags_);
if (provisioner.isError()) {
return Error("Failed to create provisioner: " + provisioner.error());
}
// Create the isolators.
//
// Currently, the order of the entries in the --isolation flag
// specifies the ordering of the isolators. Specifically, the
// `create` and `prepare` calls for each isolator are run serially
// in the order in which they appear in the --isolation flag, while
// the `cleanup` call is serialized in reverse order.
//
// It is the responsibility of each isolator to check its
// dependency requirements (if any) during its `create`
// execution. This means that if the operator specifies the
// flags in the wrong order, it will produce an error during
// isolator creation.
//
// NOTE: We ignore the placement of the filesystem isolator in
// the --isolation flag and place it at the front of the isolator
// list. This is a temporary hack until isolators are able to
// express and validate their ordering requirements.
const hashmap<string, lambda::function<Try<Isolator*>(const Flags&)>>
creators = {
// Filesystem isolators.
#ifndef __WINDOWS__
{"filesystem/posix", &PosixFilesystemIsolatorProcess::create},
#else
{"filesystem/windows", &WindowsFilesystemIsolatorProcess::create},
#endif // __WINDOWS__
#ifdef __linux__
{"filesystem/linux", &LinuxFilesystemIsolatorProcess::create},
// TODO(jieyu): Deprecate this in favor of using filesystem/linux.
{"filesystem/shared", &SharedFilesystemIsolatorProcess::create},
#endif // __linux__
// Runtime isolators.
#ifndef __WINDOWS__
{"posix/cpu", &PosixCpuIsolatorProcess::create},
{"posix/mem", &PosixMemIsolatorProcess::create},
// "posix/disk" is deprecated in favor of the name "disk/du".
{"posix/disk", &PosixDiskIsolatorProcess::create},
{"disk/du", &PosixDiskIsolatorProcess::create},
#if ENABLE_XFS_DISK_ISOLATOR
{"disk/xfs", &XfsDiskIsolatorProcess::create},
#endif
#else
{"windows/cpu", &WindowsCpuIsolatorProcess::create},
#endif // __WINDOWS__
#ifdef __linux__
{"cgroups/cpu", &CgroupsCpushareIsolatorProcess::create},
{"cgroups/devices", &CgroupsDevicesIsolatorProcess::create},
{"cgroups/mem", &CgroupsMemIsolatorProcess::create},
{"cgroups/net_cls", &CgroupsNetClsIsolatorProcess::create},
{"cgroups/perf_event", &CgroupsPerfEventIsolatorProcess::create},
{"docker/runtime", &DockerRuntimeIsolatorProcess::create},
{"docker/volume", &DockerVolumeIsolatorProcess::create},
{"gpu/nvidia",
[&nvidia] (const Flags& flags) -> Try<Isolator*> {
if (!nvml::isAvailable()) {
return Error("Cannot create the Nvidia GPU isolator:"
" NVML is not available");
}
CHECK_SOME(nvidia)
<< "Nvidia components should be set when NVML is available";
return NvidiaGpuIsolatorProcess::create(flags, nvidia.get());
}},
{"namespaces/pid", &NamespacesPidIsolatorProcess::create},
{"network/cni", &NetworkCniIsolatorProcess::create},
#endif // __linux__
// NOTE: Network isolation is currently not supported on Windows builds.
#if !defined(__WINDOWS__) && defined(WITH_NETWORK_ISOLATOR)
{"network/port_mapping", &PortMappingIsolatorProcess::create},
#endif
};
const vector<string> isolations = strings::tokenize(flags_.isolation, ",");
if (isolations.size() !=
set<string>(isolations.begin(), isolations.end()).size()) {
return Error("Duplicate entries found in --isolation flag"
" '" + stringify(isolations) + "'");
}
vector<Owned<Isolator>> isolators;
foreach (const string& isolation, isolations) {
Try<Isolator*> isolator = [&]() -> Try<Isolator*> {
if (creators.contains(isolation)) {
return creators.at(isolation)(flags_);
} else if (ModuleManager::contains<Isolator>(isolation)) {
return ModuleManager::create<Isolator>(isolation);
}
return Error("Unknown or unsupported isolator");
}();
if (isolator.isError()) {
return Error("Failed to create isolator '" + isolation + "': " +
isolator.error());
}
// NOTE: The filesystem isolator must be the first isolator used
// so that the runtime isolators can have a consistent view on the
// prepared filesystem (e.g., any volume mounts are performed).
if (strings::contains(isolation, "filesystem/")) {
isolators.insert(isolators.begin(), Owned<Isolator>(isolator.get()));
} else {
isolators.push_back(Owned<Isolator>(isolator.get()));
}
}
return new MesosContainerizer(
flags_,
local,
fetcher,
Owned<ContainerLogger>(logger.get()),
Owned<Launcher>(launcher.get()),
provisioner.get(),
isolators);
}
MesosContainerizer::MesosContainerizer(
const Flags& flags,
bool local,
Fetcher* fetcher,
const Owned<ContainerLogger>& logger,
const Owned<Launcher>& launcher,
const Owned<Provisioner>& provisioner,
const vector<Owned<Isolator>>& isolators)
: process(new MesosContainerizerProcess(
flags,
local,
fetcher,
logger,
launcher,
provisioner,
isolators))
{
spawn(process.get());
}
MesosContainerizer::MesosContainerizer(
const Owned<MesosContainerizerProcess>& _process)
: process(_process)
{
spawn(process.get());
}
MesosContainerizer::~MesosContainerizer()
{
terminate(process.get());
process::wait(process.get());
}
Future<Nothing> MesosContainerizer::recover(
const Option<state::SlaveState>& state)
{
return dispatch(process.get(), &MesosContainerizerProcess::recover, state);
}
Future<bool> MesosContainerizer::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(),
&MesosContainerizerProcess::launch,
containerId,
None(),
executorInfo,
directory,
user,
slaveId,
slavePid,
checkpoint);
}
Future<bool> MesosContainerizer::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(),
&MesosContainerizerProcess::launch,
containerId,
taskInfo,
executorInfo,
directory,
user,
slaveId,
slavePid,
checkpoint);
}
Future<Nothing> MesosContainerizer::update(
const ContainerID& containerId,
const Resources& resources)
{
return dispatch(process.get(),
&MesosContainerizerProcess::update,
containerId,
resources);
}
Future<ResourceStatistics> MesosContainerizer::usage(
const ContainerID& containerId)
{
return dispatch(
process.get(),
&MesosContainerizerProcess::usage,
containerId);
}
Future<ContainerStatus> MesosContainerizer::status(
const ContainerID& containerId)
{
return dispatch(
process.get(),
&MesosContainerizerProcess::status,
containerId);
}
Future<containerizer::Termination> MesosContainerizer::wait(
const ContainerID& containerId)
{
return dispatch(process.get(), &MesosContainerizerProcess::wait, containerId);
}
void MesosContainerizer::destroy(const ContainerID& containerId)
{
dispatch(
process.get(),
&MesosContainerizerProcess::destroy,
containerId);
}
Future<hashset<ContainerID>> MesosContainerizer::containers()
{
return dispatch(process.get(), &MesosContainerizerProcess::containers);
}
Future<Nothing> MesosContainerizerProcess::recover(
const Option<state::SlaveState>& state)
{
LOG(INFO) << "Recovering containerizer";
// Gather the executor run states that we will attempt to recover.
list<ContainerState> recoverable;
if (state.isSome()) {
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);
// 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;
}
// Note that MesosContainerizer will also recover executors
// launched by the DockerContainerizer as before 0.23 the
// slave doesn't checkpoint container information.
const ExecutorInfo& executorInfo = executor.info.get();
if (executorInfo.has_container() &&
executorInfo.container().type() != ContainerInfo::MESOS) {
LOG(INFO) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because it was not launched from mesos containerizer";
continue;
}
LOG(INFO) << "Recovering container '" << containerId
<< "' for executor '" << executor.id
<< "' of framework " << framework.id;
// NOTE: We create the executor directory before checkpointing
// the executor. Therefore, it's not possible for this
// directory to be non-existent.
const string& directory = paths::getExecutorRunPath(
flags.work_dir,
state.get().id,
framework.id,
executor.id,
containerId);
CHECK(os::exists(directory));
ContainerState executorRunState =
protobuf::slave::createContainerState(
executorInfo,
run.get().id.get(),
run.get().forkedPid.get(),
directory);
recoverable.push_back(executorRunState);
}
}
}
// Try to recover the launcher first.
return launcher->recover(recoverable)
.then(defer(self(), &Self::_recover, recoverable, lambda::_1));
}
Future<Nothing> MesosContainerizerProcess::_recover(
const list<ContainerState>& recoverable,
const hashset<ContainerID>& orphans)
{
// Recover isolators first then recover the provisioner, because of
// possible cleanups on unknown containers.
return recoverIsolators(recoverable, orphans)
.then(defer(self(), &Self::recoverProvisioner, recoverable, orphans))
.then(defer(self(), &Self::__recover, recoverable, orphans));
}
Future<list<Nothing>> MesosContainerizerProcess::recoverIsolators(
const list<ContainerState>& recoverable,
const hashset<ContainerID>& orphans)
{
list<Future<Nothing>> futures;
// Then recover the isolators.
foreach (const Owned<Isolator>& isolator, isolators) {
futures.push_back(isolator->recover(recoverable, orphans));
}
// If all isolators recover then continue.
return collect(futures);
}
Future<Nothing> MesosContainerizerProcess::recoverProvisioner(
const list<ContainerState>& recoverable,
const hashset<ContainerID>& orphans)
{
return provisioner->recover(recoverable, orphans);
}
Future<Nothing> MesosContainerizerProcess::__recover(
const list<ContainerState>& recovered,
const hashset<ContainerID>& orphans)
{
foreach (const ContainerState& run, recovered) {
const ContainerID& containerId = run.container_id();
Container* container = new Container();
Future<Option<int>> status = process::reap(run.pid());
status.onAny(defer(self(), &Self::reaped, containerId));
container->status = status;
container->directory = run.directory();
// We only checkpoint the containerizer pid after the container
// successfully launched, therefore we can assume checkpointed
// containers should be running after recover.
container->state = RUNNING;
containers_[containerId] = Owned<Container>(container);
foreach (const Owned<Isolator>& isolator, isolators) {
isolator->watch(containerId)
.onAny(defer(self(), &Self::limited, containerId, lambda::_1));
}
// Pass recovered containers to the container logger.
// NOTE: The current implementation of the container logger only
// outputs a warning and does not have any other consequences.
// See `ContainerLogger::recover` for more information.
logger->recover(run.executor_info(), run.directory())
.onFailed(defer(self(), [run](const string& message) {
LOG(WARNING) << "Container logger failed to recover executor '"
<< run.executor_info().executor_id() << "': "
<< message;
}));
}
// Destroy all the orphan containers.
// NOTE: We do not fail the recovery if the destroy of orphan
// containers failed. See MESOS-2367 for details.
foreach (const ContainerID& containerId, orphans) {
LOG(INFO) << "Removing orphan container " << containerId;
launcher->destroy(containerId)
.then(defer(self(), &Self::cleanupIsolators, containerId))
.onAny(defer(self(), &Self::___recover, containerId, lambda::_1));
}
return Nothing();
}
void MesosContainerizerProcess::___recover(
const ContainerID& containerId,
const Future<list<Future<Nothing>>>& future)
{
// NOTE: If 'future' is not ready, that indicates launcher destroy
// has failed because 'cleanupIsolators' should always return a
// ready future.
if (!future.isReady()) {
LOG(ERROR) << "Failed to destroy orphan container " << containerId << ": "
<< (future.isFailed() ? future.failure() : "discarded");
++metrics.container_destroy_errors;
return;
}
// Indicates if the isolator cleanups have any failure or not.
bool cleanupFailed = false;
foreach (const Future<Nothing>& cleanup, future.get()) {
if (!cleanup.isReady()) {
LOG(ERROR) << "Failed to clean up an isolator when destroying "
<< "orphan container " << containerId << ": "
<< (cleanup.isFailed() ? cleanup.failure() : "discarded");
cleanupFailed = true;
}
}
if (cleanupFailed) {
++metrics.container_destroy_errors;
}
}
// Launching an executor involves the following steps:
// 1. Call prepare on each isolator.
// 2. Fork the executor. The forked child is blocked from exec'ing until it has
// been isolated.
// 3. Isolate the executor. Call isolate with the pid for each isolator.
// 4. Fetch the executor.
// 5. Exec the executor. The forked child is signalled to continue. It will
// first execute any preparation commands from isolators and then exec the
// executor.
Future<bool> MesosContainerizerProcess::launch(
const ContainerID& containerId,
const Option<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.isSome() &&
taskInfo.get().has_container() &&
taskInfo.get().container().type() != ContainerInfo::MESOS) {
return false;
}
// NOTE: We make a copy of the executor info because we may mutate
// it with default container info.
ExecutorInfo executorInfo = _executorInfo;
if (executorInfo.has_container() &&
executorInfo.container().type() != ContainerInfo::MESOS) {
return false;
}
// Add the default container info to the executor info.
// TODO(jieyu): Rename the flag to be default_mesos_container_info.
if (!executorInfo.has_container() &&
flags.default_container_info.isSome()) {
executorInfo.mutable_container()->CopyFrom(
flags.default_container_info.get());
}
LOG(INFO) << "Starting container '" << containerId
<< "' for executor '" << executorInfo.executor_id()
<< "' of framework '" << executorInfo.framework_id() << "'";
Container* container = new Container();
container->directory = directory;
container->state = PROVISIONING;
container->resources = executorInfo.resources();
// We need to set the `launchInfos` to be a ready future initially
// before we starting calling isolator->prepare() because otherwise,
// the destroy will wait forever trying to wait for this future to
// be ready, which it never will. See MESOS-4878.
container->launchInfos = list<Option<ContainerLaunchInfo>>();
containers_.put(containerId, Owned<Container>(container));
// If 'container' is not set in 'executorInfo', one of the following
// is true:
// 1) This is a custom executor without ContainerInfo.
// 2) This is a command task without ContainerInfo (since we copy
// ContainerInfo for command tasks if exists).
// In either of the above cases, no provisioning is needed.
// Therefore, we can go straight to 'prepare'.
if (!executorInfo.has_container()) {
return prepare(containerId, taskInfo, executorInfo, directory, user, None())
.then(defer(self(),
&Self::__launch,
containerId,
taskInfo,
executorInfo,
directory,
user,
slaveId,
slavePid,
checkpoint,
None(),
lambda::_1));
}
// We'll first provision the image for the container , and then
// provision the images specified in Volumes.
Option<Image> containerImage;
if (taskInfo.isSome() &&
taskInfo->has_container() &&
taskInfo->container().mesos().has_image()) {
// Command task.
containerImage = taskInfo->container().mesos().image();
} else if (executorInfo.container().mesos().has_image()) {
// Custom executor.
containerImage = executorInfo.container().mesos().image();
}
if (containerImage.isNone()) {
return _launch(containerId,
taskInfo,
executorInfo,
directory,
user,
slaveId,
slavePid,
checkpoint,
None());
}
Future<ProvisionInfo> provisioning = provisioner->provision(
containerId,
containerImage.get());
container->provisionInfos.push_back(provisioning);
return provisioning
.then(defer(PID<MesosContainerizerProcess>(this),
&MesosContainerizerProcess::_launch,
containerId,
taskInfo,
executorInfo,
directory,
user,
slaveId,
slavePid,
checkpoint,
lambda::_1));
}
Future<bool> MesosContainerizerProcess::_launch(
const ContainerID& containerId,
const Option<TaskInfo>& taskInfo,
const ExecutorInfo& executorInfo,
const string& directory,
const Option<string>& user,
const SlaveID& slaveId,
const PID<Slave>& slavePid,
bool checkpoint,
const Option<ProvisionInfo>& provisionInfo)
{
CHECK(executorInfo.has_container());
CHECK_EQ(executorInfo.container().type(), ContainerInfo::MESOS);
// This is because if a 'destroy' happens after 'launch' and before
// '_launch', even if the '___destroy' will wait for the 'provision'
// in 'launch' to finish, there is still a chance that '___destroy'
// and its dependencies finish before '_launch' starts since onAny
// is not guaranteed to be executed in order.
if (!containers_.contains(containerId)) {
return Failure("Container destroyed during provisioning");
}
// Make sure containerizer is not in DESTROYING state, to avoid
// a possible race that containerizer is destroying the container
// while it is provisioning the image from volumes.
if (containers_[containerId]->state == DESTROYING) {
return Failure("Container is being destroyed during provisioning");
}
CHECK_EQ(containers_[containerId]->state, PROVISIONING);
// We will provision the images specified in ContainerInfo::volumes
// as well. We will mutate ContainerInfo::volumes to include the
// paths to the provisioned root filesystems (by setting the
// 'host_path') if the volume specifies an image as the source.
//
// TODO(gilbert): We need to figure out a way to support passing
// runtime configurations specified in the image to the container.
Owned<ExecutorInfo> _executorInfo(new ExecutorInfo(executorInfo));
list<Future<Nothing>> futures;
for (int i = 0; i < _executorInfo->container().volumes_size(); i++) {
Volume* volume = _executorInfo->mutable_container()->mutable_volumes(i);
if (!volume->has_image()) {
continue;
}
const Image& image = volume->image();
Future<ProvisionInfo> future = provisioner->provision(containerId, image);
containers_[containerId]->provisionInfos.push_back(future);
futures.push_back(future.then([=](const ProvisionInfo& info) {
volume->set_host_path(info.rootfs);
return Nothing();
}));
}
// We put `prepare` inside of a lambda expression, in order to get
// _executorInfo object after host path set in volume.
return collect(futures)
.then(defer([=]() -> Future<bool> {
return prepare(containerId,
taskInfo,
*_executorInfo,
directory,
user,
provisionInfo)
.then(defer(self(),
&Self::__launch,
containerId,
taskInfo,
*_executorInfo,
directory,
user,
slaveId,
slavePid,
checkpoint,
provisionInfo,
lambda::_1));
}));
}
static list<Option<ContainerLaunchInfo>> accumulate(
list<Option<ContainerLaunchInfo>> l,
const Option<ContainerLaunchInfo>& e)
{
l.push_back(e);
return l;
}
static Future<list<Option<ContainerLaunchInfo>>> _prepare(
const Owned<Isolator>& isolator,
const ContainerID& containerId,
const ContainerConfig& containerConfig,
const list<Option<ContainerLaunchInfo>> launchInfos)
{
// Propagate any failure.
return isolator->prepare(containerId, containerConfig)
.then(lambda::bind(&accumulate, launchInfos, lambda::_1));
}
Future<list<Option<ContainerLaunchInfo>>> MesosContainerizerProcess::prepare(
const ContainerID& containerId,
const Option<TaskInfo>& taskInfo,
const ExecutorInfo& executorInfo,
const string& directory,
const Option<string>& user,
const Option<ProvisionInfo>& provisionInfo)
{
// This is because if a 'destroy' happens during the provisoiner is
// provisioning in '_launch', even if the '____destroy' will wait
// for the 'provision' in '_launch' to finish, there is still a
// chance that '____destroy' and its dependencies finish before
// 'prepare' starts since onAny is not guaranteed to be executed
// in order.
if (!containers_.contains(containerId)) {
return Failure("Container destroyed during provisioning");
}
// Make sure containerizer is not in DESTROYING state, to avoid
// a possible race that containerizer is destroying the container
// while it is preparing isolators for the container.
if (containers_[containerId]->state == DESTROYING) {
return Failure("Container is being destroyed during provisioning");
}