-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathscheduler.go
More file actions
1584 lines (1432 loc) · 55.3 KB
/
scheduler.go
File metadata and controls
1584 lines (1432 loc) · 55.3 KB
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
/*
* === This file is part of ALICE O² ===
*
* Copyright 2017-2018 CERN and copyright holders of ALICE O².
* Author: Teo Mrnjavac <teo.mrnjavac@cern.ch>
*
* Portions from examples in <https://github.com/mesos/mesos-go>:
* Copyright 2013-2015, Mesosphere, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* In applying this license CERN does not waive the privileges and
* immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
package task
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"strconv"
"strings"
"sync"
"time"
"github.com/AliceO2Group/Control/apricot"
"github.com/AliceO2Group/Control/common"
"github.com/AliceO2Group/Control/common/controlmode"
"github.com/AliceO2Group/Control/common/logger/infologger"
"github.com/AliceO2Group/Control/common/utils"
"github.com/AliceO2Group/Control/common/utils/uid"
"github.com/AliceO2Group/Control/core/task/channel"
"github.com/AliceO2Group/Control/core/task/schedutil"
"github.com/AliceO2Group/Control/core/the"
"github.com/spf13/viper"
"github.com/AliceO2Group/Control/common/event"
"github.com/AliceO2Group/Control/core/controlcommands"
"github.com/AliceO2Group/Control/core/task/constraint"
pb "github.com/AliceO2Group/Control/executor/protos"
mesos "github.com/mesos/mesos-go/api/v1/lib"
"github.com/mesos/mesos-go/api/v1/lib/backoff"
xmetrics "github.com/mesos/mesos-go/api/v1/lib/extras/metrics"
"github.com/mesos/mesos-go/api/v1/lib/extras/scheduler/callrules"
"github.com/mesos/mesos-go/api/v1/lib/extras/scheduler/controller"
"github.com/mesos/mesos-go/api/v1/lib/extras/scheduler/eventrules"
"github.com/mesos/mesos-go/api/v1/lib/extras/store"
"github.com/mesos/mesos-go/api/v1/lib/resources"
"github.com/mesos/mesos-go/api/v1/lib/scheduler"
"github.com/mesos/mesos-go/api/v1/lib/scheduler/calls"
"github.com/mesos/mesos-go/api/v1/lib/scheduler/events"
"github.com/sirupsen/logrus"
"google.golang.org/protobuf/proto"
)
var (
RegistrationMinBackoff = 1 * time.Second
RegistrationMaxBackoff = 15 * time.Second
)
// StateError is returned when the system encounters an unresolvable state transition error and
// should likely exit.
type StateError string
func (err StateError) Error() string { return string(err) }
var schedEventsCh = make(chan scheduler.Event_Type)
func runSchedulerController(ctx context.Context,
state *schedulerState,
fidStore store.Singleton,
) error {
// Set up communication from controller to state machine.
go func() {
for {
receivedEvent := <-schedEventsCh
switch {
case receivedEvent == scheduler.Event_SUBSCRIBED:
if state.sm.Is("INITIAL") {
err := state.sm.Event(context.Background(), "CONNECT")
if err != nil {
log.WithField(infologger.Level, infologger.IL_Support).
WithError(err).
Error("scheduler state CONNECT event failed")
}
}
}
}
}()
// Set up communication from state machine to controller
go func() {
for {
<-state.reviveOffersTrg
doReviveOffers(ctx, state)
state.reviveOffersTrg <- struct{}{}
}
}()
// The controller starts here, it takes care of connecting to Mesos and subscribing
// as well as resubscribing if the connection is dropped.
// It also handles incoming events on the subscription connection.
//
// buildFrameworkInfo returns a *mesos.FrameworkInfo which includes the framework
// ID, as well as additional information such as Roles, WebUI URL, etc.
return controller.Run(
ctx,
schedutil.BuildFrameworkInfo(),
state.cli, /* controller.Option...: */
controller.WithEventHandler(state.buildEventHandler(fidStore)),
controller.WithFrameworkID(store.GetIgnoreErrors(fidStore)),
controller.WithRegistrationTokens(
// Limit the rate of reregistration.
// When the Done chan closes, the Run controller loop terminates. The
// Done chan is closed by the context when its cancel func is called.
backoff.Notifier(RegistrationMinBackoff, RegistrationMaxBackoff, ctx.Done()),
),
controller.WithSubscriptionTerminated(func(err error) {
// Sets a handler that runs at the end of every subscription cycle.
if err != nil {
if err != io.EOF {
log.WithPrefix("scheduler").WithField("error", err.Error()).
Error("subscription terminated")
}
if _, ok := err.(StateError); ok {
state.shutdown()
}
return
}
log.WithPrefix("scheduler").
Info("disconnected")
}),
)
}
// buildEventHandler generates and returns a handler to process events received
// from the subscription. The handler is then passed as controller.Option to
// controller.Run.
func (state *schedulerState) buildEventHandler(fidStore store.Singleton) events.Handler {
// disable brief logs when verbose logs are enabled (there's no sense logging twice!)
logger := controller.LogEvents(nil).Unless(viper.GetBool("verbose"))
return eventrules.New( /* eventrules.Rule... */
logAllEvents().If(viper.GetBool("verbose")),
eventMetrics(state.metricsAPI, time.Now, viper.GetBool("summaryMetrics")),
controller.LiftErrors().DropOnError(),
eventrules.HandleF(state.notifyStateMachine()),
).Handle(events.Handlers{
// scheduler.Event_Type: events.Handler
scheduler.Event_FAILURE: logger.HandleF(state.failure), // wrapper + print error
scheduler.Event_OFFERS: state.trackOffersReceived().HandleF(state.resourceOffers(fidStore)),
scheduler.Event_UPDATE: controller.AckStatusUpdates(state.cli).AndThen().HandleF(state.statusUpdate()),
scheduler.Event_SUBSCRIBED: eventrules.New(
logger,
controller.TrackSubscription(fidStore, viper.GetDuration("mesosFailoverTimeout")),
eventrules.New().HandleF(state.reconciliationCall()),
),
scheduler.Event_MESSAGE: eventrules.HandleF(state.incomingMessageHandler()),
}.Otherwise(logger.HandleEvent))
}
// Channel the event type of the newly received event to an asynchronous dispatcher
// in runSchedulerController
func (state *schedulerState) notifyStateMachine() events.HandlerFunc {
return func(ctx context.Context, e *scheduler.Event) error {
schedEventsCh <- e.GetType()
return nil
}
}
// Implicit Reconciliation Call that sends an empty list of tasks and the master responds
// with the latest state for all currently known non-terminal tasks.
func (state *schedulerState) reconciliationCall() events.HandlerFunc {
return func(ctx context.Context, e *scheduler.Event) error {
reconcileCall := calls.Reconcile(calls.ReconcileTasks(nil))
_ = calls.CallNoData(ctx, state.cli, reconcileCall)
return nil
}
}
// Update metrics when we receive an offer
func (state *schedulerState) trackOffersReceived() eventrules.Rule {
return func(ctx context.Context, e *scheduler.Event, err error, chain eventrules.Chain) (context.Context, *scheduler.Event, error) {
if err == nil {
state.metricsAPI.offersReceived.Int(len(e.GetOffers().GetOffers()))
}
return chain(ctx, e, err)
}
}
// Handle an incoming Event_FAILURE, which may be a failure in the executor or
// in the Mesos agent.
func (state *schedulerState) failure(_ context.Context, e *scheduler.Event) error {
var (
f = e.GetFailure()
eid, aid, stat = f.ExecutorID, f.AgentID, f.Status
)
if eid != nil {
// executor failed..
fields := logrus.Fields{
"executor": eid.Value,
}
if aid != nil {
fields["agent"] = aid.Value
host := state.getAgentCacheHostname(*aid)
fields["srcHost"] = host
detector, err := apricot.Instance().GetDetectorForHost(host)
if err == nil {
fields["detector"] = detector
}
}
if stat != nil {
fields["error"] = strconv.Itoa(int(*stat))
}
log.WithPrefix("scheduler").
WithFields(fields).
WithField("level", infologger.IL_Support).
Error("executor failed")
state.taskman.internalEventCh <- event.NewExecutorFailedEvent(eid)
} else if aid != nil {
// agent failed..
fields := logrus.Fields{}
fields["agent"] = aid.Value
host := state.getAgentCacheHostname(*aid)
fields["srcHost"] = host
detector, err := apricot.Instance().GetDetectorForHost(host)
if err == nil {
fields["detector"] = detector
}
if stat != nil {
fields["error"] = strconv.Itoa(int(*stat))
}
log.WithPrefix("scheduler").
WithFields(fields).
WithField("level", infologger.IL_Support).
Error("agent failed")
log.WithField("level", infologger.IL_Ops).
WithField("detector", detector).
Errorf("possible connectivity issues with host '%s'", host)
state.taskman.internalEventCh <- event.NewAgentFailedEvent(aid)
}
return nil
}
func (state *schedulerState) getAgentCacheHostname(id mesos.AgentID) string {
if state == nil ||
state.taskman == nil {
return ""
}
if entry := state.taskman.AgentCache.Get(id); entry != nil {
return entry.Hostname
}
return ""
}
// Handler for Event_MESSAGE
func (state *schedulerState) incomingMessageHandler() events.HandlerFunc {
// instantiate map of MCtargets, command IDs and timeouts here
// what should happen
// sendCommand sends a command, pushes the targets list, command id and timeout (maybe
// through a channel) to a structure accessible here.
// then when we receive a response, if its id, target and timeout is satisfied by one and
// only one entry in the list, we signal back to commandqueue
// otherwise, we log and ignore.
return func(ctx context.Context, e *scheduler.Event) (err error) {
mesosMessage := e.GetMessage()
if mesosMessage == nil {
err = errors.New("message handler got bad MESSAGE")
log.WithPrefix("scheduler").
WithError(err).
Warning("message handler cannot continue")
return
}
agentId := mesosMessage.GetAgentID()
executorId := mesosMessage.GetExecutorID()
if len(agentId.GetValue()) == 0 || len(executorId.GetValue()) == 0 {
err = errors.New("message handler got MESSAGE with no valid sender")
log.WithPrefix("scheduler").
WithFields(logrus.Fields{
"agentId": agentId.GetValue(),
"executorId": executorId.GetValue(),
"error": err.Error(),
}).
Warning("message handler cannot continue")
return
}
data := mesosMessage.GetData()
var incomingType struct {
MessageType string `json:"_messageType"`
}
err = json.Unmarshal(data, &incomingType)
if err != nil {
return
}
switch incomingType.MessageType {
case "DeviceEvent":
var incomingEvent struct {
Type pb.DeviceEventType `json:"type"`
Origin event.DeviceEventOrigin `json:"origin"`
Labels map[string]string `json:"labels"`
}
err = json.Unmarshal(data, &incomingEvent)
if err != nil {
return
}
envId := uid.NilID()
if len(incomingEvent.Labels) > 0 {
envIdS, ok := incomingEvent.Labels["environmentId"]
if ok {
envId, err = uid.FromString(envIdS)
if err != nil {
envId = uid.NilID()
}
}
}
ev := event.NewDeviceEvent(incomingEvent.Origin, incomingEvent.Type)
if ev != nil {
ev.SetLabels(incomingEvent.Labels)
err = json.Unmarshal(data, &ev)
if err != nil {
return
}
state.taskman.internalEventCh <- ev
// state.handleDeviceEvent(ev)
} else {
log.WithFields(logrus.Fields{
"type": incomingEvent.Type.String(),
"originTask": incomingEvent.Origin.TaskId.Value,
"partition": envId.String(),
}).
Error("cannot handle incoming device event")
}
case "MesosCommandResponse":
var incomingCommand struct {
CommandName string `json:"name"`
}
err = json.Unmarshal(data, &incomingCommand)
if err != nil {
return
}
log.WithPrefix("scheduler").
WithField("commandName", incomingCommand.CommandName).
Trace("processing incoming MESSAGE")
switch incomingCommand.CommandName {
case "MesosCommand_TriggerHook":
var res controlcommands.MesosCommandResponse_TriggerHook
err = json.Unmarshal(data, &res)
if err != nil {
log.WithPrefix("scheduler").WithFields(logrus.Fields{
"commandName": incomingCommand.CommandName,
"agentId": agentId.GetValue(),
"executorId": executorId.GetValue(),
"message": string(data[:]),
"error": err.Error(),
}).
Error("cannot unmarshal incoming MESSAGE")
return
}
sender := controlcommands.MesosCommandTarget{
AgentId: agentId,
ExecutorId: executorId,
TaskId: mesos.TaskID{Value: res.TaskId},
}
go func() {
state.servent.ProcessResponse(&res, sender)
}()
return
case "MesosCommand_Transition":
var res controlcommands.MesosCommandResponse_Transition
err = json.Unmarshal(data, &res)
if err != nil {
log.WithPrefix("scheduler").WithFields(logrus.Fields{
"commandName": incomingCommand.CommandName,
"agentId": agentId.GetValue(),
"executorId": executorId.GetValue(),
"message": string(data[:]),
"error": err.Error(),
}).
Error("cannot unmarshal incoming MESSAGE")
return
}
sender := controlcommands.MesosCommandTarget{
AgentId: agentId,
ExecutorId: executorId,
TaskId: mesos.TaskID{Value: res.TaskId},
}
go func() {
taskmanMessage := NewTaskStateMessage(res.TaskId, res.CurrentState)
state.taskman.MessageChannel <- taskmanMessage
// servent should be inside taskman and eventually
// all this handling.
state.servent.ProcessResponse(&res, sender)
}()
return
default:
return errors.New(fmt.Sprintf("unrecognized response for controlcommand %s", incomingCommand.CommandName))
}
case "AnnounceTaskPIDEvent":
var taskMessage event.AnnounceTaskPIDEvent
err = json.Unmarshal(data, &taskMessage)
if err != nil {
return
}
t := state.taskman.GetTask(taskMessage.GetTaskId())
if t != nil {
t.setTaskPID(taskMessage.GetTaskPID())
}
}
return
}
}
// Handler for Event_OFFERS
func (state *schedulerState) resourceOffers(fidStore store.Singleton) events.HandlerFunc {
return func(ctx context.Context, e *scheduler.Event) error {
timeResourceOffersCall := time.Now()
var (
offers = e.GetOffers().GetOffers()
callOption = calls.RefuseSeconds(time.Second) // calls.RefuseSecondsWithJitter(state.random, state.config.maxRefuseSeconds)
tasksLaunchedThisCycle = 0
offersDeclined = 0
)
if viper.GetBool("veryVerbose") {
var (
prettyOffers []string
offerIds []string
hostnames []string
)
for i := range offers {
prettyOffer, _ := json.MarshalIndent(offers[i], "", "\t")
prettyOffers = append(prettyOffers, string(prettyOffer))
offerIds = append(offerIds, offers[i].ID.Value)
hostnames = append(hostnames, offers[i].Hostname)
}
log.WithPrefix("scheduler").WithFields(logrus.Fields{
"offerIds": strings.Join(offerIds, ", "),
"hostnames": strings.Join(hostnames, ", "),
"offersCount": len(offerIds),
}).
Trace("received offers")
}
var descriptorsStillToDeploy Descriptors
envId := uid.NilID()
var deploymentRequestPayload *ResourceOffersDeploymentRequest
// receive deployment request from channel, if any
select {
case deploymentRequestPayload = <-state.tasksToDeploy:
if deploymentRequestPayload == nil {
break
}
descriptorsStillToDeploy = deploymentRequestPayload.tasksToDeploy
envId = deploymentRequestPayload.envId
if viper.GetBool("veryVerbose") {
rolePaths := make([]string, len(descriptorsStillToDeploy))
taskClasses := make([]string, len(descriptorsStillToDeploy))
for i, d := range descriptorsStillToDeploy {
rolePaths[i] = d.TaskRole.GetPath()
taskClasses[i] = d.TaskClassName
}
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithFields(logrus.Fields{
"roles": strings.Join(rolePaths, ", "),
"classes": strings.Join(taskClasses, ", "),
"descriptors": len(descriptorsStillToDeploy),
}).
Debugf("received %d descriptors for tasks to deploy on this offers round", len(deploymentRequestPayload.tasksToDeploy))
utils.TimeTrack(timeResourceOffersCall, "resourceOffers: start to descriptors channel receive", log.WithField("descriptors", len(descriptorsStillToDeploy)))
}
default:
if viper.GetBool("veryVerbose") {
log.WithPrefix("scheduler").
Trace("no roles need deployment")
}
}
timeGotDescriptors := time.Now()
machinesUsed := make(map[string]struct{})
// by default we get ready to decline all offers
offerIDsToDecline := make(map[mesos.OfferID]struct{}, len(offers))
for i := range offers {
offerIDsToDecline[offers[i].ID] = struct{}{}
}
tasksDeployed := make(DeploymentMap)
tasksDeployedMutex := sync.Mutex{}
// list of descriptors that we find impossible to deploy due to wants/constraints
descriptorsUndeployable := make(Descriptors, 0)
if len(descriptorsStillToDeploy) > 0 {
// 3 ways to make decisions
// * FLP1, FLP2, ... , EPN1, EPN2, ... o2-roles as mesos attributes of an agent
// * readout cards as resources
// * o2 machine types (FLP, EPN) as mesos-roles so that other frameworks never get
// offers for stuff that doesn't belong to them i.e. readout cards
// Walk through the roles list and find out if the current []offers satisfies
// what we need.
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
Debug("about to deploy workflow tasks")
var err error
// We make a map[Descriptor]constraint.Constraints and for each descriptor to deploy we
// fill it with the pre-computed total constraints for that Descriptor.
descriptorConstraints := state.taskman.BuildDescriptorConstraints(descriptorsStillToDeploy)
utils.TimeTrack(timeGotDescriptors, "resourceOffers: descriptors channel receive to constraints built", log.
WithField("descriptors", len(descriptorsStillToDeploy)).
WithField("partition", envId.String()))
timePreProcessing := time.Now()
// Pre-processing: for each descriptorConstraint, if it includes a machine_id, means the descriptor can only
// match a single offer. If such a descriptorConstraint is unsatisfiable, we should bail out early without
// even trying to match it to an offer.
// Here's where we accumulate descriptors that we know can only be matched to a single offer, provided the
// offer can satisfy constraints, which we don't know yet.
offerDescriptorsPrematchToDeploy := make(map[mesos.OfferID]Descriptors)
// Each offer *must* have a machine_id, otherwise the O² system instance is broken at install time
offersByMachineId := make(map[string]mesos.Offer)
for _, offer := range offers {
machineIdAttr := ""
for _, attr := range offer.Attributes {
if attr.GetName() == "machine_id" {
machineIdAttr = attr.GetText().GetValue()
break
}
}
if machineIdAttr != "" {
offersByMachineId[machineIdAttr] = offer
}
}
for i := len(descriptorsStillToDeploy) - 1; i >= 0; i-- {
descriptor := descriptorsStillToDeploy[i]
requiredMachineId := ""
for _, descriptorConstraint := range descriptorConstraints[descriptor] {
if descriptorConstraint.Attribute == "machine_id" {
requiredMachineId = descriptorConstraint.Value
break
}
}
if requiredMachineId != "" {
// We have a constraint on the machine_id, so we need to find an offer that matches it.
// If we don't find any, we can bail out early.
offer, found := offersByMachineId[requiredMachineId]
if found {
// We found an offer that matches the machine_id constraint, so we can add the descriptor to the
// pre-match list. It doesn't mean the offer can be accepted straight away, but it means that if
// the descriptor has any hope of being deployed, it will only be on this offer, provided other
// constraints and resources are satisfied.
if offerDescriptorsPrematchToDeploy[offer.ID] == nil {
offerDescriptorsPrematchToDeploy[offer.ID] = make(Descriptors, 0)
}
offerDescriptorsPrematchToDeploy[offer.ID] = append(offerDescriptorsPrematchToDeploy[offer.ID], descriptor)
descriptorsStillToDeploy = append(descriptorsStillToDeploy[:i], descriptorsStillToDeploy[i+1:]...)
log.WithField("partition", envId.String()).
WithField("level", infologger.IL_Devel).
WithField("descriptor", descriptor.TaskClassName).
WithField("hostname", offer.Hostname).Trace("descriptor matched")
} else {
// We have a constraint on the machine_id, but we didn't find any offer that matches it.
// We can bail out early.
descriptorsUndeployable = append(descriptorsUndeployable, descriptor)
descriptorsStillToDeploy = append(descriptorsStillToDeploy[:i], descriptorsStillToDeploy[i+1:]...)
log.WithField("partition", envId.String()).
WithField("level", infologger.IL_Devel).
WithField("descriptor", descriptor.TaskClassName).
Errorf("no resource offer for required host %s, deployment will be aborted", requiredMachineId)
}
}
}
utils.TimeTrack(timePreProcessing, "resourceOffers: constraints built to offers pre-processing done", log.
WithField("descriptors", len(descriptorsStillToDeploy)).
WithField("partition", envId.String()))
timeForOffers := time.Now()
// We protect the descriptors structures with a mutex, within the scope of the current offers round, because
// concurrent stuff starts to happen here.
descriptorsMu := sync.Mutex{}
// Parallelized offer processing, exhaustive search for each offer
var offerWaitGroup sync.WaitGroup
offerWaitGroup.Add(len(offers))
for offerIndex := range offers {
go func(offerIndex int) {
defer offerWaitGroup.Done()
offer := offers[offerIndex]
timeSingleOffer := time.Now()
var (
remainingResourcesInOffer = mesos.Resources(offer.Resources)
taskInfosToLaunchForCurrentOffer = make([]mesos.TaskInfo, 0)
tasksDeployedForCurrentOffer = make(DeploymentMap)
targetExecutorId = mesos.ExecutorID{}
)
// If there are no executors provided by the offer,
// we start a new one by generating a new ID
if len(offer.ExecutorIDs) == 0 {
targetExecutorId.Value = uid.New().String()
log.WithField("executorId", targetExecutorId.Value).
WithField("offerHost", offer.GetHostname()).
WithField("level", infologger.IL_Support).
Info("received offer without executor ID, will start new executor if accepted")
} else {
targetExecutorId.Value = offer.ExecutorIDs[0].Value
if len(offer.ExecutorIDs) == 1 {
log.WithField("executorId", targetExecutorId.Value).
WithField("offerHost", offer.GetHostname()).
WithField("level", infologger.IL_Support).
Info("received offer with one executor ID, will use existing executor")
} else if len(offer.ExecutorIDs) > 1 {
log.WithField("executorId", targetExecutorId.Value).
WithField("executorIds", offer.ExecutorIDs).
WithField("offerHost", offer.GetHostname()).
WithField("level", infologger.IL_Support).
Warn("received offer with more than one executor ID, will use first one")
}
}
host := offer.GetHostname()
var detector string
detector, err = apricot.Instance().GetDetectorForHost(host)
if err != nil {
detector = ""
}
log.WithPrefix("scheduler").
WithFields(logrus.Fields{
"offerId": offer.ID.Value,
"offerHost": host,
"resources": remainingResourcesInOffer.String(),
"partition": envId.String(),
"detector": detector,
}).
Debug("processing offer")
remainingResourcesFlattened := resources.Flatten(remainingResourcesInOffer)
// avoid the expense of computing these if we can...
if viper.GetBool("summaryMetrics") && viper.GetBool("mesosResourceTypeMetrics") {
for name, resType := range resources.TypesOf(remainingResourcesFlattened...) {
if resType == mesos.SCALAR {
sum, _ := name.Sum(remainingResourcesFlattened...)
state.metricsAPI.offeredResources(sum.GetScalar().GetValue(), name.String())
}
}
}
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithField("detector", detector).
Trace("state lock to process descriptors to deploy")
timeDescriptorsSection := time.Now()
descriptorsMu.Lock()
descriptorsPrematchToDeploy, prematchedDescriptorsExistForThisOffer := offerDescriptorsPrematchToDeploy[offer.ID]
if prematchedDescriptorsExistForThisOffer {
FOR_PREMATCH_DESCRIPTORS:
for i := len(descriptorsPrematchToDeploy) - 1; i >= 0; i-- {
descriptor := descriptorsPrematchToDeploy[i]
descriptorDetector, ok := descriptor.TaskRole.GetVars().Get("detector")
if !ok {
descriptorDetector = ""
}
offerAttributes := constraint.Attributes(offer.Attributes)
if !offerAttributes.Satisfy(descriptorConstraints[descriptor]) {
if viper.GetBool("veryVerbose") {
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithField("detector", descriptorDetector).
WithFields(logrus.Fields{
"taskClass": descriptor.TaskClassName,
"constraints": descriptorConstraints[descriptor],
"offerId": offer.ID.Value,
"resources": remainingResourcesInOffer.String(),
"attributes": offerAttributes.String(),
}).
Trace("descriptor constraints not satisfied by pre-matched offer attributes, descriptor undeployable")
}
// we know this descriptor will never be satisfiable, no point in continuing
descriptorsPrematchToDeploy = append(descriptorsPrematchToDeploy[:i], descriptorsPrematchToDeploy[i+1:]...)
descriptorsUndeployable = append(descriptorsUndeployable, descriptor)
break FOR_PREMATCH_DESCRIPTORS
}
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithField("detector", descriptorDetector).
Debug("pre-matched offer attributes satisfy constraints")
var wants *Wants
wants, err = state.taskman.GetWantsForDescriptor(descriptor, envId)
if err != nil {
log.WithPrefix("scheduler").
WithError(err).
WithField("partition", envId.String()).
WithField("detector", descriptorDetector).
WithFields(logrus.Fields{
"class": descriptor.TaskClassName,
"constraints": descriptor.RoleConstraints.String(),
"level": infologger.IL_Devel,
"offerHost": offer.Hostname,
}).
Error("invalid task class: no task class or no resource demands for pre-matched descriptor, WILL NOT BE DEPLOYED")
// we know this descriptor will never be satisfiable, no point in continuing
descriptorsPrematchToDeploy = append(descriptorsPrematchToDeploy[:i], descriptorsPrematchToDeploy[i+1:]...)
descriptorsUndeployable = append(descriptorsUndeployable, descriptor)
break FOR_PREMATCH_DESCRIPTORS
}
if !Resources(remainingResourcesInOffer).Satisfy(wants) {
if viper.GetBool("veryVerbose") {
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithField("detector", descriptorDetector).
WithFields(logrus.Fields{
"taskClass": descriptor.TaskClassName,
"wants": *wants,
"offerId": offer.ID.Value,
"resources": remainingResourcesInOffer.String(),
"level": infologger.IL_Devel,
"offerHost": offer.Hostname,
}).
Warn("descriptor wants not satisfied by pre-matched offer resources")
}
// we know this descriptor will never be satisfiable, no point in continuing
descriptorsPrematchToDeploy = append(descriptorsPrematchToDeploy[:i], descriptorsPrematchToDeploy[i+1:]...)
descriptorsUndeployable = append(descriptorsUndeployable, descriptor)
break FOR_PREMATCH_DESCRIPTORS
}
var limits *Limits
limits = state.taskman.GetLimitsForDescriptor(descriptor, envId)
// Point of no return, we start subtracting resources
taskPtr, mesosTaskInfo := makeTaskForMesosResources(
state,
&offer,
descriptor,
wants,
limits,
remainingResourcesInOffer,
machinesUsed,
targetExecutorId,
envId,
descriptorDetector,
offerIDsToDecline,
)
if taskPtr == nil || mesosTaskInfo == nil {
break FOR_PREMATCH_DESCRIPTORS
}
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithField("detector", descriptorDetector).
WithFields(logrus.Fields{
"name": mesosTaskInfo.Name,
"taskId": mesosTaskInfo.TaskID.Value,
"offerId": offer.ID.Value,
"executorId": state.executor.ExecutorID.Value,
"limits": mesosTaskInfo.Limits,
}).Debug("launching task")
taskPtr.SendEvent(&event.TaskEvent{
Name: taskPtr.GetName(),
TaskID: mesosTaskInfo.TaskID.Value,
State: "LAUNCHED",
Hostname: taskPtr.hostname,
ClassName: taskPtr.GetClassName(),
})
taskInfosToLaunchForCurrentOffer = append(taskInfosToLaunchForCurrentOffer, *mesosTaskInfo)
descriptorsPrematchToDeploy = append(descriptorsPrematchToDeploy[:i], descriptorsPrematchToDeploy[i+1:]...)
tasksDeployedForCurrentOffer[taskPtr] = descriptor
}
} // end FOR_PREMATCH_DESCRIPTORS
// We iterate down over the descriptors, and we remove them as we match
FOR_DESCRIPTORS:
for i := len(descriptorsStillToDeploy) - 1; i >= 0; i-- {
descriptor := descriptorsStillToDeploy[i]
descriptorDetector, ok := descriptor.TaskRole.GetVars().Get("detector")
if !ok {
descriptorDetector = ""
}
offerAttributes := constraint.Attributes(offer.Attributes)
if !offerAttributes.Satisfy(descriptorConstraints[descriptor]) {
if viper.GetBool("veryVerbose") {
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithField("detector", descriptorDetector).
WithFields(logrus.Fields{
"taskClass": descriptor.TaskClassName,
"constraints": descriptorConstraints[descriptor],
"offerId": offer.ID.Value,
"resources": remainingResourcesInOffer.String(),
"attributes": offerAttributes.String(),
}).
Trace("descriptor constraints not satisfied by offer attributes")
}
continue FOR_DESCRIPTORS // next descriptor
}
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithField("detector", descriptorDetector).
Debug("offer attributes satisfy constraints")
var wants *Wants
wants, err = state.taskman.GetWantsForDescriptor(descriptor, envId)
if err != nil {
log.WithPrefix("scheduler").
WithError(err).
WithField("partition", envId.String()).
WithField("detector", descriptorDetector).
WithFields(logrus.Fields{
"class": descriptor.TaskClassName,
"constraints": descriptor.RoleConstraints.String(),
"level": infologger.IL_Devel,
"offerHost": offer.Hostname,
}).
Error("invalid task class: no task class or no resource demands for descriptor, WILL NOT BE DEPLOYED")
continue FOR_DESCRIPTORS // next descriptor
}
if !Resources(remainingResourcesInOffer).Satisfy(wants) {
if viper.GetBool("veryVerbose") {
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithField("detector", descriptorDetector).
WithFields(logrus.Fields{
"taskClass": descriptor.TaskClassName,
"wants": *wants,
"offerId": offer.ID.Value,
"resources": remainingResourcesInOffer.String(),
"level": infologger.IL_Devel,
"offerHost": offer.Hostname,
}).
Warn("descriptor wants not satisfied by offer resources")
}
continue FOR_DESCRIPTORS // next descriptor
}
var limits *Limits
limits = state.taskman.GetLimitsForDescriptor(descriptor, envId)
// Point of no return, we start subtracting resources
taskPtr, mesosTaskInfo := makeTaskForMesosResources(
state,
&offer,
descriptor,
wants,
limits,
remainingResourcesInOffer,
machinesUsed,
targetExecutorId,
envId,
descriptorDetector,
offerIDsToDecline,
)
if taskPtr == nil || mesosTaskInfo == nil {
continue FOR_DESCRIPTORS // next descriptor
}
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithField("detector", descriptorDetector).
WithFields(logrus.Fields{
"name": mesosTaskInfo.Name,
"taskId": mesosTaskInfo.TaskID.Value,
"offerId": offer.ID.Value,
"executorId": state.executor.ExecutorID.Value,
"limits": mesosTaskInfo.Limits,
}).Debug("launching task")
taskPtr.SendEvent(&event.TaskEvent{
Name: taskPtr.GetName(),
TaskID: mesosTaskInfo.TaskID.Value,
State: "LAUNCHED",
Hostname: taskPtr.hostname,
ClassName: taskPtr.GetClassName(),
})
taskInfosToLaunchForCurrentOffer = append(taskInfosToLaunchForCurrentOffer, *mesosTaskInfo)
descriptorsStillToDeploy = append(descriptorsStillToDeploy[:i], descriptorsStillToDeploy[i+1:]...)
tasksDeployedForCurrentOffer[taskPtr] = descriptor
} // end FOR_DESCRIPTORS
descriptorsMu.Unlock()
utils.TimeTrack(timeDescriptorsSection, "resourceOffers: single offer descriptors section", log.
WithField("partition", envId.String()).
WithField("offerHost", host).
WithField("tasksDeployed", len(tasksDeployedForCurrentOffer)).
WithField("descriptorsStillToDeploy", len(descriptorsStillToDeploy)).
WithField("offers", len(offers)))
timeOfferAcceptance := time.Now()
log.WithPrefix("scheduler").
WithField("offerHost", host).
WithField("detector", detector).
WithField("partition", envId.String()).
Trace("state unlock")
// build ACCEPT call to launch all of the tasks we've assembled
accept := calls.Accept(
calls.OfferOperations{calls.OpLaunch(taskInfosToLaunchForCurrentOffer...)}.WithOffers(offer.ID),
).With(callOption) // handles refuseSeconds etc.
// send ACCEPT call to mesos
err = calls.CallNoData(ctx, state.cli, accept)
if err != nil {
log.WithPrefix("scheduler").
WithError(err).
WithField("detector", detector).
WithField("partition", envId.String()).
WithField("offerHost", host).
Error("failed to launch tasks")
// FIXME: we probably need to react to a failed ACCEPT here
} else {
if n := len(taskInfosToLaunchForCurrentOffer); n > 0 {
tasksLaunchedThisCycle += n
log.WithPrefix("scheduler").
WithField("tasks", n).
WithField("partition", envId.String()).
WithField("detector", detector).
WithField("level", infologger.IL_Support).
WithField("offerHost", offer.Hostname).
WithField("executorId", targetExecutorId.Value).
Infof("launch request sent to %s: %d tasks", offer.Hostname, n)
for _, taskInfo := range taskInfosToLaunchForCurrentOffer {
log.WithPrefix("scheduler").
WithFields(logrus.Fields{
"executorId": taskInfo.GetExecutor().ExecutorID.Value,
"executorName": taskInfo.GetExecutor().GetName(),
"agentId": taskInfo.GetAgentID().Value,
"taskId": taskInfo.GetTaskID().Value,
"level": infologger.IL_Devel,
}).
WithField("offerHost", offer.Hostname).
WithField("partition", envId.String()).
WithField("detector", detector).
Debug("task launch requested")
}