/
master.cpp
12907 lines (10509 loc) · 428 KB
/
master.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 <stdint.h>
#include <algorithm>
#include <cctype>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iterator>
#include <list>
#include <memory>
#include <set>
#include <sstream>
#include <tuple>
#include <utility>
#include <mesos/module.hpp>
#include <mesos/resource_quantities.hpp>
#include <mesos/roles.hpp>
#include <mesos/authentication/authenticator.hpp>
#include <mesos/authorizer/authorizer.hpp>
#include <mesos/allocator/allocator.hpp>
#include <mesos/master/contender.hpp>
#include <mesos/master/detector.hpp>
#include <mesos/module/authenticator.hpp>
#include <mesos/scheduler/scheduler.hpp>
#include <process/check.hpp>
#include <process/collect.hpp>
#include <process/defer.hpp>
#include <process/delay.hpp>
#include <process/http.hpp>
#include <process/id.hpp>
#include <process/limiter.hpp>
#include <process/owned.hpp>
#include <process/run.hpp>
#include <process/shared.hpp>
#include <process/metrics/metrics.hpp>
#include <stout/check.hpp>
#include <stout/duration.hpp>
#include <stout/error.hpp>
#include <stout/foreach.hpp>
#include <stout/ip.hpp>
#include <stout/lambda.hpp>
#include <stout/multihashmap.hpp>
#include <stout/net.hpp>
#include <stout/nothing.hpp>
#include <stout/numify.hpp>
#include <stout/option.hpp>
#include <stout/path.hpp>
#include <stout/stringify.hpp>
#include <stout/unreachable.hpp>
#include <stout/utils.hpp>
#include <stout/uuid.hpp>
#include "authentication/cram_md5/authenticator.hpp"
#include "common/authorization.hpp"
#include "common/build.hpp"
#include "common/http.hpp"
#include "common/protobuf_utils.hpp"
#include "common/status_utils.hpp"
#include "credentials/credentials.hpp"
#include "hook/manager.hpp"
#include "logging/flags.hpp"
#include "logging/logging.hpp"
#include "master/authorization.hpp"
#include "master/flags.hpp"
#include "master/master.hpp"
#include "master/registry_operations.hpp"
#include "master/weights.hpp"
#include "module/manager.hpp"
#include "watcher/whitelist_watcher.hpp"
using std::list;
using std::make_move_iterator;
using std::reference_wrapper;
using std::set;
using std::shared_ptr;
using std::string;
using std::tie;
using std::tuple;
using std::vector;
using process::await;
using process::wait; // Necessary on some OS's to disambiguate.
using process::Clock;
using process::ExitedEvent;
using process::Failure;
using process::Future;
using process::MessageEvent;
using process::Owned;
using process::PID;
using process::Process;
using process::Promise;
using process::RateLimiter;
using process::Shared;
using process::Time;
using process::Timer;
using process::UPID;
using process::http::Pipe;
using process::http::authentication::Principal;
using process::metrics::Counter;
using google::protobuf::RepeatedPtrField;
namespace mesos {
namespace internal {
namespace master {
using mesos::allocator::Allocator;
using mesos::authorization::createSubject;
using mesos::authorization::VIEW_ROLE;
using mesos::authorization::VIEW_FRAMEWORK;
using mesos::authorization::VIEW_TASK;
using mesos::authorization::VIEW_EXECUTOR;
using mesos::authorization::ActionObject;
using mesos::master::contender::MasterContender;
using mesos::master::detector::MasterDetector;
static bool isValidFailoverTimeout(const FrameworkInfo& frameworkInfo);
class SlaveObserver : public ProtobufProcess<SlaveObserver>
{
public:
SlaveObserver(const UPID& _slave,
const SlaveInfo& _slaveInfo,
const SlaveID& _slaveId,
const PID<Master>& _master,
const Option<shared_ptr<RateLimiter>>& _limiter,
const shared_ptr<Metrics>& _metrics,
const Duration& _slavePingTimeout,
const size_t _maxSlavePingTimeouts)
: ProcessBase(process::ID::generate("slave-observer")),
slave(_slave),
slaveInfo(_slaveInfo),
slaveId(_slaveId),
master(_master),
limiter(_limiter),
metrics(_metrics),
slavePingTimeout(_slavePingTimeout),
maxSlavePingTimeouts(_maxSlavePingTimeouts),
timeouts(0),
pinged(false),
connected(true)
{
install<PongSlaveMessage>(&SlaveObserver::pong);
}
void reconnect()
{
connected = true;
}
void disconnect()
{
connected = false;
}
protected:
void initialize() override
{
ping();
}
void ping()
{
PingSlaveMessage message;
message.set_connected(connected);
send(slave, message);
pinged = true;
delay(slavePingTimeout, self(), &SlaveObserver::timeout);
}
void pong()
{
timeouts = 0;
pinged = false;
// Cancel any pending unreachable transitions.
if (markingUnreachable.isSome()) {
// Need a copy for non-const access.
Future<Nothing> future = markingUnreachable.get();
future.discard();
}
}
void timeout()
{
if (pinged) {
timeouts++; // No pong has been received before the timeout.
if (timeouts >= maxSlavePingTimeouts) {
// No pong has been received for the last
// 'maxSlavePingTimeouts' pings.
markUnreachable();
}
}
// NOTE: We keep pinging even if we schedule a transition to
// UNREACHABLE. This is because if the slave eventually responds
// to a ping, we can cancel the UNREACHABLE transition.
ping();
}
// Marking slaves unreachable is rate-limited and can be canceled if
// a pong is received before `_markUnreachable` is called.
//
// TODO(neilc): Using a rate-limit when marking slaves unreachable
// is only necessary for frameworks that are not PARTITION_AWARE.
// For such frameworks, we shutdown their tasks when an unreachable
// agent reregisters, so a rate-limit is a useful safety
// precaution. Once all frameworks are PARTITION_AWARE, we can
// likely remove the rate-limit (MESOS-5948).
void markUnreachable()
{
if (markingUnreachable.isSome()) {
return; // Unreachable transition is already in progress.
}
Future<Nothing> acquire = Nothing();
if (limiter.isSome()) {
LOG(INFO) << "Scheduling transition of agent " << slaveId
<< " to UNREACHABLE because of health check timeout";
acquire = limiter.get()->acquire();
}
markingUnreachable = acquire.onAny(defer(self(), &Self::_markUnreachable));
++metrics->slave_unreachable_scheduled;
}
void _markUnreachable()
{
CHECK_SOME(markingUnreachable);
const Future<Nothing>& future = markingUnreachable.get();
CHECK(!future.isFailed());
if (future.isReady()) {
++metrics->slave_unreachable_completed;
dispatch(master,
&Master::markUnreachable,
slaveInfo,
false,
"health check timed out");
} else if (future.isDiscarded()) {
LOG(INFO) << "Canceling transition of agent " << slaveId
<< " to UNREACHABLE because a pong was received!";
++metrics->slave_unreachable_canceled;
}
markingUnreachable = None();
}
private:
const UPID slave;
const SlaveInfo slaveInfo;
const SlaveID slaveId;
const PID<Master> master;
const Option<shared_ptr<RateLimiter>> limiter;
shared_ptr<Metrics> metrics;
Option<Future<Nothing>> markingUnreachable;
const Duration slavePingTimeout;
const size_t maxSlavePingTimeouts;
uint32_t timeouts;
bool pinged;
bool connected;
};
Master::Master(
Allocator* _allocator,
Registrar* _registrar,
Files* _files,
MasterContender* _contender,
MasterDetector* _detector,
const Option<Authorizer*>& _authorizer,
const Option<shared_ptr<RateLimiter>>& _slaveRemovalLimiter,
const Flags& _flags)
: ProcessBase("master"),
flags(_flags),
http(this),
allocator(_allocator),
registrar(_registrar),
files(_files),
contender(_contender),
detector(_detector),
authorizer(_authorizer),
frameworks(flags),
subscribers(this, flags.max_operator_event_stream_subscribers),
authenticator(None()),
metrics(new Metrics(*this)),
electedTime(None())
{
slaves.limiter = _slaveRemovalLimiter;
// NOTE: We populate 'info_' here instead of inside 'initialize()'
// because 'StandaloneMasterDetector' needs access to the info.
// Master ID is generated randomly based on UUID.
info_.set_id(id::UUID::random().toString());
// NOTE: Currently, we store ip in MasterInfo in network order,
// which should be fixed. See MESOS-1201 for details.
// TODO(marco): The ip, port, hostname fields above are
// being deprecated; the code should be removed once
// the deprecation cycle is complete.
info_.set_ip(self().address.ip.in()->s_addr);
info_.set_port(self().address.port);
info_.set_pid(self());
info_.set_version(MESOS_VERSION);
for (const MasterInfo::Capability& capability : MASTER_CAPABILITIES()) {
info_.add_capabilities()->CopyFrom(capability);
}
// 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();
}
info_.set_hostname(hostname);
// This uses the new `Address` message in `MasterInfo`.
info_.mutable_address()->set_ip(stringify(self().address.ip));
info_.mutable_address()->set_port(self().address.port);
info_.mutable_address()->set_hostname(hostname);
if (flags.domain.isSome()) {
info_.mutable_domain()->CopyFrom(flags.domain.get());
}
}
Master::~Master() {}
hashset<string> Master::missingMinimumCapabilities(
const MasterInfo& masterInfo, const Registry& registry)
{
if (registry.minimum_capabilities().size() == 0) {
return hashset<string>();
}
hashset<string> minimumCapabilities, masterCapabilities;
foreach (
const Registry::MinimumCapability& minimumCapability,
registry.minimum_capabilities()) {
minimumCapabilities.insert(minimumCapability.capability());
}
foreach (
const MasterInfo::Capability& masterCapability,
masterInfo.capabilities()) {
masterCapabilities.insert(
MasterInfo::Capability::Type_Name(masterCapability.type()));
}
return minimumCapabilities - masterCapabilities;
}
// TODO(vinod): Update this interface to return failed futures when
// capacity is reached.
struct BoundedRateLimiter
{
BoundedRateLimiter(double qps, Option<uint64_t> _capacity)
: limiter(new process::RateLimiter(qps)),
capacity(_capacity),
messages(0) {}
process::Owned<process::RateLimiter> limiter;
const Option<uint64_t> capacity;
// Number of outstanding messages for this RateLimiter.
// NOTE: ExitedEvents are throttled but not counted towards
// the capacity here.
uint64_t messages;
};
void Master::initialize()
{
LOG(INFO) << "Master " << info_.id() << " (" << info_.hostname() << ")"
<< " started on " << string(self()).substr(7);
LOG(INFO) << "Flags at startup: " << flags;
if (process::address().ip.isLoopback()) {
LOG(WARNING) << "\n**************************************************\n"
<< "Master bound to loopback interface!"
<< " Cannot communicate with remote schedulers or agents."
<< " You might want to set '--ip' flag to a routable"
<< " IP address.\n"
<< "**************************************************";
}
// NOTE: We enforce a minimum slave reregister timeout because the
// slave bounds its (re-)registration retries based on the minimum.
if (flags.agent_reregister_timeout < MIN_AGENT_REREGISTER_TIMEOUT) {
EXIT(EXIT_FAILURE)
<< "Invalid value '" << flags.agent_reregister_timeout << "'"
<< " for --agent_reregister_timeout:"
<< " Must be at least " << MIN_AGENT_REREGISTER_TIMEOUT;
}
// Parse the percentage for the slave removal limit.
// TODO(bmahler): Add a 'Percentage' abstraction.
if (!strings::endsWith(flags.recovery_agent_removal_limit, "%")) {
EXIT(EXIT_FAILURE)
<< "Invalid value '" << flags.recovery_agent_removal_limit << "'"
<< " for --recovery_agent_removal_percent_limit: " << "missing '%'";
}
Try<double> limit = numify<double>(
strings::remove(
flags.recovery_agent_removal_limit,
"%",
strings::SUFFIX));
if (limit.isError()) {
EXIT(EXIT_FAILURE)
<< "Invalid value '" << flags.recovery_agent_removal_limit << "'"
<< " for --recovery_agent_removal_percent_limit: " << limit.error();
}
if (limit.get() < 0.0 || limit.get() > 100.0) {
EXIT(EXIT_FAILURE)
<< "Invalid value '" << flags.recovery_agent_removal_limit << "'"
<< " for --recovery_agent_removal_percent_limit:"
<< " Must be within [0%-100%]";
}
// Log authentication state.
if (flags.authenticate_frameworks) {
LOG(INFO) << "Master only allowing authenticated frameworks to register";
} else {
LOG(INFO) << "Master allowing unauthenticated frameworks to register";
}
if (flags.authenticate_agents) {
LOG(INFO) << "Master only allowing authenticated agents to register";
} else {
LOG(INFO) << "Master allowing unauthenticated agents to register";
}
if (flags.authenticate_http_frameworks) {
LOG(INFO) << "Master only allowing authenticated HTTP frameworks to "
<< "register";
} else {
LOG(INFO) << "Master allowing HTTP frameworks to register without "
<< "authentication";
}
// Load credentials.
Option<Credentials> credentials;
if (flags.credentials.isSome()) {
Result<Credentials> _credentials =
credentials::read(flags.credentials.get());
if (_credentials.isError()) {
EXIT(EXIT_FAILURE) << _credentials.error() << " (see --credentials flag)";
} else if (_credentials.isNone()) {
EXIT(EXIT_FAILURE)
<< "Credentials file must contain at least one credential"
<< " (see --credentials flag)";
}
// Store credentials in master to use them in routes.
credentials = _credentials.get();
}
// Extract authenticator names and validate them.
authenticatorNames = strings::split(flags.authenticators, ",");
if (authenticatorNames.empty()) {
EXIT(EXIT_FAILURE) << "No authenticator specified";
}
if (authenticatorNames.size() > 1) {
EXIT(EXIT_FAILURE) << "Multiple authenticators not supported";
}
if (authenticatorNames[0] != DEFAULT_AUTHENTICATOR &&
!modules::ModuleManager::contains<Authenticator>(
authenticatorNames[0])) {
EXIT(EXIT_FAILURE)
<< "Authenticator '" << authenticatorNames[0] << "' not found."
<< " Check the spelling (compare to '" << DEFAULT_AUTHENTICATOR << "')"
<< " or verify that the authenticator was loaded successfully"
<< " (see --modules)";
}
// TODO(tillt): Allow multiple authenticators to be loaded and enable
// the authenticatee to select the appropriate one. See MESOS-1939.
if (authenticatorNames[0] == DEFAULT_AUTHENTICATOR) {
LOG(INFO) << "Using default '" << DEFAULT_AUTHENTICATOR
<< "' authenticator";
authenticator = new cram_md5::CRAMMD5Authenticator();
} else {
Try<Authenticator*> module =
modules::ModuleManager::create<Authenticator>(authenticatorNames[0]);
if (module.isError()) {
EXIT(EXIT_FAILURE)
<< "Could not create authenticator module '"
<< authenticatorNames[0] << "': " << module.error();
}
LOG(INFO) << "Using '" << authenticatorNames[0] << "' authenticator";
authenticator = module.get();
}
// Give Authenticator access to credentials when needed.
CHECK_SOME(authenticator);
Try<Nothing> initialize = authenticator.get()->initialize(credentials);
if (initialize.isError()) {
const string error =
"Failed to initialize authenticator '" + authenticatorNames[0] +
"': " + initialize.error();
if (flags.authenticate_frameworks || flags.authenticate_agents) {
EXIT(EXIT_FAILURE)
<< "Failed to start master with authentication enabled: " << error;
} else {
// A failure to initialize the authenticator does lead to
// unusable authentication but still allows non authenticating
// frameworks and slaves to connect.
LOG(WARNING) << "Only non-authenticating frameworks and agents are "
<< "allowed to connect. "
<< "Authentication is disabled: " << error;
delete authenticator.get();
authenticator = None();
}
}
if (flags.authenticate_http_readonly) {
Try<Nothing> result = initializeHttpAuthenticators(
READONLY_HTTP_AUTHENTICATION_REALM,
strings::split(flags.http_authenticators, ","),
credentials);
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, ","),
credentials);
if (result.isError()) {
EXIT(EXIT_FAILURE) << result.error();
}
}
if (flags.authenticate_http_frameworks) {
// The `--http_framework_authenticators` flag should always be set when HTTP
// framework authentication is enabled.
if (flags.http_framework_authenticators.isNone()) {
EXIT(EXIT_FAILURE)
<< "Missing `--http_framework_authenticators` flag. This must be used "
<< "in conjunction with `--authenticate_http_frameworks`";
}
Try<Nothing> result = initializeHttpAuthenticators(
DEFAULT_HTTP_FRAMEWORK_AUTHENTICATION_REALM,
strings::split(flags.http_framework_authenticators.get(), ","),
credentials);
if (result.isError()) {
EXIT(EXIT_FAILURE) << result.error();
}
}
if (authorizer.isSome()) {
LOG(INFO) << "Authorization enabled";
}
if (flags.rate_limits.isSome()) {
// Add framework rate limiters.
foreach (const RateLimit& limit_, flags.rate_limits->limits()) {
if (frameworks.limiters.contains(limit_.principal())) {
EXIT(EXIT_FAILURE)
<< "Duplicate principal " << limit_.principal()
<< " found in RateLimits configuration";
}
if (limit_.has_qps() && limit_.qps() <= 0) {
EXIT(EXIT_FAILURE)
<< "Invalid qps: " << limit_.qps()
<< ". It must be a positive number";
}
if (limit_.has_qps()) {
Option<uint64_t> capacity;
if (limit_.has_capacity()) {
capacity = limit_.capacity();
}
frameworks.limiters.put(
limit_.principal(),
Owned<BoundedRateLimiter>(
new BoundedRateLimiter(limit_.qps(), capacity)));
} else {
frameworks.limiters.put(limit_.principal(), None());
}
}
if (flags.rate_limits->has_aggregate_default_qps() &&
flags.rate_limits->aggregate_default_qps() <= 0) {
EXIT(EXIT_FAILURE)
<< "Invalid aggregate_default_qps: "
<< flags.rate_limits->aggregate_default_qps()
<< ". It must be a positive number";
}
if (flags.rate_limits->has_aggregate_default_qps()) {
Option<uint64_t> capacity;
if (flags.rate_limits->has_aggregate_default_capacity()) {
capacity = flags.rate_limits->aggregate_default_capacity();
}
frameworks.defaultLimiter =
Owned<BoundedRateLimiter>(new BoundedRateLimiter(
flags.rate_limits->aggregate_default_qps(), capacity));
}
LOG(INFO) << "Framework rate limiting enabled";
}
// If the rate limiter is injected for testing,
// the flag may not be set.
if (slaves.limiter.isSome() && flags.agent_removal_rate_limit.isSome()) {
LOG(INFO) << "Agent removal is rate limited to "
<< flags.agent_removal_rate_limit.get();
}
// If "--roles" is set, configure the role whitelist.
// TODO(neilc): Remove support for explicit roles in ~Mesos 0.32.
if (flags.roles.isSome()) {
LOG(WARNING) << "The '--roles' flag is deprecated. This flag will be "
<< "removed in the future. See the Mesos 0.27 upgrade "
<< "notes for more information";
Try<vector<string>> roles = roles::parse(flags.roles.get());
if (roles.isError()) {
EXIT(EXIT_FAILURE) << "Failed to parse roles: " << roles.error();
}
roleWhitelist = hashset<string>();
foreach (const string& role, roles.get()) {
roleWhitelist->insert(role);
}
if (roleWhitelist->size() < roles->size()) {
LOG(WARNING) << "Duplicate values in '--roles': " << flags.roles.get();
}
// The default role is always allowed.
roleWhitelist->insert("*");
}
// Add role weights.
if (flags.weights.isSome()) {
vector<string> tokens = strings::tokenize(flags.weights.get(), ",");
foreach (const string& token, tokens) {
vector<string> pair = strings::tokenize(token, "=");
if (pair.size() != 2) {
EXIT(EXIT_FAILURE)
<< "Invalid weight: '" << token << "'. --weights should"
<< " be of the form 'role=weight,role=weight'";
} else if (!isWhitelistedRole(pair[0])) {
EXIT(EXIT_FAILURE)
<< "Invalid weight: '" << token << "'. " << pair[0]
<< " is not a valid role";
}
double weight = atof(pair[1].c_str());
if (weight <= 0) {
EXIT(EXIT_FAILURE)
<< "Invalid weight: '" << token << "'. Weights must be positive";
}
weights[pair[0]] = weight;
}
}
// Verify the timeout is greater than zero.
if (flags.offer_timeout.isSome() &&
flags.offer_timeout.get() <= Duration::zero()) {
EXIT(EXIT_FAILURE)
<< "Invalid value '" << flags.offer_timeout.get() << "'"
<< " for --offer_timeout: Must be greater than zero";
}
// Parse min_allocatable_resources.
vector<ResourceQuantities> minAllocatableResources;
foreach (
const string& token,
strings::tokenize(flags.min_allocatable_resources, "|")) {
Try<ResourceQuantities> resourceQuantities =
ResourceQuantities::fromString(token);
if (resourceQuantities.isError()) {
EXIT(EXIT_FAILURE) << "Error parsing min_allocatable_resources '"
<< flags.min_allocatable_resources
<< "': " << resourceQuantities.error();
}
// We check the configuration against first-class resources and warn
// against possible mis-configuration (e.g. typo).
set<string> firstClassResources = {"cpus", "mem", "disk", "ports", "gpus"};
for (auto it = resourceQuantities->begin(); it != resourceQuantities->end();
++it) {
if (firstClassResources.count(it->first) == 0) {
LOG(WARNING) << "Non-first-class resource '" << it->first
<< "' is configured as part of min_allocatable_resources";
}
}
minAllocatableResources.push_back(resourceQuantities.get());
}
// Initialize the allocator options.
mesos::allocator::Options options;
options.allocationInterval = flags.allocation_interval;
options.fairnessExcludeResourceNames =
flags.fair_sharing_excluded_resource_names;
options.filterGpuResources = flags.filter_gpu_resources;
options.domain = flags.domain;
options.minAllocatableResources = minAllocatableResources;
options.maxCompletedFrameworks = flags.max_completed_frameworks;
options.publishPerFrameworkMetrics = flags.publish_per_framework_metrics;
// Initialize the allocator.
allocator->initialize(
options,
defer(self(), &Master::offer, lambda::_1, lambda::_2),
defer(self(), &Master::inverseOffer, lambda::_1, lambda::_2));
// Parse the whitelist. Passing Allocator::updateWhitelist()
// callback is safe because we shut down the whitelistWatcher in
// Master::finalize(), while allocator lifetime is greater than
// masters. Therefore there is no risk of calling into an allocator
// that has been cleaned up.
whitelistWatcher = new WhitelistWatcher(
flags.whitelist,
WHITELIST_WATCH_INTERVAL,
[this](const Option<hashset<string>>& whitelist) {
return allocator->updateWhitelist(whitelist);
});
spawn(whitelistWatcher);
nextFrameworkId = 0;
nextSlaveId = 0;
nextOfferId = 0;
startTime = Clock::now();
install<scheduler::Call>(&Master::receive);
// Install handler functions for certain messages.
install<SubmitSchedulerRequest>(
&Master::submitScheduler,
&SubmitSchedulerRequest::name);
install<RegisterFrameworkMessage>(
&Master::registerFramework);
install<ReregisterFrameworkMessage>(
&Master::reregisterFramework);
install<UnregisterFrameworkMessage>(
&Master::unregisterFramework,
&UnregisterFrameworkMessage::framework_id);
install<DeactivateFrameworkMessage>(
&Master::deactivateFramework,
&DeactivateFrameworkMessage::framework_id);
install<ResourceRequestMessage>(
&Master::resourceRequest,
&ResourceRequestMessage::framework_id,
&ResourceRequestMessage::requests);
install<LaunchTasksMessage>(
&Master::launchTasks);
install<ReviveOffersMessage>(
&Master::reviveOffers,
&ReviveOffersMessage::framework_id,
&ReviveOffersMessage::roles);
install<KillTaskMessage>(
&Master::killTask,
&KillTaskMessage::framework_id,
&KillTaskMessage::task_id);
install<StatusUpdateAcknowledgementMessage>(
&Master::statusUpdateAcknowledgement);
install<FrameworkToExecutorMessage>(
&Master::schedulerMessage);
install<RegisterSlaveMessage>(
&Master::registerSlave);
install<ReregisterSlaveMessage>(
&Master::reregisterSlave);
install<UnregisterSlaveMessage>(
&Master::unregisterSlave,
&UnregisterSlaveMessage::slave_id);
install<StatusUpdateMessage>(
&Master::statusUpdate);
// Added in 0.24.0 to support HTTP schedulers. Since
// these do not have a pid, the slave must forward
// messages through the master.
install<ExecutorToFrameworkMessage>(
&Master::executorMessage);
install<ReconcileTasksMessage>(
&Master::reconcileTasks);
install<UpdateOperationStatusMessage>(
&Master::updateOperationStatus);
install<ExitedExecutorMessage>(
&Master::exitedExecutor,
&ExitedExecutorMessage::slave_id,
&ExitedExecutorMessage::framework_id,
&ExitedExecutorMessage::executor_id,
&ExitedExecutorMessage::status);
install<UpdateSlaveMessage>(&Master::updateSlave);
install<AuthenticateMessage>(
&Master::authenticate,
&AuthenticateMessage::pid);
// Setup HTTP routes.
route("/api/v1",
// TODO(benh): Is this authentication realm sufficient or do
// we need some kind of hybrid if we expect both schedulers
// and operators/tooling to use this endpoint?
READWRITE_HTTP_AUTHENTICATION_REALM,
Http::API_HELP(),
[this](const process::http::Request& request,
const Option<Principal>& principal) {
logRequest(request);
return http.api(request, principal);
});
route("/api/v1/scheduler",
DEFAULT_HTTP_FRAMEWORK_AUTHENTICATION_REALM,
Http::SCHEDULER_HELP(),
[this](const process::http::Request& request,
const Option<Principal>& principal) {
logRequest(request);
return http.scheduler(request, principal);
});
route("/create-volumes",
READWRITE_HTTP_AUTHENTICATION_REALM,
Http::CREATE_VOLUMES_HELP(),
[this](const process::http::Request& request,
const Option<Principal>& principal) {
logRequest(request);
return http.createVolumes(request, principal);
});
route("/destroy-volumes",
READWRITE_HTTP_AUTHENTICATION_REALM,
Http::DESTROY_VOLUMES_HELP(),
[this](const process::http::Request& request,
const Option<Principal>& principal) {
logRequest(request);
return http.destroyVolumes(request, principal);
});
route("/frameworks",
READONLY_HTTP_AUTHENTICATION_REALM,
Http::FRAMEWORKS_HELP(),
[this](const process::http::Request& request,
const Option<Principal>& principal) {
logRequest(request);
return http.frameworks(request, principal)
.onReady([request](const process::http::Response& response) {
logResponse(request, response);
});
});
route("/flags",
READONLY_HTTP_AUTHENTICATION_REALM,
Http::FLAGS_HELP(),
[this](const process::http::Request& request,
const Option<Principal>& principal) {
logRequest(request);
return http.flags(request, principal);
});
route("/health",
Http::HEALTH_HELP(),
[this](const process::http::Request& request) {
return http.health(request);
});
route("/redirect",
Http::REDIRECT_HELP(),
[this](const process::http::Request& request) {
return http.redirect(request);
});
route("/reserve",
READWRITE_HTTP_AUTHENTICATION_REALM,
Http::RESERVE_HELP(),
[this](const process::http::Request& request,
const Option<Principal>& principal) {
logRequest(request);
return http.reserve(request, principal);
});
route("/roles",
READONLY_HTTP_AUTHENTICATION_REALM,
Http::ROLES_HELP(),
[this](const process::http::Request& request,
const Option<Principal>& principal) {
logRequest(request);
return http.roles(request, principal);
});
route("/teardown",
READWRITE_HTTP_AUTHENTICATION_REALM,
Http::TEARDOWN_HELP(),
[this](const process::http::Request& request,
const Option<Principal>& principal) {
logRequest(request);
return http.teardown(request, principal);
});
route("/slaves",
READONLY_HTTP_AUTHENTICATION_REALM,
Http::SLAVES_HELP(),
[this](const process::http::Request& request,
const Option<Principal>& principal) {
logRequest(request);
return http.slaves(request, principal)
.onReady([request](const process::http::Response& response) {
logResponse(request, response);
});
});
route("/state",
READONLY_HTTP_AUTHENTICATION_REALM,