/
slave.cpp
7347 lines (6135 loc) · 242 KB
/
slave.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 <errno.h>
#include <signal.h>
#include <stdlib.h> // For random().
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include <mesos/type_utils.hpp>
#include <mesos/module/authenticatee.hpp>
#include <process/async.hpp>
#include <process/check.hpp>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/delay.hpp>
#include <process/dispatch.hpp>
#include <process/http.hpp>
#include <process/id.hpp>
#include <process/reap.hpp>
#include <process/time.hpp>
#include <stout/bytes.hpp>
#include <stout/check.hpp>
#include <stout/duration.hpp>
#include <stout/exit.hpp>
#include <stout/fs.hpp>
#include <stout/lambda.hpp>
#include <stout/net.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#ifdef __linux__
#include <stout/proc.hpp>
#endif // __linux__
#include <stout/numify.hpp>
#include <stout/stringify.hpp>
#include <stout/strings.hpp>
#include <stout/try.hpp>
#include <stout/uuid.hpp>
#include <stout/utils.hpp>
#ifdef __linux__
#include "linux/cgroups.hpp"
#include "linux/fs.hpp"
#endif // __linux__
#include "authentication/cram_md5/authenticatee.hpp"
#include "common/build.hpp"
#include "common/protobuf_utils.hpp"
#include "common/resources_utils.hpp"
#include "common/status_utils.hpp"
#include "credentials/credentials.hpp"
#include "hook/manager.hpp"
#include "logging/logging.hpp"
#include "module/manager.hpp"
#include "slave/constants.hpp"
#include "slave/flags.hpp"
#include "slave/paths.hpp"
#include "slave/slave.hpp"
#include "slave/status_update_manager.hpp"
#ifdef __WINDOWS__
// Used to install a Windows console ctrl handler.
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms682066(v=vs.85).aspx
#include <slave/windows_ctrlhandler.hpp>
#else
// Used to install a handler for POSIX signal.
// http://pubs.opengroup.org/onlinepubs/009695399/functions/sigaction.html
#include <slave/posix_signalhandler.hpp>
#endif // __WINDOWS__
using google::protobuf::RepeatedPtrField;
using mesos::executor::Call;
using mesos::master::detector::MasterDetector;
using mesos::slave::ContainerTermination;
using mesos::slave::QoSController;
using mesos::slave::QoSCorrection;
using mesos::slave::ResourceEstimator;
using std::find;
using std::list;
using std::map;
using std::ostringstream;
using std::set;
using std::string;
using std::tuple;
using std::vector;
using process::async;
using process::wait; // Necessary on some OS's to disambiguate.
using process::Clock;
using process::Failure;
using process::Future;
using process::Owned;
using process::PID;
using process::Time;
using process::UPID;
#ifdef __WINDOWS__
constexpr char MESOS_EXECUTOR[] = "mesos-executor.exe";
#else
constexpr char MESOS_EXECUTOR[] = "mesos-executor";
#endif // __WINDOWS__
namespace mesos {
namespace internal {
namespace slave {
using namespace state;
Slave::Slave(const string& id,
const slave::Flags& _flags,
MasterDetector* _detector,
Containerizer* _containerizer,
Files* _files,
GarbageCollector* _gc,
StatusUpdateManager* _statusUpdateManager,
ResourceEstimator* _resourceEstimator,
QoSController* _qosController,
const Option<Authorizer*>& _authorizer)
: ProcessBase(id),
state(RECOVERING),
flags(_flags),
http(this),
completedFrameworks(MAX_COMPLETED_FRAMEWORKS),
detector(_detector),
containerizer(_containerizer),
files(_files),
metrics(*this),
gc(_gc),
statusUpdateManager(_statusUpdateManager),
masterPingTimeout(DEFAULT_MASTER_PING_TIMEOUT()),
metaDir(paths::getMetaRootDir(flags.work_dir)),
recoveryErrors(0),
credential(None()),
authenticatee(nullptr),
authenticating(None()),
authenticated(false),
reauthenticate(false),
failedAuthentications(0),
executorDirectoryMaxAllowedAge(age(0)),
resourceEstimator(_resourceEstimator),
qosController(_qosController),
authorizer(_authorizer) {}
Slave::~Slave()
{
// TODO(benh): Shut down frameworks?
// TODO(benh): Shut down executors? The executor should get an "exited"
// event and initiate a shut down itself.
foreachvalue (Framework* framework, frameworks) {
delete framework;
}
delete authenticatee;
}
void Slave::signaled(int signal, int uid)
{
if (signal == SIGUSR1) {
Result<string> user = os::user(uid);
shutdown(
UPID(),
"Received SIGUSR1 signal" +
(user.isSome() ? " from user " + user.get() : ""));
}
}
void Slave::initialize()
{
LOG(INFO) << "Mesos agent started on " << string(self()).substr(5);
LOG(INFO) << "Flags at startup: " << flags;
if (self().address.ip.isLoopback()) {
LOG(WARNING) << "\n**************************************************\n"
<< "Agent bound to loopback interface!"
<< " Cannot communicate with remote master(s)."
<< " You might want to set '--ip' flag to a routable"
<< " IP address.\n"
<< "**************************************************";
}
#ifdef __linux__
// Move the slave into its own cgroup for each of the specified
// subsystems.
//
// NOTE: Any subsystem configuration is inherited from the mesos
// root cgroup for that subsystem, e.g., by default the memory
// cgroup will be unlimited.
//
// TODO(jieyu): Make sure the corresponding cgroup isolator is
// enabled so that the container processes are moved to different
// cgroups than the agent cgroup.
if (flags.agent_subsystems.isSome()) {
foreach (const string& subsystem,
strings::tokenize(flags.agent_subsystems.get(), ",")) {
LOG(INFO) << "Moving agent process into its own cgroup for"
<< " subsystem: " << subsystem;
// Ensure the subsystem is mounted and the Mesos root cgroup is
// present.
Try<string> hierarchy = cgroups::prepare(
flags.cgroups_hierarchy,
subsystem,
flags.cgroups_root);
if (hierarchy.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to prepare cgroup " << flags.cgroups_root
<< " for subsystem " << subsystem << ": " << hierarchy.error();
}
// Create a cgroup for the slave.
string cgroup = path::join(flags.cgroups_root, "slave");
Try<bool> exists = cgroups::exists(hierarchy.get(), cgroup);
if (exists.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to find cgroup " << cgroup
<< " for subsystem " << subsystem
<< " under hierarchy " << hierarchy.get()
<< " for agent: " << exists.error();
}
if (!exists.get()) {
Try<Nothing> create = cgroups::create(hierarchy.get(), cgroup);
if (create.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to create cgroup " << cgroup
<< " for subsystem " << subsystem
<< " under hierarchy " << hierarchy.get()
<< " for agent: " << create.error();
}
}
// Exit if there are processes running inside the cgroup - this
// indicates a prior slave (or child process) is still running.
Try<set<pid_t>> processes = cgroups::processes(hierarchy.get(), cgroup);
if (processes.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to check for existing threads in cgroup " << cgroup
<< " for subsystem " << subsystem
<< " under hierarchy " << hierarchy.get()
<< " for agent: " << processes.error();
}
// Log if there are any processes in the slave's cgroup. They
// may be transient helper processes like 'perf' or 'du',
// ancillary processes like 'docker log' or possibly a stuck
// slave.
// TODO(idownes): Generally, it's not a problem if there are
// processes running in the slave's cgroup, though any resources
// consumed by those processes are accounted to the slave. Where
// applicable, transient processes should be configured to
// terminate if the slave exits; see example usage for perf in
// isolators/cgroups/perf.cpp. Consider moving ancillary
// processes to a different cgroup, e.g., moving 'docker log' to
// the container's cgroup.
if (!processes.get().empty()) {
// For each process, we print its pid as well as its command
// to help triaging.
vector<string> infos;
foreach (pid_t pid, processes.get()) {
Result<os::Process> proc = os::process(pid);
// Only print the command if available.
if (proc.isSome()) {
infos.push_back(stringify(pid) + " '" + proc.get().command + "'");
} else {
infos.push_back(stringify(pid));
}
}
LOG(INFO) << "An agent (or child process) is still running, please"
<< " consider checking the following process(es) listed in "
<< path::join(hierarchy.get(), cgroup, "cgroups.proc")
<< ":\n" << strings::join("\n", infos);
}
// Move all of our threads into the cgroup.
Try<Nothing> assign = cgroups::assign(hierarchy.get(), cgroup, getpid());
if (assign.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to move agent into cgroup " << cgroup
<< " for subsystem " << subsystem
<< " under hierarchy " << hierarchy.get()
<< " for agent: " << assign.error();
}
}
}
#endif // __linux__
if (flags.registration_backoff_factor > REGISTER_RETRY_INTERVAL_MAX) {
EXIT(EXIT_FAILURE)
<< "Invalid value '" << flags.registration_backoff_factor << "'"
<< " for --registration_backoff_factor:"
<< " Must be less than " << REGISTER_RETRY_INTERVAL_MAX;
}
authenticateeName = flags.authenticatee;
// Load credential for agent authentication with the master.
if (flags.credential.isSome()) {
Result<Credential> _credential =
credentials::readCredential(flags.credential.get());
if (_credential.isError()) {
EXIT(EXIT_FAILURE) << _credential.error() << " (see --credential flag)";
} else if (_credential.isNone()) {
EXIT(EXIT_FAILURE)
<< "Empty credential file '" << flags.credential.get() << "'"
<< " (see --credential flag)";
} else {
credential = _credential.get();
LOG(INFO) << "Agent using credential for: "
<< credential.get().principal();
}
}
Option<Credentials> httpCredentials;
if (flags.http_credentials.isSome()) {
Result<Credentials> credentials =
credentials::read(flags.http_credentials.get());
if (credentials.isError()) {
EXIT(EXIT_FAILURE)
<< credentials.error() << " (see --http_credentials flag)";
} else if (credentials.isNone()) {
EXIT(EXIT_FAILURE)
<< "Credentials file must contain at least one credential"
<< " (see --http_credentials flag)";
}
httpCredentials = credentials.get();
}
if (flags.authenticate_http_readonly) {
Try<Nothing> result = initializeHttpAuthenticators(
READONLY_HTTP_AUTHENTICATION_REALM,
strings::split(flags.http_authenticators, ","),
httpCredentials);
if (result.isError()) {
EXIT(EXIT_FAILURE) << result.error();
}
}
if (flags.authenticate_http_readwrite) {
Try<Nothing> result = initializeHttpAuthenticators(
READWRITE_HTTP_AUTHENTICATION_REALM,
strings::split(flags.http_authenticators, ","),
httpCredentials);
if (result.isError()) {
EXIT(EXIT_FAILURE) << result.error();
}
}
if ((flags.gc_disk_headroom < 0) || (flags.gc_disk_headroom > 1)) {
EXIT(EXIT_FAILURE)
<< "Invalid value '" << flags.gc_disk_headroom << "'"
<< " for --gc_disk_headroom. Must be between 0.0 and 1.0";
}
Try<Nothing> initialize =
resourceEstimator->initialize(defer(self(), &Self::usage));
if (initialize.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to initialize the resource estimator: " << initialize.error();
}
initialize = qosController->initialize(defer(self(), &Self::usage));
if (initialize.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to initialize the QoS Controller: " << initialize.error();
}
// Ensure slave work directory exists.
CHECK_SOME(os::mkdir(flags.work_dir))
<< "Failed to create agent work directory '" << flags.work_dir << "'";
Try<Resources> resources = Containerizer::resources(flags);
if (resources.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to determine agent resources: " << resources.error();
}
// Ensure disk `source`s are accessible.
foreach (
const Resource& resource,
resources->filter([](const Resource& _resource) {
return _resource.has_disk() && _resource.disk().has_source();
})) {
// For `PATH` sources we create them if they do not exist.
const Resource::DiskInfo::Source& source = resource.disk().source();
if (source.type() == Resource::DiskInfo::Source::PATH) {
CHECK(source.has_path());
Try<Nothing> mkdir =
os::mkdir(source.path().root(), true);
if (mkdir.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to create DiskInfo path directory '"
<< source.path().root() << "': " << mkdir.error();
}
} else if (source.type() == Resource::DiskInfo::Source::MOUNT) {
CHECK(source.has_mount());
// For `MOUNT` sources we fail if they don't exist.
// On Linux we test the mount table for existence.
#ifdef __linux__
// Get the `realpath` of the `root` to verify it against the
// mount table entries.
// TODO(jmlvanre): Consider enforcing allowing only real paths
// as opposed to symlinks. This would prevent the ability for
// an operator to change the underlying data while the slave
// checkpointed `root` had the same value. We could also check
// the UUID of the underlying block device to catch this case.
Result<string> realpath = os::realpath(source.mount().root());
if (!realpath.isSome()) {
EXIT(EXIT_FAILURE)
<< "Failed to determine `realpath` for DiskInfo mount in resource '"
<< resource << "' with path '" << source.mount().root() << "': "
<< (realpath.isError() ? realpath.error() : "no such path");
}
// TODO(jmlvanre): Consider moving this out of the for loop.
Try<fs::MountTable> mountTable = fs::MountTable::read("/proc/mounts");
if (mountTable.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to open mount table to verify mounts: "
<< mountTable.error();
}
bool foundEntry = false;
foreach (const fs::MountTable::Entry& entry, mountTable.get().entries) {
if (entry.dir == realpath.get()) {
foundEntry = true;
break;
}
}
if (!foundEntry) {
EXIT(EXIT_FAILURE)
<< "Failed to found mount '" << realpath.get() << "' in /proc/mounts";
}
#else // __linux__
// On other platforms we test whether that provided `root` exists.
if (!os::exists(source.mount().root())) {
EXIT(EXIT_FAILURE)
<< "Failed to find mount point '" << source.mount().root() << "'";
}
#endif // __linux__
} else {
EXIT(EXIT_FAILURE)
<< "Unsupported 'DiskInfo.Source.Type' in '" << resource << "'";
}
}
Attributes attributes;
if (flags.attributes.isSome()) {
attributes = Attributes::parse(flags.attributes.get());
}
// Determine our hostname or use the hostname provided.
string hostname;
if (flags.hostname.isNone()) {
if (flags.hostname_lookup) {
Try<string> result = net::getHostname(self().address.ip);
if (result.isError()) {
LOG(FATAL) << "Failed to get hostname: " << result.error();
}
hostname = result.get();
} else {
// We use the IP address for hostname if the user requested us
// NOT to look it up, and it wasn't explicitly set via --hostname:
hostname = stringify(self().address.ip);
}
} else {
hostname = flags.hostname.get();
}
// Initialize slave info.
info.set_hostname(hostname);
info.set_port(self().address.port);
info.mutable_resources()->CopyFrom(resources.get());
if (HookManager::hooksAvailable()) {
info.mutable_resources()->CopyFrom(
HookManager::slaveResourcesDecorator(info));
}
// Initialize `totalResources` with `info.resources`, checkpointed
// resources will be applied later during recovery.
totalResources = resources.get();
LOG(INFO) << "Agent resources: " << info.resources();
info.mutable_attributes()->CopyFrom(attributes);
if (HookManager::hooksAvailable()) {
info.mutable_attributes()->CopyFrom(
HookManager::slaveAttributesDecorator(info));
}
LOG(INFO) << "Agent attributes: " << info.attributes();
// Checkpointing of slaves is always enabled.
info.set_checkpoint(true);
LOG(INFO) << "Agent hostname: " << info.hostname();
statusUpdateManager->initialize(defer(self(), &Slave::forward, lambda::_1)
.operator std::function<void(StatusUpdate)>());
// We pause the status update manager so that it doesn't forward any updates
// while the slave is still recovering. It is unpaused/resumed when the slave
// (re-)registers with the master.
statusUpdateManager->pause();
// Start disk monitoring.
// NOTE: We send a delayed message here instead of directly calling
// checkDiskUsage, to make disabling this feature easy (e.g by specifying
// a very large disk_watch_interval).
delay(flags.disk_watch_interval, self(), &Slave::checkDiskUsage);
startTime = Clock::now();
// Install protobuf handlers.
install<SlaveRegisteredMessage>(
&Slave::registered,
&SlaveRegisteredMessage::slave_id,
&SlaveRegisteredMessage::connection);
install<SlaveReregisteredMessage>(
&Slave::reregistered,
&SlaveReregisteredMessage::slave_id,
&SlaveReregisteredMessage::reconciliations,
&SlaveReregisteredMessage::connection);
install<RunTaskMessage>(
&Slave::runTask,
&RunTaskMessage::framework,
&RunTaskMessage::framework_id,
&RunTaskMessage::pid,
&RunTaskMessage::task);
install<RunTaskGroupMessage>(
&Slave::runTaskGroup,
&RunTaskGroupMessage::framework,
&RunTaskGroupMessage::executor,
&RunTaskGroupMessage::task_group);
install<KillTaskMessage>(
&Slave::killTask);
install<ShutdownExecutorMessage>(
&Slave::shutdownExecutor,
&ShutdownExecutorMessage::framework_id,
&ShutdownExecutorMessage::executor_id);
install<ShutdownFrameworkMessage>(
&Slave::shutdownFramework,
&ShutdownFrameworkMessage::framework_id);
install<FrameworkToExecutorMessage>(
&Slave::schedulerMessage,
&FrameworkToExecutorMessage::slave_id,
&FrameworkToExecutorMessage::framework_id,
&FrameworkToExecutorMessage::executor_id,
&FrameworkToExecutorMessage::data);
install<UpdateFrameworkMessage>(
&Slave::updateFramework,
&UpdateFrameworkMessage::framework_id,
&UpdateFrameworkMessage::pid);
install<CheckpointResourcesMessage>(
&Slave::checkpointResources,
&CheckpointResourcesMessage::resources);
install<StatusUpdateAcknowledgementMessage>(
&Slave::statusUpdateAcknowledgement,
&StatusUpdateAcknowledgementMessage::slave_id,
&StatusUpdateAcknowledgementMessage::framework_id,
&StatusUpdateAcknowledgementMessage::task_id,
&StatusUpdateAcknowledgementMessage::uuid);
install<RegisterExecutorMessage>(
&Slave::registerExecutor,
&RegisterExecutorMessage::framework_id,
&RegisterExecutorMessage::executor_id);
install<ReregisterExecutorMessage>(
&Slave::reregisterExecutor,
&ReregisterExecutorMessage::framework_id,
&ReregisterExecutorMessage::executor_id,
&ReregisterExecutorMessage::tasks,
&ReregisterExecutorMessage::updates);
install<StatusUpdateMessage>(
&Slave::statusUpdate,
&StatusUpdateMessage::update,
&StatusUpdateMessage::pid);
install<ExecutorToFrameworkMessage>(
&Slave::executorMessage,
&ExecutorToFrameworkMessage::slave_id,
&ExecutorToFrameworkMessage::framework_id,
&ExecutorToFrameworkMessage::executor_id,
&ExecutorToFrameworkMessage::data);
install<ShutdownMessage>(
&Slave::shutdown,
&ShutdownMessage::message);
install<PingSlaveMessage>(
&Slave::ping,
&PingSlaveMessage::connected);
// Setup the '/api/v1' handler for streaming requests.
RouteOptions options;
options.requestStreaming = true;
route("/api/v1",
// TODO(benh): Is this authentication realm sufficient or do
// we need some kind of hybrid if we expect both executors
// and operators/tooling to use this endpoint?
READWRITE_HTTP_AUTHENTICATION_REALM,
Http::API_HELP(),
[this](const process::http::Request& request,
const Option<string>& principal) {
Http::log(request);
return http.api(request, principal);
},
options);
route("/api/v1/executor",
Http::EXECUTOR_HELP(),
[this](const process::http::Request& request) {
Http::log(request);
return http.executor(request);
});
// TODO(ijimenez): Remove this endpoint at the end of the
// deprecation cycle on 0.26.
route("/state.json",
READONLY_HTTP_AUTHENTICATION_REALM,
Http::STATE_HELP(),
[this](const process::http::Request& request,
const Option<string>& principal) {
Http::log(request);
return http.state(request, principal);
});
route("/state",
READONLY_HTTP_AUTHENTICATION_REALM,
Http::STATE_HELP(),
[this](const process::http::Request& request,
const Option<string>& principal) {
Http::log(request);
return http.state(request, principal);
});
route("/flags",
READONLY_HTTP_AUTHENTICATION_REALM,
Http::FLAGS_HELP(),
[this](const process::http::Request& request,
const Option<string>& principal) {
Http::log(request);
return http.flags(request, principal);
});
route("/health",
Http::HEALTH_HELP(),
[this](const process::http::Request& request) {
return http.health(request);
});
route("/monitor/statistics",
READONLY_HTTP_AUTHENTICATION_REALM,
Http::STATISTICS_HELP(),
[this](const process::http::Request& request,
const Option<string>& principal) {
return http.statistics(request, principal);
});
// TODO(ijimenez): Remove this endpoint at the end of the
// deprecation cycle on 0.26.
route("/monitor/statistics.json",
READONLY_HTTP_AUTHENTICATION_REALM,
Http::STATISTICS_HELP(),
[this](const process::http::Request& request,
const Option<string>& principal) {
return http.statistics(request, principal);
});
route("/containers",
READONLY_HTTP_AUTHENTICATION_REALM,
Http::CONTAINERS_HELP(),
[this](const process::http::Request& request,
const Option<string>& principal) {
return http.containers(request, principal);
});
const PID<Slave> slavePid = self();
auto authorize = [slavePid](const Option<string>& principal) {
return dispatch(
slavePid,
&Slave::authorizeLogAccess,
principal);
};
// Expose the log file for the webui. Fall back to 'log_dir' if
// an explicit file was not specified.
if (flags.external_log_file.isSome()) {
files->attach(flags.external_log_file.get(), "/slave/log", authorize)
.onAny(defer(self(),
&Self::fileAttached,
lambda::_1,
flags.external_log_file.get()));
} else if (flags.log_dir.isSome()) {
Try<string> log =
logging::getLogFile(logging::getLogSeverity(flags.logging_level));
if (log.isError()) {
LOG(ERROR) << "Agent log file cannot be found: " << log.error();
} else {
files->attach(log.get(), "/slave/log", authorize)
.onAny(defer(self(), &Self::fileAttached, lambda::_1, log.get()));
}
}
// Check that the recover flag is valid.
if (flags.recover != "reconnect" && flags.recover != "cleanup") {
EXIT(EXIT_FAILURE)
<< "Unknown option for 'recover' flag " << flags.recover << "."
<< " Please run the agent with '--help' to see the valid options";
}
auto signalHandler = defer(self(), &Slave::signaled, lambda::_1, lambda::_2)
.operator std::function<void(int, int)>();
#ifdef __WINDOWS__
if (!os::internal::installCtrlHandler(&signalHandler)) {
EXIT(EXIT_FAILURE)
<< "Failed to configure console handlers: " << WindowsError().message;
}
#else
if (os::internal::configureSignal(&signalHandler) < 0) {
EXIT(EXIT_FAILURE)
<< "Failed to configure signal handlers: " << os::strerror(errno);
}
#endif // __WINDOWS__
// Do recovery.
async(&state::recover, metaDir, flags.strict)
.then(defer(self(), &Slave::recover, lambda::_1))
.then(defer(self(), &Slave::_recover))
.onAny(defer(self(), &Slave::__recover, lambda::_1));
}
void Slave::finalize()
{
LOG(INFO) << "Agent terminating";
// NOTE: We use 'frameworks.keys()' here because 'shutdownFramework'
// can potentially remove a framework from 'frameworks'.
foreach (const FrameworkID& frameworkId, frameworks.keys()) {
// TODO(benh): Because a shut down isn't instantaneous (but has
// a shut down/kill phases) we might not actually propagate all
// the status updates appropriately here. Consider providing
// an alternative function which skips the shut down phase and
// simply does a kill (sending all status updates
// immediately). Of course, this still isn't sufficient
// because those status updates might get lost and we won't
// resend them unless we build that into the system.
// NOTE: We shut down the framework only if it has disabled
// checkpointing. This is because slave recovery tests terminate
// the slave to simulate slave restart.
if (!frameworks[frameworkId]->info.checkpoint()) {
shutdownFramework(UPID(), frameworkId);
}
}
if (state == TERMINATING) {
// We remove the "latest" symlink in meta directory, so that the
// slave doesn't recover the state when it restarts and registers
// as a new slave with the master.
if (os::exists(paths::getLatestSlavePath(metaDir))) {
CHECK_SOME(os::rm(paths::getLatestSlavePath(metaDir)));
}
}
}
void Slave::shutdown(const UPID& from, const string& message)
{
if (from && master != from) {
LOG(WARNING) << "Ignoring shutdown message from " << from
<< " because it is not from the registered master: "
<< (master.isSome() ? stringify(master.get()) : "None");
return;
}
if (from) {
LOG(INFO) << "Agent asked to shut down by " << from
<< (message.empty() ? "" : " because '" + message + "'");
} else if (info.has_id()) {
if (message.empty()) {
LOG(INFO) << "Unregistering and shutting down";
} else {
LOG(INFO) << message << "; unregistering and shutting down";
}
UnregisterSlaveMessage message_;
message_.mutable_slave_id()->MergeFrom(info.id());
send(master.get(), message_);
} else {
if (message.empty()) {
LOG(INFO) << "Shutting down";
} else {
LOG(INFO) << message << "; shutting down";
}
}
state = TERMINATING;
if (frameworks.empty()) { // Terminate slave if there are no frameworks.
terminate(self());
} else {
// NOTE: The slave will terminate after all the executors have
// terminated.
// NOTE: We use 'frameworks.keys()' here because 'shutdownFramework'
// can potentially remove a framework from 'frameworks'.
foreach (const FrameworkID& frameworkId, frameworks.keys()) {
shutdownFramework(from, frameworkId);
}
}
}
void Slave::fileAttached(const Future<Nothing>& result, const string& path)
{
if (result.isReady()) {
VLOG(1) << "Successfully attached file '" << path << "'";
} else {
LOG(ERROR) << "Failed to attach file '" << path << "': "
<< (result.isFailed() ? result.failure() : "discarded");
}
}
// TODO(vinod/bmahler): Get rid of this helper.
Nothing Slave::detachFile(const string& path)
{
files->detach(path);
return Nothing();
}
void Slave::detected(const Future<Option<MasterInfo>>& _master)
{
CHECK(state == DISCONNECTED ||
state == RUNNING ||
state == TERMINATING) << state;
if (state != TERMINATING) {
state = DISCONNECTED;
}
// Pause the status updates.
statusUpdateManager->pause();
if (_master.isFailed()) {
EXIT(EXIT_FAILURE) << "Failed to detect a master: " << _master.failure();
}
Option<MasterInfo> latest;
if (_master.isDiscarded()) {
LOG(INFO) << "Re-detecting master";
latest = None();
master = None();
} else if (_master.get().isNone()) {
LOG(INFO) << "Lost leading master";
latest = None();
master = None();
} else {
latest = _master.get();
master = UPID(_master.get().get().pid());
LOG(INFO) << "New master detected at " << master.get();
// Cancel the pending registration timer to avoid spurious attempts
// at reregistration. `Clock::cancel` is idempotent, so this call
// is safe even if no timer is active or pending.
Clock::cancel(agentRegistrationTimer);
if (state == TERMINATING) {
LOG(INFO) << "Skipping registration because agent is terminating";
return;
}
// Wait for a random amount of time before authentication or
// registration.
Duration duration =
flags.registration_backoff_factor * ((double) os::random() / RAND_MAX);
if (credential.isSome()) {
// Authenticate with the master.
// TODO(vinod): Consider adding an "AUTHENTICATED" state to the
// slave instead of "authenticate" variable.
delay(duration, self(), &Slave::authenticate);
} else {
// Proceed with registration without authentication.
LOG(INFO) << "No credentials provided."
<< " Attempting to register without authentication";
delay(duration,
self(),
&Slave::doReliableRegistration,
flags.registration_backoff_factor * 2); // Backoff.
}
}
// Keep detecting masters.
LOG(INFO) << "Detecting new master";
detection = detector->detect(latest)
.onAny(defer(self(), &Slave::detected, lambda::_1));
}
void Slave::authenticate()
{
authenticated = false;
if (master.isNone()) {
return;
}
if (authenticating.isSome()) {
// Authentication is in progress. Try to cancel it.
// Note that it is possible that 'authenticating' is ready
// and the dispatch to '_authenticate' is enqueued when we
// are here, making the 'discard' here a no-op. This is ok
// because we set 'reauthenticate' here which enforces a retry
// in '_authenticate'.
Future<bool> authenticating_ = authenticating.get();
authenticating_.discard();
reauthenticate = true;
return;
}
LOG(INFO) << "Authenticating with master " << master.get();
// Ensure there is a link to the master before we start
// communicating with it.
link(master.get());
CHECK(authenticatee == nullptr);