-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathsched.cpp
2535 lines (2038 loc) · 71.5 KB
/
sched.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.
#ifndef __WINDOWS__
#include <dlfcn.h>
#endif // __WINDOWS__
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef __WINDOWS__
#include <unistd.h>
#endif // __WINDOWS__
#ifndef __WINDOWS__
#include <arpa/inet.h>
#endif // __WINDOWS__
#include <cmath>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <mesos/mesos.hpp>
#include <mesos/module.hpp>
#include <mesos/scheduler.hpp>
#include <mesos/type_utils.hpp>
#include <mesos/authentication/authenticatee.hpp>
#include <mesos/master/detector.hpp>
#include <mesos/module/authenticatee.hpp>
#include <mesos/scheduler/scheduler.hpp>
#include <process/defer.hpp>
#include <process/delay.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/id.hpp>
#include <process/latch.hpp>
#include <process/owned.hpp>
#include <process/pid.hpp>
#include <process/process.hpp>
#include <process/protobuf.hpp>
#include <process/metrics/pull_gauge.hpp>
#include <process/metrics/metrics.hpp>
#include <stout/abort.hpp>
#include <stout/check.hpp>
#include <stout/duration.hpp>
#include <stout/error.hpp>
#include <stout/flags.hpp>
#include <stout/hashmap.hpp>
#include <stout/ip.hpp>
#include <stout/lambda.hpp>
#include <stout/net.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/stopwatch.hpp>
#include <stout/utils.hpp>
#include <stout/uuid.hpp>
#include "authentication/cram_md5/authenticatee.hpp"
#include "common/protobuf_utils.hpp"
#include "local/flags.hpp"
#include "local/local.hpp"
#include "logging/flags.hpp"
#include "logging/logging.hpp"
#include "messages/messages.hpp"
#include "module/manager.hpp"
#include "sched/constants.hpp"
#include "sched/flags.hpp"
#include "version/version.hpp"
using namespace mesos;
using namespace mesos::internal;
using namespace mesos::internal::master;
using namespace mesos::scheduler;
using google::protobuf::RepeatedPtrField;
using mesos::scheduler::OfferConstraints;
using mesos::master::detector::MasterDetector;
using process::Clock;
using process::DispatchEvent;
using process::Future;
using process::Latch;
using process::MessageEvent;
using process::Process;
using process::UPID;
using std::map;
using std::make_move_iterator;
using std::mutex;
using std::shared_ptr;
using std::set;
using std::string;
using std::vector;
using std::weak_ptr;
using process::wait; // Necessary on some OS's to disambiguate.
using utils::copy;
namespace mesos {
namespace internal {
// The DetectorPool is responsible for tracking single detector per url
// to avoid having multiple detectors per url when multiple frameworks
// are instantiated per process. See MESOS-3595.
class DetectorPool
{
public:
virtual ~DetectorPool() {}
static Try<shared_ptr<MasterDetector>> get(const string& url)
{
synchronized (DetectorPool::instance()->poolMutex) {
// Get or create the `weak_ptr` map entry.
shared_ptr<MasterDetector> result =
DetectorPool::instance()->pool[url].lock();
if (result) {
// Return existing master detector.
return result;
} else {
// Else, create the master detector and record it in the map.
Try<MasterDetector*> detector = MasterDetector::create(url);
if (detector.isError()) {
return Error(detector.error());
}
result = shared_ptr<MasterDetector>(detector.get());
DetectorPool::instance()->pool[url] = result;
return result;
}
}
}
private:
// Hide the constructors and assignment operator.
DetectorPool() {}
DetectorPool(const DetectorPool&) = delete;
DetectorPool& operator=(const DetectorPool&) = delete;
// Instead of having multiple detectors for multiple frameworks,
// keep track of one detector per url.
hashmap<string, weak_ptr<MasterDetector>> pool;
std::mutex poolMutex;
// Internal Singleton.
static DetectorPool* instance()
{
static DetectorPool* singleton = new DetectorPool();
return singleton;
}
};
// The scheduler process (below) is responsible for interacting with
// the master and responding to Mesos API calls from scheduler
// drivers. In order to allow a message to be sent back to the master
// we allow friend functions to invoke 'send', 'post', etc. Therefore,
// we must make sure that any necessary synchronization is performed.
class SchedulerProcess : public ProtobufProcess<SchedulerProcess>
{
public:
SchedulerProcess(MesosSchedulerDriver* _driver,
Scheduler* _scheduler,
const FrameworkInfo& _framework,
const vector<string>& _suppressedRoles,
const Option<Credential>& _credential,
bool _implicitAcknowledgements,
const string& schedulerId,
MasterDetector* _detector,
const internal::scheduler::Flags& _flags,
std::recursive_mutex* _mutex,
Latch* _latch)
// We use a UUID here to ensure that the master can reliably
// distinguish between scheduler runs. Otherwise the master may
// receive a delayed ExitedEvent enqueued behind a
// re-registration, and deactivate the framework incorrectly.
// TODO(bmahler): Investigate better ways to solve this problem.
// Check if bidirectional links in Erlang provides better
// semantics:
// http://www.erlang.org/doc/reference_manual/processes.html#id84804.
// Consider using unique PIDs throughout libprocess and relying
// on name registration to identify the process without the PID.
: ProcessBase(schedulerId),
metrics(*this),
driver(_driver),
scheduler(_scheduler),
framework(_framework),
suppressedRoles(_suppressedRoles.begin(), _suppressedRoles.end()),
mutex(_mutex),
latch(_latch),
failover(_framework.has_id() && !framework.id().value().empty()),
connected(false),
sendUpdateFrameworkOnConnect(false),
running(true),
detector(_detector),
flags(_flags),
implicitAcknowledgements(_implicitAcknowledgements),
credential(_credential),
authenticatee(nullptr),
authenticating(None()),
authenticated(false),
reauthenticate(false),
failedAuthentications(0)
{
LOG(INFO) << "Version: " << MESOS_VERSION;
}
~SchedulerProcess() override
{
delete authenticatee;
}
protected:
void initialize() override
{
install<Event>(&SchedulerProcess::receive);
// TODO(benh): Get access to flags so that we can decide whether
// or not to make ZooKeeper verbose.
install<FrameworkRegisteredMessage>(
&SchedulerProcess::registered,
&FrameworkRegisteredMessage::framework_id,
&FrameworkRegisteredMessage::master_info);
install<FrameworkReregisteredMessage>(
&SchedulerProcess::reregistered,
&FrameworkReregisteredMessage::framework_id,
&FrameworkReregisteredMessage::master_info);
install<ResourceOffersMessage>(
&SchedulerProcess::resourceOffers,
&ResourceOffersMessage::offers,
&ResourceOffersMessage::pids);
install<RescindResourceOfferMessage>(
&SchedulerProcess::rescindOffer,
&RescindResourceOfferMessage::offer_id);
install<StatusUpdateMessage>(
&SchedulerProcess::statusUpdate,
&StatusUpdateMessage::update,
&StatusUpdateMessage::pid);
install<LostSlaveMessage>(
&SchedulerProcess::lostSlave,
&LostSlaveMessage::slave_id);
install<ExitedExecutorMessage>(
&SchedulerProcess::lostExecutor,
&ExitedExecutorMessage::executor_id,
&ExitedExecutorMessage::slave_id,
&ExitedExecutorMessage::status);
install<ExecutorToFrameworkMessage>(
&SchedulerProcess::frameworkMessage,
&ExecutorToFrameworkMessage::slave_id,
&ExecutorToFrameworkMessage::executor_id,
&ExecutorToFrameworkMessage::data);
install<FrameworkErrorMessage>(
&SchedulerProcess::error,
&FrameworkErrorMessage::message);
// Start detecting masters.
detector->detect()
.onAny(defer(self(), &SchedulerProcess::detected, lambda::_1));
}
void detected(const Future<Option<MasterInfo>>& _master)
{
if (!running.load()) {
VLOG(1) << "Ignoring the master change because the driver is not"
<< " running!";
return;
}
CHECK(!_master.isDiscarded());
if (_master.isFailed()) {
EXIT(EXIT_FAILURE) << "Failed to detect a master: " << _master.failure();
}
if (_master->isSome()) {
master = _master->get();
} else {
master = None();
}
if (connected) {
// There are three cases here:
// 1. The master failed.
// 2. The master failed over to a new master.
// 3. The master failed over to the same master.
// In any case, we will reconnect (possibly immediately), so we
// must notify schedulers of the disconnection.
Stopwatch stopwatch;
if (FLAGS_v >= 1) {
stopwatch.start();
}
scheduler->disconnected(driver);
VLOG(1) << "Scheduler::disconnected took " << stopwatch.elapsed();
}
connected = false;
if (master.isSome()) {
LOG(INFO) << "New master detected at " << master->pid();
link(master->pid());
// 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(frameworkRegistrationTimer);
if (credential.isSome()) {
// Authenticate with the master.
// TODO(adam-mesos): Consider adding an initial delay like we do for
// slave registration, to combat thundering herds on master failover.
authenticate(
flags.authentication_timeout_min,
std::min(
flags.authentication_timeout_min +
flags.authentication_backoff_factor * 2,
flags.authentication_timeout_max));
} else {
// Proceed with registration without authentication.
LOG(INFO) << "No credentials provided."
<< " Attempting to register without authentication";
// TODO(vinod): Similar to the slave add a random delay to the
// first registration attempt too. This needs fixing tests
// that expect scheduler to register even with clock paused
// (e.g., rate limiting tests).
doReliableRegistration(flags.registration_backoff_factor);
}
} else {
// In this case, we don't actually invoke Scheduler::error
// since we might get reconnected to a master imminently.
LOG(INFO) << "No master detected";
}
// Keep detecting masters.
detector->detect(_master.get())
.onAny(defer(self(), &SchedulerProcess::detected, lambda::_1));
}
void authenticate(Duration minTimeout, Duration maxTimeout)
{
if (!running.load()) {
VLOG(1) << "Ignoring authenticate because the driver is not running!";
return;
}
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'.
copy(authenticating.get()).discard();
reauthenticate = true;
return;
}
LOG(INFO) << "Authenticating with master " << master->pid();
CHECK_SOME(credential);
CHECK(authenticatee == nullptr);
if (flags.authenticatee == scheduler::DEFAULT_AUTHENTICATEE) {
LOG(INFO) << "Using default CRAM-MD5 authenticatee";
authenticatee = new cram_md5::CRAMMD5Authenticatee();
} else {
Try<Authenticatee*> module =
modules::ModuleManager::create<Authenticatee>(flags.authenticatee);
if (module.isError()) {
EXIT(EXIT_FAILURE)
<< "Could not create authenticatee module '"
<< flags.authenticatee << "': " << module.error();
}
LOG(INFO) << "Using '" << flags.authenticatee << "' authenticatee";
authenticatee = module.get();
}
// We pick a random duration between `minTimeout` and `maxTimeout`.
Duration timeout = minTimeout + (maxTimeout - minTimeout) *
((double)os::random() / RAND_MAX);
// NOTE: We do not pass 'Owned<Authenticatee>' here because doing
// so could make 'AuthenticateeProcess' responsible for deleting
// 'Authenticatee' causing a deadlock because the destructor of
// 'Authenticatee' waits on 'AuthenticateeProcess'.
// This will happen in the following scenario:
// --> 'AuthenticateeProcess' does a 'Future.set()'.
// --> '_authenticate()' is dispatched to this process.
// --> This process executes '_authenticatee()'.
// --> 'AuthenticateeProcess' removes the onAny callback
// from its queue which holds the last reference to
// 'Authenticatee'.
// --> '~Authenticatee()' is invoked by 'AuthenticateeProcess'.
// TODO(vinod): Consider using 'Shared' to 'Owned' upgrade.
authenticating =
authenticatee->authenticate(master->pid(), self(), credential.get())
.onAny(defer(self(), &Self::_authenticate, minTimeout, maxTimeout))
.after(timeout, [](Future<bool> future) {
// NOTE: Discarded future results in a retry in '_authenticate()'.
// This is a no-op if the future is already ready.
if (future.discard()) {
LOG(WARNING) << "Authentication timed out";
}
return future;
});
}
void _authenticate(Duration currentMinTimeout, Duration currentMaxTimeout)
{
if (!running.load()) {
VLOG(1) << "Ignoring _authenticate because the driver is not running!";
return;
}
delete CHECK_NOTNULL(authenticatee);
authenticatee = nullptr;
CHECK_SOME(authenticating);
const Future<bool>& future = authenticating.get();
if (master.isNone()) {
LOG(INFO) << "Ignoring _authenticate because the master is lost";
authenticating = None();
// Set it to false because we do not want further retries until
// a new master is detected.
// We obviously do not need to reauthenticate either even if
// 'reauthenticate' is currently true because the master is
// lost.
reauthenticate = false;
return;
}
if (reauthenticate || !future.isReady()) {
LOG(INFO)
<< "Failed to authenticate with master " << master->pid() << ": "
<< (reauthenticate ? "master changed" :
(future.isFailed() ? future.failure() : "future discarded"));
authenticating = None();
reauthenticate = false;
// TODO(vinod): Add a limit on number of retries.
// Grow the timeout range using exponential backoff:
//
// [min, min + factor * 2^0]
// [min, min + factor * 2^1]
// ...
// [min, min + factor * 2^N]
// ...
// [min, max] // Stop at max.
Duration maxTimeout =
currentMinTimeout + (currentMaxTimeout - currentMinTimeout) * 2;
authenticate(
currentMinTimeout,
std::min(maxTimeout, flags.authentication_timeout_max));
return;
}
if (!future.get()) {
LOG(ERROR) << "Master " << master->pid() << " refused authentication";
error("Master refused authentication");
return;
}
LOG(INFO) << "Successfully authenticated with master " << master->pid();
authenticated = true;
authenticating = None();
failedAuthentications = 0;
doReliableRegistration(flags.registration_backoff_factor);
}
void drop(const Event& event, const string& message)
{
// TODO(bmahler): Increment a metric.
LOG(WARNING) << "Dropping " << event.type() << ": " << message;
}
void receive(const UPID& from, const Event& event)
{
switch (event.type()) {
case Event::SUBSCRIBED: {
if (!event.has_subscribed()) {
drop(event, "Expecting 'subscribed' to be present");
break;
}
// The scheduler API requires a MasterInfo be passed during
// (re-)registration, so we rely on the MasterInfo provided
// by the detector. If it's None, the driver would have
// dropped the message.
if (master.isNone()) {
drop(event, "No master detected");
break;
}
const FrameworkID& frameworkId = event.subscribed().framework_id();
// 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(frameworkRegistrationTimer);
// We match the existing registration semantics of the
// driver, except for the 3rd case in MESOS-786 (since
// it requires non-local knowledge and schedulers could
// not have possibly relied on this case).
if (!framework.has_id() || framework.id().value().empty()) {
registered(from, frameworkId, master.get());
} else if (failover) {
registered(from, frameworkId, master.get());
} else {
reregistered(from, frameworkId, master.get());
}
break;
}
case Event::OFFERS: {
if (!event.has_offers()) {
drop(event, "Expecting 'offers' to be present");
break;
}
const vector<Offer> offers =
google::protobuf::convert(event.offers().offers());
vector<string> pids;
foreach (const Offer& offer, offers) {
CHECK(offer.has_url())
<< "Offer.url required for Event support";
CHECK(offer.url().has_path())
<< "Offer.url.path required for Event support";
string id = offer.url().path();
id = strings::trim(id, "/");
Try<net::IP> ip =
net::IP::parse(offer.url().address().ip(), AF_INET);
CHECK_SOME(ip) << "Failed to parse Offer.url.address.ip";
pids.push_back(UPID(id, ip.get(), offer.url().address().port()));
}
resourceOffers(from, offers, pids);
break;
}
case Event::RESCIND: {
if (!event.has_rescind()) {
drop(event, "Expecting 'rescind' to be present");
break;
}
// TODO(bmahler): Rename 'rescindOffer' to 'rescind'
// to match the Event naming scheme.
rescindOffer(from, event.rescind().offer_id());
break;
}
case Event::UPDATE: {
if (!event.has_update()) {
drop(event, "Expecting 'update' to be present");
break;
}
const TaskStatus& status = event.update().status();
// Create a StatusUpdate based on the TaskStatus.
StatusUpdate update;
update.mutable_framework_id()->CopyFrom(framework.id());
update.mutable_status()->CopyFrom(status);
update.set_timestamp(status.timestamp());
if (status.has_executor_id()) {
update.mutable_executor_id()->CopyFrom(status.executor_id());
}
if (status.has_slave_id()) {
update.mutable_slave_id()->CopyFrom(status.slave_id());
}
if (status.has_uuid()) {
update.set_uuid(status.uuid());
}
// Note that we do not need to set the 'pid' now that
// the driver uses 'uuid' absence to skip acknowledgement.
//
// TODO(bmahler): Implement an 'update' method to match
// the Event naming scheme, and have 'statusUpdate' call
// into it.
statusUpdate(from, update, UPID());
break;
}
// TODO(greggomann): Implement handling of operation status updates.
case Event::UPDATE_OPERATION_STATUS:
break;
case Event::MESSAGE: {
if (!event.has_message()) {
drop(event, "Expecting 'message' to be present");
break;
}
// TODO(bmahler): Rename 'frameworkMessage' to 'message'
// to match the Event naming scheme.
frameworkMessage(
event.message().slave_id(),
event.message().executor_id(),
event.message().data());
break;
}
case Event::FAILURE: {
if (!event.has_failure()) {
drop(event, "Expecting 'failure' to be present");
break;
}
// TODO(bmahler): Add a 'failure' method and have the
// lost slave handler call into it.
if (event.failure().has_slave_id() &&
event.failure().has_executor_id()) {
CHECK(event.failure().has_status());
lostExecutor(
from,
event.failure().executor_id(),
event.failure().slave_id(),
event.failure().status());
} else if (event.failure().has_slave_id()) {
lostSlave(from, event.failure().slave_id());
} else {
drop(event, "Expecting 'slave_id' to be present");
}
break;
}
case Event::ERROR: {
if (!event.has_error()) {
drop(event, "Expecting 'error' to be present");
break;
}
error(event.error().message());
break;
}
case Event::INVERSE_OFFERS:
case Event::RESCIND_INVERSE_OFFER:
case Event::HEARTBEAT: {
break;
}
case Event::UNKNOWN: {
drop(event, "Unknown event");
break;
}
}
}
void registered(
const UPID& from,
const FrameworkID& frameworkId,
const MasterInfo& masterInfo)
{
if (!running.load()) {
VLOG(1) << "Ignoring framework registered message because "
<< "the driver is not running!";
return;
}
if (connected) {
VLOG(1) << "Ignoring framework registered message because "
<< "the driver is already connected!";
return;
}
if (master.isNone() || from != master->pid()) {
LOG(WARNING)
<< "Ignoring framework registered message because it was sent "
<< "from '" << from << "' instead of the leading master '"
<< (master.isSome() ? UPID(master->pid()) : UPID()) << "'";
return;
}
LOG(INFO) << "Framework registered with " << frameworkId;
framework.mutable_id()->MergeFrom(frameworkId);
connected = true;
failover = false;
if (sendUpdateFrameworkOnConnect) {
sendUpdateFramework();
}
sendUpdateFrameworkOnConnect = false;
Stopwatch stopwatch;
if (FLAGS_v >= 1) {
stopwatch.start();
}
scheduler->registered(driver, frameworkId, masterInfo);
VLOG(1) << "Scheduler::registered took " << stopwatch.elapsed();
}
void reregistered(
const UPID& from,
const FrameworkID& frameworkId,
const MasterInfo& masterInfo)
{
if (!running.load()) {
VLOG(1) << "Ignoring framework reregistered message because "
<< "the driver is not running!";
return;
}
if (connected) {
VLOG(1) << "Ignoring framework reregistered message because "
<< "the driver is already connected!";
return;
}
if (master.isNone() || from != master->pid()) {
LOG(WARNING)
<< "Ignoring framework reregistered message because it was sent "
<< "from '" << from << "' instead of the leading master '"
<< (master.isSome() ? UPID(master->pid()) : UPID()) << "'";
return;
}
LOG(INFO) << "Framework reregistered with " << frameworkId;
CHECK(framework.id() == frameworkId);
connected = true;
failover = false;
if (sendUpdateFrameworkOnConnect) {
sendUpdateFramework();
}
sendUpdateFrameworkOnConnect = false;
Stopwatch stopwatch;
if (FLAGS_v >= 1) {
stopwatch.start();
}
scheduler->reregistered(driver, masterInfo);
VLOG(1) << "Scheduler::reregistered took " << stopwatch.elapsed();
}
void doReliableRegistration(Duration maxBackoff)
{
if (!running.load()) {
return;
}
if (connected || master.isNone()) {
return;
}
if (credential.isSome() && !authenticated) {
return;
}
VLOG(1) << "Sending SUBSCRIBE call to " << master->pid();
Call call;
call.set_type(Call::SUBSCRIBE);
Call::Subscribe* subscribe = call.mutable_subscribe();
subscribe->mutable_framework_info()->CopyFrom(framework);
*subscribe->mutable_offer_constraints() = offerConstraints;
*subscribe->mutable_suppressed_roles() = RepeatedPtrField<string>(
suppressedRoles.begin(), suppressedRoles.end());
if (framework.has_id() && !framework.id().value().empty()) {
subscribe->set_force(failover);
call.mutable_framework_id()->CopyFrom(framework.id());
}
send(master->pid(), call);
// Bound the maximum backoff by 'REGISTRATION_RETRY_INTERVAL_MAX'.
maxBackoff =
std::min(maxBackoff, scheduler::REGISTRATION_RETRY_INTERVAL_MAX);
// If failover timeout is present, bound the maximum backoff
// by 1/10th of the failover timeout.
if (framework.has_failover_timeout()) {
Try<Duration> duration = Duration::create(framework.failover_timeout());
if (duration.isSome() && duration.get() > Duration::zero()) {
maxBackoff = std::min(maxBackoff, duration.get() / 10);
}
}
// Determine the delay for next attempt by picking a random
// duration between 0 and 'maxBackoff'.
// TODO(vinod): Use random numbers from <random> header.
Duration delay = maxBackoff * ((double) os::random() / RAND_MAX);
VLOG(1) << "Will retry registration in " << delay << " if necessary";
// Backoff.
frameworkRegistrationTimer = process::delay(
delay, self(), &Self::doReliableRegistration, maxBackoff * 2);
}
void resourceOffers(
const UPID& from,
const vector<Offer>& offers,
const vector<string>& pids)
{
if (!running.load()) {
VLOG(1) << "Ignoring resource offers message because "
<< "the driver is not running!";
return;
}
if (!connected) {
VLOG(1) << "Ignoring resource offers message because the driver is "
<< "disconnected!";
return;
}
CHECK_SOME(master);
if (from != master->pid()) {
VLOG(1) << "Ignoring resource offers message because it was sent "
<< "from '" << from << "' instead of the leading master '"
<< master->pid() << "'";
return;
}
// We exit early if `offers` is empty since we don't implement inverse
// offers in the old scheduler API. It could be empty when there are only
// inverse offers as part of the `ResourceOffersMessage`.
if (offers.empty()) {
return;
}
VLOG(2) << "Received " << offers.size() << " offers";
CHECK_EQ(offers.size(), pids.size());
// Save the pid associated with each slave (one per offer) so
// later we can send framework messages directly.
for (size_t i = 0; i < offers.size(); i++) {
UPID pid(pids[i]);
// Check if parse failed (e.g., due to DNS).
if (pid != UPID()) {
VLOG(3) << "Saving PID '" << pids[i] << "'";
savedOffers[offers[i].id()][offers[i].slave_id()] = pid;
} else {
VLOG(1) << "Failed to parse PID '" << pids[i] << "'";
}
}
Stopwatch stopwatch;
if (FLAGS_v >= 1) {
stopwatch.start();
}
scheduler->resourceOffers(driver, offers);
VLOG(1) << "Scheduler::resourceOffers took " << stopwatch.elapsed();
}
void rescindOffer(const UPID& from, const OfferID& offerId)
{
if (!running.load()) {
VLOG(1) << "Ignoring rescind offer message because "
<< "the driver is not running!";
return;
}
if (!connected) {
VLOG(1) << "Ignoring rescind offer message because the driver is "
<< "disconnected!";
return;
}
CHECK_SOME(master);
if (from != master->pid()) {
VLOG(1) << "Ignoring rescind offer message because it was sent "
<< "from '" << from << "' instead of the leading master '"
<< master->pid() << "'";
return;
}
VLOG(1) << "Rescinded offer " << offerId;
savedOffers.erase(offerId);
Stopwatch stopwatch;
if (FLAGS_v >= 1) {
stopwatch.start();
}
scheduler->offerRescinded(driver, offerId);
VLOG(1) << "Scheduler::offerRescinded took " << stopwatch.elapsed();
}
void statusUpdate(
const UPID& from,
const StatusUpdate& update,
const UPID& pid)
{
if (!running.load()) {
VLOG(1) << "Ignoring task status update message because "
<< "the driver is not running!";
return;
}
// Allow status updates created from the driver itself.
if (from != UPID()) {
if (!connected) {
VLOG(1) << "Ignoring status update message because the driver is "
<< "disconnected!";
return;
}
CHECK_SOME(master);
if (from != master->pid()) {
VLOG(1) << "Ignoring status update message because it was sent "
<< "from '" << from << "' instead of the leading master '"