/
switchboard.cpp
1675 lines (1405 loc) · 52.9 KB
/
switchboard.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 <stdio.h>
#include <stdlib.h>
#include <list>
#include <map>
#include <string>
#include <vector>
#include <process/address.hpp>
#include <process/clock.hpp>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/http.hpp>
#include <process/io.hpp>
#include <process/limiter.hpp>
#include <process/loop.hpp>
#include <process/owned.hpp>
#include <process/process.hpp>
#include <process/reap.hpp>
#include <process/shared.hpp>
#include <process/socket.hpp>
#include <process/subprocess.hpp>
#include <stout/hashmap.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/recordio.hpp>
#ifndef __WINDOWS__
#include <stout/posix/os.hpp>
#endif // __WINDOWS__
#include <mesos/http.hpp>
#include <mesos/type_utils.hpp>
#include <mesos/agent/agent.hpp>
#include <mesos/slave/containerizer.hpp>
#include <mesos/slave/container_logger.hpp>
#include "common/http.hpp"
#include "common/recordio.hpp"
#include "slave/flags.hpp"
#include "slave/state.hpp"
#include "slave/containerizer/mesos/paths.hpp"
#include "slave/containerizer/mesos/io/switchboard.hpp"
namespace http = process::http;
#ifndef __WINDOWS__
namespace unix = process::network::unix;
#endif // __WINDOWS__
using std::list;
using std::map;
using std::string;
using std::vector;
using process::await;
using process::Clock;
using process::ErrnoFailure;
using process::Failure;
using process::Future;
using process::loop;
using process::Owned;
using process::PID;
using process::Process;
using process::Promise;
using process::RateLimiter;
using process::Shared;
using process::Subprocess;
using process::network::internal::SocketImpl;
using mesos::slave::ContainerConfig;
using mesos::slave::ContainerClass;
using mesos::slave::ContainerIO;
using mesos::slave::ContainerLaunchInfo;
using mesos::slave::ContainerLimitation;
using mesos::slave::ContainerLogger;
using mesos::slave::ContainerState;
using mesos::slave::Isolator;
namespace mesos {
namespace internal {
namespace slave {
Try<IOSwitchboard*> IOSwitchboard::create(
const Flags& flags,
bool local)
{
Try<ContainerLogger*> logger =
ContainerLogger::create(flags.container_logger);
if (logger.isError()) {
return Error("Cannot create container logger: " + logger.error());
}
return new IOSwitchboard(
flags,
local,
Owned<ContainerLogger>(logger.get()));
}
IOSwitchboard::IOSwitchboard(
const Flags& _flags,
bool _local,
Owned<ContainerLogger> _logger)
: flags(_flags),
local(_local),
logger(_logger) {}
IOSwitchboard::~IOSwitchboard() {}
bool IOSwitchboard::supportsNesting()
{
return true;
}
Future<Nothing> IOSwitchboard::recover(
const list<ContainerState>& states,
const hashset<ContainerID>& orphans)
{
#ifdef __WINDOWS__
return Nothing();
#else
if (local) {
return Nothing();
}
// Recover any active container's io switchboard info.
//
// NOTE: If a new agent is started with io switchboard server mode
// disabled, we will still recover the io switchboard info for
// containers previously launched by an agent with server mode enabled.
foreach (const ContainerState& state, states) {
const ContainerID& containerId = state.container_id();
const string path = containerizer::paths::getContainerIOSwitchboardPath(
flags.runtime_dir, containerId);
// If we don't have a checkpoint directory created for this
// container's io switchboard, there is nothing to recover. This
// can only happen for containers that were launched with `DEFAULT`
// ContainerClass *and* no `TTYInfo` set.
if (!os::exists(path)) {
continue;
}
Result<pid_t> pid = containerizer::paths::getContainerIOSwitchboardPid(
flags.runtime_dir, containerId);
// For active containers that have an io switchboard directory,
// we should *always* have a valid pid file. If we don't that is a
// an error and we should fail appropriately.
if (!pid.isSome()) {
return Failure("Failed to get I/O switchboard server pid for"
" '" + stringify(containerId) + "':"
" " + (pid.isError() ?
pid.error() :
"pid file does not exist"));
}
infos[containerId] = Owned<Info>(new Info(
pid.get(),
process::reap(pid.get()).onAny(defer(
PID<IOSwitchboard>(this),
&IOSwitchboard::reaped,
containerId,
lambda::_1))));
}
// Recover the io switchboards from any orphaned containers.
foreach (const ContainerID& orphan, orphans) {
const string path = containerizer::paths::getContainerIOSwitchboardPath(
flags.runtime_dir, orphan);
// If we don't have a checkpoint directory created for this
// container's io switchboard, there is nothing to recover.
if (!os::exists(path)) {
continue;
}
Result<pid_t> pid = containerizer::paths::getContainerIOSwitchboardPid(
flags.runtime_dir, orphan);
// If we were able to retrieve the checkpointed pid, we simply
// populate our info struct and rely on the containerizer to
// destroy the orphaned container and call `cleanup()` on us later.
if (pid.isSome()) {
infos[orphan] = Owned<Info>(new Info(
pid.get(),
process::reap(pid.get()).onAny(defer(
PID<IOSwitchboard>(this),
&IOSwitchboard::reaped,
orphan,
lambda::_1))));
} else {
// If we were not able to retrieve the checkpointed pid, we
// still need to populate our info struct (but with a pid value
// of `None()`). This way when `cleanup()` is called, we still
// do whatever cleanup we can (we just don't wait for the pid
// to be reaped -- we do it immediately).
//
// We could enter this case under 4 conditions:
//
// (1) The io switchboard we are recovering was launched, but
// the agent died before checkpointing its pid.
// (2) The io switchboard pid file was removed.
// (3) There was an error reading the io switchbaord pid file.
// (4) The io switchboard pid file was corrupted.
//
// We log an error in cases (3) and (4).
infos[orphan] = Owned<Info>(new Info(
None(),
Future<Option<int>>(None())));
if (pid.isError()) {
LOG(ERROR) << "Error retrieving the 'IOSwitchboard' pid file"
" for orphan '" << orphan << "': " << pid.error();
}
}
}
return Nothing();
#endif // __WINDOWS__
}
Future<Option<ContainerLaunchInfo>> IOSwitchboard::prepare(
const ContainerID& containerId,
const ContainerConfig& containerConfig)
{
// In local mode, the container will inherit agent's stdio.
if (local) {
return None();
}
// TODO(jieyu): Currently, if the agent fails over after the
// executor is launched, but before its nested containers are
// launched, the nested containers launched later might not have
// access to the root parent container's ExecutorInfo (i.e.,
// 'containerConfig.executor_info()' will be empty).
return logger->prepare(
containerConfig.executor_info(),
containerConfig.directory(),
containerConfig.has_user()
? Option<string>(containerConfig.user())
: None())
.then(defer(
PID<IOSwitchboard>(this),
&IOSwitchboard::_prepare,
containerId,
containerConfig,
lambda::_1));
}
Future<Option<ContainerLaunchInfo>> IOSwitchboard::_prepare(
const ContainerID& containerId,
const ContainerConfig& containerConfig,
const ContainerLogger::SubprocessInfo& loggerInfo)
{
// On windows, we do not yet support running an io switchboard
// server, so we must error out if it is required.
#ifdef __WINDOWS__
if (IOSwitchboard::requiresServer(containerConfig)) {
return Failure(
"IO Switchboard server is not supported on windows");
}
#endif
bool hasTTY = containerConfig.has_container_info() &&
containerConfig.container_info().has_tty_info();
if (!IOSwitchboard::requiresServer(containerConfig)) {
ContainerLaunchInfo launchInfo;
ContainerIO* out = launchInfo.mutable_out();
ContainerIO* err = launchInfo.mutable_err();
switch (loggerInfo.out.type()) {
case ContainerLogger::SubprocessInfo::IO::Type::FD:
out->set_type(ContainerIO::FD);
out->set_fd(loggerInfo.out.fd().get());
break;
case ContainerLogger::SubprocessInfo::IO::Type::PATH:
out->set_type(ContainerIO::PATH);
out->set_path(loggerInfo.out.path().get());
break;
default:
UNREACHABLE();
}
switch (loggerInfo.err.type()) {
case ContainerLogger::SubprocessInfo::IO::Type::FD:
err->set_type(ContainerIO::FD);
err->set_fd(loggerInfo.err.fd().get());
break;
case ContainerLogger::SubprocessInfo::IO::Type::PATH:
err->set_type(ContainerIO::PATH);
err->set_path(loggerInfo.err.path().get());
break;
default:
UNREACHABLE();
}
return launchInfo;
}
#ifndef __WINDOWS__
// First make sure that we haven't already spawned an io
// switchboard server for this container.
if (infos.contains(containerId)) {
return Failure("Already prepared io switchboard server for container"
" '" + stringify(containerId) + "'");
}
// Return the set of fds that should be sent to the
// container and dup'd onto its stdin/stdout/stderr.
ContainerLaunchInfo launchInfo;
// Manually construct pipes instead of using `Subprocess::PIPE`
// so that the ownership of the FDs is properly represented. The
// `Subprocess` spawned below owns one end of each pipe and will
// be solely responsible for closing that end. The ownership of
// the other end will be passed to the caller of this function
// and eventually passed to the container being launched.
int stdinToFd = -1;
int stdoutFromFd = -1;
int stderrFromFd = -1;
// A list of file decriptors we've opened so far.
hashset<int> openedFds = {};
// A list of file descriptors that will be passed to the I/O
// switchboard. We need to close those file descriptors once the
// I/O switchboard server is forked.
hashset<int> ioSwitchboardFds = {};
// Helper for closing a set of file descriptors.
auto close = [](const hashset<int>& fds) {
foreach (int fd, fds) {
os::close(fd);
}
};
// Setup a pseudo terminal for the container.
if (hasTTY) {
// TODO(jieyu): Consider moving all TTY related method to stout.
// For instance, 'stout/posix/tty.hpp'.
// Set flag 'O_NOCTTY' so that the terminal device will not become
// the controlling terminal for the process.
int master = posix_openpt(O_RDWR | O_NOCTTY | O_CLOEXEC);
if (master == -1) {
return Failure("Failed to open a master pseudo terminal");
}
openedFds.insert(master);
Try<string> slavePath = os::ptsname(master);
if (slavePath.isError()) {
close(openedFds);
return Failure("Failed to get the slave pseudo terminal path: " +
slavePath.error());
}
// Unlock the slave end of the pseudo terminal.
if (unlockpt(master) != 0) {
close(openedFds);
return ErrnoFailure("Failed to unlock the slave pseudo terminal");
}
// Set proper permission and ownership for the device.
if (grantpt(master) != 0) {
close(openedFds);
return ErrnoFailure("Failed to grant the slave pseudo terminal");
}
if (containerConfig.has_user()) {
Try<Nothing> chown = os::chown(
containerConfig.user(),
slavePath.get(),
false);
if (chown.isError()) {
close(openedFds);
return Failure("Failed to chown the slave pseudo terminal: " +
chown.error());
}
}
// Open the slave end of the pseudo terminal. The opened file
// descriptor will be dup'ed to stdin/out/err of the container.
Try<int> slave = os::open(slavePath.get(), O_RDWR | O_NOCTTY | O_CLOEXEC);
if (slave.isError()) {
return Failure("Failed to open the slave pseudo terminal: " +
slave.error());
}
openedFds.insert(slave.get());
LOG(INFO) << "Allocated pseudo terminal '" << slavePath.get()
<< "' for container " << containerId;
stdinToFd = master;
stdoutFromFd = master;
stderrFromFd = master;
launchInfo.mutable_in()->set_type(ContainerIO::FD);
launchInfo.mutable_in()->set_fd(slave.get());
launchInfo.mutable_out()->set_type(ContainerIO::FD);
launchInfo.mutable_out()->set_fd(slave.get());
launchInfo.mutable_err()->set_type(ContainerIO::FD);
launchInfo.mutable_err()->set_fd(slave.get());
launchInfo.set_tty_slave_path(slavePath.get());
} else {
int infds[2];
int outfds[2];
int errfds[2];
Try<Nothing> pipe = os::pipe(infds);
if (pipe.isError()) {
close(openedFds);
return Failure("Failed to create stdin pipe: " + pipe.error());
}
openedFds.insert(infds[0]);
openedFds.insert(infds[1]);
pipe = os::pipe(outfds);
if (pipe.isError()) {
close(openedFds);
return Failure("Failed to create stdout pipe: " + pipe.error());
}
openedFds.insert(outfds[0]);
openedFds.insert(outfds[1]);
pipe = os::pipe(errfds);
if (pipe.isError()) {
close(openedFds);
return Failure("Failed to create stderr pipe: " + pipe.error());
}
openedFds.insert(errfds[0]);
openedFds.insert(errfds[1]);
stdinToFd = infds[1];
stdoutFromFd = outfds[0];
stderrFromFd = errfds[0];
launchInfo.mutable_in()->set_type(ContainerIO::FD);
launchInfo.mutable_in()->set_fd(infds[0]);
launchInfo.mutable_out()->set_type(ContainerIO::FD);
launchInfo.mutable_out()->set_fd(outfds[1]);
launchInfo.mutable_err()->set_type(ContainerIO::FD);
launchInfo.mutable_err()->set_fd(errfds[1]);
}
// Make sure all file descriptors opened have CLOEXEC set.
foreach (int fd, openedFds) {
Try<Nothing> cloexec = os::cloexec(fd);
if (cloexec.isError()) {
close(openedFds);
return Failure("Failed to set cloexec: " + cloexec.error());
}
}
ioSwitchboardFds.insert(stdinToFd);
ioSwitchboardFds.insert(stdoutFromFd);
ioSwitchboardFds.insert(stderrFromFd);
// Set up our flags to send to the io switchboard server process.
IOSwitchboardServer::Flags switchboardFlags;
switchboardFlags.tty = hasTTY;
switchboardFlags.stdin_to_fd = stdinToFd;
switchboardFlags.stdout_from_fd = stdoutFromFd;
switchboardFlags.stderr_from_fd = stderrFromFd;
switchboardFlags.stdout_to_fd = STDOUT_FILENO;
switchboardFlags.stderr_to_fd = STDERR_FILENO;
switchboardFlags.heartbeat_interval = flags.http_heartbeat_interval;
if (containerConfig.container_class() == ContainerClass::DEBUG) {
switchboardFlags.wait_for_connection = true;
} else {
switchboardFlags.wait_for_connection = false;
}
switchboardFlags.socket_path = path::join(
stringify(os::PATH_SEPARATOR),
"tmp",
"mesos-io-switchboard-" + UUID::random().toString());
// Just before launching our io switchboard server, we need to
// create a directory to hold checkpointed files related to the
// server. The existence of this directory indicates that we
// intended to launch an io switchboard server on behalf of a
// container. The lack of any expected files in this directroy
// during recovery/cleanup indicates that something went wrong and
// we need to take appropriate action.
string path = containerizer::paths::getContainerIOSwitchboardPath(
flags.runtime_dir, containerId);
Try<Nothing> mkdir = os::mkdir(path);
if (mkdir.isError()) {
return Failure("Error creating 'IOSwitchboard' checkpoint directory"
" for container '" + stringify(containerId) + "':"
" " + mkdir.error());
}
// Prepare the environment for the io switchboard server process.
// We inherit agent environment variables except for those
// LIBPROCESS or MESOS prefixed environment variables since io
// switchboard server process does not rely on those environment
// variables.
map<string, string> environment;
foreachpair (const string& key, const string& value, os::environment()) {
if (!strings::startsWith(key, "LIBPROCESS_") &&
!strings::startsWith(key, "MESOS_")) {
environment.emplace(key, value);
}
}
// TODO(jieyu): This is to make sure the libprocess of the io
// switchboard can properly initialize and find the IP. Since we
// don't need to use the TCP socket for communication, it's OK to
// use a local address. Consider disable TCP socket in libprocess if
// libprocess supports that.
environment.emplace("LIBPROCESS_IP", "127.0.0.1");
// TODO(jieyu): Consider making this configurable.
environment.emplace("LIBPROCESS_NUM_WORKER_THREADS", "8");
VLOG(1) << "Launching '" << IOSwitchboardServer::NAME << "' with flags '"
<< switchboardFlags << "' for container " << containerId;
// Launch the io switchboard server process.
// We `dup()` the `stdout` and `stderr` passed to us by the
// container logger over the `stdout` and `stderr` of the io
// switchboard process itself. In this way, the io switchboard
// process simply needs to write to its own `stdout` and
// `stderr` in order to send output to the logger files.
Try<Subprocess> child = subprocess(
path::join(flags.launcher_dir, IOSwitchboardServer::NAME),
{IOSwitchboardServer::NAME},
Subprocess::PATH("/dev/null"),
loggerInfo.out,
loggerInfo.err,
&switchboardFlags,
environment,
None(),
{},
{Subprocess::ChildHook::SETSID(),
Subprocess::ChildHook::UNSET_CLOEXEC(stdinToFd),
Subprocess::ChildHook::UNSET_CLOEXEC(stdoutFromFd),
Subprocess::ChildHook::UNSET_CLOEXEC(stderrFromFd)});
if (child.isError()) {
close(openedFds);
return Failure("Failed to create io switchboard"
" server process: " + child.error());
}
LOG(INFO) << "Created I/O switchboard server (pid: " << child->pid()
<< ") listening on socket file '"
<< switchboardFlags.socket_path.get()
<< "' for container " << containerId;
close(ioSwitchboardFds);
// We remove the already closed file descriptors from 'openedFds' so
// that we don't close multiple times if failures happen below.
foreach (int fd, ioSwitchboardFds) {
openedFds.erase(fd);
}
// Now that the child has come up, we checkpoint the socket
// address we told it to bind to so we can access it later.
path = containerizer::paths::getContainerIOSwitchboardSocketPath(
flags.runtime_dir, containerId);
Try<Nothing> checkpointed = slave::state::checkpoint(
path, switchboardFlags.socket_path.get());
if (checkpointed.isError()) {
close(openedFds);
return Failure("Failed to checkpoint container's socket path to"
" '" + path + "': " + checkpointed.error());
}
// We also checkpoint the child's pid.
path = containerizer::paths::getContainerIOSwitchboardPidPath(
flags.runtime_dir, containerId);
checkpointed = slave::state::checkpoint(path, stringify(child->pid()));
if (checkpointed.isError()) {
close(openedFds);
return Failure("Failed to checkpoint container's io switchboard pid to"
" '" + path + "': " + checkpointed.error());
}
// Build an info struct for this container.
infos[containerId] = Owned<Info>(new Info(
child->pid(),
process::reap(child->pid()).onAny(defer(
PID<IOSwitchboard>(this),
&IOSwitchboard::reaped,
containerId,
lambda::_1))));
return launchInfo;
#endif // __WINDOWS__
}
Future<http::Connection> IOSwitchboard::connect(
const ContainerID& containerId)
{
#ifdef __WINDOWS__
return Failure("Not supported on Windows");
#else
if (local) {
return Failure("Not supported in local mode");
}
if (!infos.contains(containerId)) {
return Failure("I/O switchboard server was disabled for this container");
}
// Get the io switchboard address from the `containerId`.
//
// NOTE: We explicitly don't want to check for the existence of
// `containerId` in our `infos` struct. Otherwise we wouldn't be
// able to reconnect to the io switchboard after agent restarts.
Result<unix::Address> address =
containerizer::paths::getContainerIOSwitchboardAddress(
flags.runtime_dir, containerId);
if (!address.isSome()) {
return Failure("Failed to get the io switchboard address"
": " + (address.isError() ? address.error() : "Not found"));
}
// Wait for the server to create the domain socket file.
Shared<RateLimiter> limiter(new RateLimiter(1, Milliseconds(10)));
return loop(
self(),
[=]() {
return limiter->acquire();
},
[=](const Nothing&) {
return infos.contains(containerId) && !os::exists(address->path());
})
.then(defer(self(), [=]() -> Future<http::Connection> {
if (!infos.contains(containerId)) {
return Failure("Container has or is being destroyed");
}
// TODO(jieyu): We might still get a connection refused error
// here because the server might not have started listening on
// the socket yet. Consider retrying if 'http::connect' failed
// with ECONNREFUSED.
return http::connect(address.get(), http::Scheme::HTTP);
}));
#endif // __WINDOWS__
}
Future<ContainerLimitation> IOSwitchboard::watch(
const ContainerID& containerId)
{
#ifdef __WINDOWS__
return Future<ContainerLimitation>();
#else
if (local) {
return Future<ContainerLimitation>();
}
// We ignore unknown containers here because legacy containers
// without an io switchboard directory will not have an info struct
// created for during recovery. Likewise, containers launched
// by a previous agent with io switchboard server mode disabled will
// not have info structs created for them either. In both cases
// there is nothing to watch, so we return an unsatisfiable future.
if (!infos.contains(containerId)) {
return Future<ContainerLimitation>();
}
return infos[containerId]->limitation.future();
#endif // __WINDOWS__
}
Future<Nothing> IOSwitchboard::cleanup(
const ContainerID& containerId)
{
#ifdef __WINDOWS__
// Since we don't support spawning an io switchboard server on
// windows yet, there is nothing to wait for here.
return Nothing();
#else
if (local) {
return Nothing();
}
// We ignore unknown containers here because legacy containers
// without an io switchboard directory will not have an info struct
// created for them during recovery. Likewise, containers launched
// by a previous agent with io switchboard server mode disabled will
// not have info structs created for them either. In both cases
// there is nothing to cleanup, so we simly return `Nothing()`.
if (!infos.contains(containerId)) {
return Nothing();
}
Option<pid_t> pid = infos[containerId]->pid;
Future<Option<int>> status = infos[containerId]->status;
infos.erase(containerId);
// If we have a pid, then we attempt to send it a SIGTERM to have it
// shutdown gracefully. This is best effort, as it's likely that the
// switchboard has already shutdown in the common case.
//
// NOTE: There is an unfortunate race condition here. If the io
// switchboard terminates and the pid is reused by some other
// process, we might be sending SIGTERM to a random process. This
// could be a problem under high load.
//
// TODO(jieyu): We give the I/O switchboard server a grace period to
// wait for the connection from the containerizer. This is for the
// case where the container itself is short lived (e.g., a DEBUG
// container does an 'ls' and exits). For that case, we still want
// the subsequent attach output call to get the output from that
// container.
//
// TODO(klueska): Send a message over the io switchboard server's
// domain socket instead of using a signal.
if (pid.isSome() && status.isPending()) {
Clock::timer(Seconds(5), [pid, status, containerId]() {
if (status.isPending()) {
LOG(INFO) << "Sending SIGTERM to I/O switchboard server (pid: "
<< pid.get() << ") since container " << containerId
<< " is being destroyed";
os::kill(pid.get(), SIGTERM);
}
});
}
// NOTE: We use 'await' here so that we can handle the FAILED and
// DISCARDED cases as well.
return await(list<Future<Option<int>>>{status}).then(
defer(self(), [this, containerId]() -> Future<Nothing> {
// Best effort removal of the unix domain socket file created for
// this container's `IOSwitchboardServer`. If it hasn't been
// checkpointed yet, or the socket file itself hasn't been created,
// we simply continue without error.
Result<unix::Address> address =
containerizer::paths::getContainerIOSwitchboardAddress(
flags.runtime_dir, containerId);
if (address.isSome()) {
Try<Nothing> rm = os::rm(address->path());
if (rm.isError()) {
LOG(ERROR) << "Failed to remove unix domain socket file"
<< " '" << address->path() << "' for container"
<< " '" << containerId << "': " << rm.error();
}
}
return Nothing();
}));
#endif // __WINDOWS__
}
bool IOSwitchboard::requiresServer(const ContainerConfig& containerConfig)
{
if (containerConfig.has_container_info() &&
containerConfig.container_info().has_tty_info()) {
return true;
}
if (containerConfig.has_container_class() &&
containerConfig.container_class() ==
mesos::slave::ContainerClass::DEBUG) {
return true;
}
return false;
}
#ifndef __WINDOWS__
void IOSwitchboard::reaped(
const ContainerID& containerId,
const Future<Option<int>>& future)
{
// NOTE: If reaping of the server process failed, we simply
// return here because it is unknown to us whether we should
// destroy the container or not.
if (!future.isReady()) {
LOG(ERROR) << "Failed to reap the I/O switchboard server: "
<< (future.isFailed() ? future.failure() : "discarded");
return;
}
const Option<int>& status = future.get();
// No need to do anything if the I/O switchboard server terminates
// normally, or its terminal status is unknown. Only initiate the
// destroy of the container if we know for sure that the I/O
// switchboard server terminates unexpectedly.
if (status.isNone()) {
LOG(INFO) << "I/O switchboard server process for container "
<< containerId << " has terminated (status=N/A)";
return;
} else if (WIFEXITED(status.get()) && WEXITSTATUS(status.get()) == 0) {
LOG(INFO) << "I/O switchboard server process for container "
<< containerId << " has terminated (status=0)";
return;
}
// No need to proceed if the container has or is being destroyed.
if (!infos.contains(containerId)) {
return;
}
ContainerLimitation limitation;
limitation.set_reason(TaskStatus::REASON_IO_SWITCHBOARD_EXITED);
if (WIFEXITED(status.get())) {
limitation.set_message(
"'IOSwitchboard' exited with status:"
" " + stringify(WEXITSTATUS(status.get())));
} else if (WIFSIGNALED(status.get())) {
limitation.set_message(
"'IOSwitchboard' exited with signal:"
" " + stringify(strsignal(WTERMSIG(status.get()))));
}
infos[containerId]->limitation.set(limitation);
LOG(ERROR) << "Unexpected termination of I/O switchboard server: "
<< limitation.message() << " for container " << containerId;
}
const char IOSwitchboardServer::NAME[] = "mesos-io-switchboard";
class IOSwitchboardServerProcess : public Process<IOSwitchboardServerProcess>
{
public:
IOSwitchboardServerProcess(
bool _tty,
int _stdinToFd,
int _stdoutFromFd,
int _stdoutToFd,
int _stderrFromFd,
int _stderrToFd,
const unix::Socket& _socket,
bool waitForConnection,
Option<Duration> heartbeatInterval);
virtual void finalize();
Future<Nothing> run();
Future<Nothing> unblock();
private:
class HttpConnection
{
public:
HttpConnection(
const http::Pipe::Writer& _writer,
const ContentType& contentType)
: writer(_writer),
encoder(lambda::bind(serialize, contentType, lambda::_1)) {}
bool send(const agent::ProcessIO& message)
{
return writer.write(encoder.encode(message));
}
bool close()
{
return writer.close();
}
process::Future<Nothing> closed() const
{
return writer.readerClosed();
}
private:
http::Pipe::Writer writer;
::recordio::Encoder<agent::ProcessIO> encoder;
};
// Sit in a heartbeat loop forever.
void heartbeatLoop();
// Sit in an accept loop forever.
void acceptLoop();
// Parse the request and look for `ATTACH_CONTAINER_INPUT` and
// `ATTACH_CONTAINER_OUTPUT` calls. We call their corresponding
// handler functions once we have parsed them. We accept calls as
// both `APPLICATION_PROTOBUF` and `APPLICATION_JSON` and respond
// with the same format we receive them in.
Future<http::Response> handler(const http::Request& request);
// Validate `ATTACH_CONTAINER_INPUT` calls.
//
// TODO(klueska): Move this to `src/slave/validation.hpp` and make
// the agent validate all the calls before forwarding them to the
// switchboard.
Option<Error> validate(const agent::Call::AttachContainerInput& call);
// Handle `ATTACH_CONTAINER_INPUT` calls.
Future<http::Response> attachContainerInput(
const Owned<recordio::Reader<agent::Call>>& reader);
// Handle `ATTACH_CONTAINER_OUTPUT` calls.
Future<http::Response> attachContainerOutput(ContentType acceptType);
// Asynchronously receive data as we read it from our
// `stdoutFromFd` and `stdoutFromFd` file descriptors.
void outputHook(
const string& data,
const agent::ProcessIO::Data::Type& type);
bool tty;
int stdinToFd;
int stdoutFromFd;
int stdoutToFd;
int stderrFromFd;
int stderrToFd;
unix::Socket socket;
bool waitForConnection;
Option<Duration> heartbeatInterval;
bool inputConnected;
Promise<Nothing> promise;
Promise<Nothing> startRedirect;
// The following must be a `std::list`
// for proper erase semantics later on.
list<HttpConnection> outputConnections;
Option<Failure> failure;
};
Try<Owned<IOSwitchboardServer>> IOSwitchboardServer::create(
bool tty,
int stdinToFd,
int stdoutFromFd,
int stdoutToFd,
int stderrFromFd,
int stderrToFd,
const string& socketPath,
bool waitForConnection,
Option<Duration> heartbeatInterval)
{