-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathmanager.go
More file actions
1376 lines (1202 loc) · 44.3 KB
/
manager.go
File metadata and controls
1376 lines (1202 loc) · 44.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 2018-2019 CERN and copyright holders of ALICE O².
* Author: Teo Mrnjavac <teo.mrnjavac@cern.ch>
*
* 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"
"errors"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/AliceO2Group/Control/common/utils/safeacks"
"github.com/AliceO2Group/Control/apricot"
"github.com/AliceO2Group/Control/common/event"
"github.com/AliceO2Group/Control/common/gera"
"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/repos"
"github.com/AliceO2Group/Control/core/task/sm"
"github.com/AliceO2Group/Control/core/task/taskclass"
"github.com/AliceO2Group/Control/core/task/taskop"
"github.com/AliceO2Group/Control/core/the"
"github.com/AliceO2Group/Control/executor/executorutil"
"github.com/mesos/mesos-go/api/v1/lib/extras/store"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
"github.com/AliceO2Group/Control/core/controlcommands"
"github.com/AliceO2Group/Control/core/task/channel"
"github.com/k0kubun/pp"
mesos "github.com/mesos/mesos-go/api/v1/lib"
"github.com/mesos/mesos-go/api/v1/lib/scheduler/calls"
"github.com/sirupsen/logrus"
)
type KillTaskFunc func(*Task) error
const (
TARGET_SEPARATOR_RUNE = ':'
TARGET_SEPARATOR = ":"
)
const TaskMan_QUEUE = 32768
type ResourceOffersOutcome struct {
deployed DeploymentMap
undeployed Descriptors
undeployable Descriptors
}
type ResourceOffersDeploymentRequest struct {
tasksToDeploy Descriptors
envId uid.ID
outcomeCh chan ResourceOffersOutcome
}
type Manager struct {
deployMu sync.Mutex
ctx context.Context
fidStore store.Singleton
AgentCache AgentCache
MessageChannel chan *TaskmanMessage
classes *taskclass.Classes
roster *roster
tasksToDeploy chan<- *ResourceOffersDeploymentRequest
reviveOffersTrg chan struct{}
cq *controlcommands.CommandQueue
tasksLaunched int
tasksFinished int
schedulerState *schedulerState
internalEventCh chan<- event.Event
ackKilledTasks *safeacks.SafeAcks
killTasksMu sync.Mutex // to avoid races when attempting to kill the same tasks in different goroutines
}
func NewManager(shutdown func(), internalEventCh chan<- event.Event) (taskman *Manager, err error) {
// TODO(jdef) how to track/handle timeout errors that occur for SUBSCRIBE calls? we should
// probably tolerate X number of subsequent subscribe failures before bailing. we'll need
// to track the lastCallAttempted along with subsequentSubscribeTimeouts.
// store.Singleton is a thread-safe abstraction to load and store and string,
// provided by mesos-go.
// We also make sure that a log message is printed with the FrameworkID.
fidStore := store.DecorateSingleton(
store.NewInMemorySingleton(),
store.DoSet().AndThen(func(_ store.Setter, v string, _ error) error {
// Store Mesos Framework ID to configuration.
err = the.ConfSvc().SetRuntimeEntry("aliecs", "mesos_fid", v)
if err != nil {
log.WithField("error", err).Error("cannot write to configuration")
}
log.WithField("frameworkId", v).Debug("frameworkId")
return nil
}))
// Set Framework ID from the configuration
if fidValue, err := the.ConfSvc().GetRuntimeEntry("aliecs", "mesos_fid"); err == nil {
store.SetOrPanic(fidStore)(fidValue)
}
taskman = &Manager{
classes: taskclass.NewClasses(),
roster: newRoster(),
internalEventCh: internalEventCh,
}
schedState, err := NewScheduler(taskman, fidStore, shutdown)
if err != nil {
return nil, err
}
taskman.schedulerState = schedState
taskman.cq = taskman.schedulerState.commandqueue
taskman.tasksToDeploy = taskman.schedulerState.tasksToDeploy
taskman.reviveOffersTrg = taskman.schedulerState.reviveOffersTrg
taskman.ackKilledTasks = safeacks.NewAcks()
schedState.setupCli()
return
}
// NewTaskForMesosOffer accepts a Mesos offer and a Descriptor and returns a newly
// constructed Task.
// This function should only be called by the Mesos scheduler controller when
// matching role requests with offers (matchRoles).
func (m *Manager) newTaskForMesosOffer(
offer *mesos.Offer,
descriptor *Descriptor,
localBindMap channel.BindMap,
executorId mesos.ExecutorID,
) (t *Task) {
newId := uid.New().String()
t = &Task{
name: fmt.Sprintf("%s#%s", descriptor.TaskClassName, newId),
parent: descriptor.TaskRole,
className: descriptor.TaskClassName,
hostname: offer.Hostname,
agentId: offer.AgentID.Value,
offerId: offer.ID.Value,
taskId: newId,
properties: gera.MakeMap[string, string]().Wrap(m.GetTaskClass(descriptor.TaskClassName).Properties),
executorId: executorId.Value,
GetTaskClass: nil,
localBindMap: nil,
state: sm.STANDBY,
status: INACTIVE,
}
t.GetTaskClass = func() *taskclass.Class {
return m.GetTaskClass(t.className)
}
t.localBindMap = make(channel.BindMap)
for k, v := range localBindMap {
t.localBindMap[k] = v
}
return
}
func getTaskClassList(taskClassesRequired []string) (taskClassList []*taskclass.Class, err error) {
repoManager := the.RepoManager()
var yamlData []byte
taskClassList = make([]*taskclass.Class, 0)
for _, taskClass := range taskClassesRequired {
taskClassString := strings.Split(taskClass, "@")
taskClassFile := taskClassString[0] + ".yaml"
var tempRepo repos.Repo
_, tempRepo, err = repos.NewRepo(strings.Split(taskClassFile, "tasks")[0], repoManager.GetDefaultRevision(), repoManager.GetReposPath())
if err != nil {
return
}
repo := repoManager.GetAllRepos()[tempRepo.GetIdentifier()] // get IRepo pointer from RepoManager
if repo == nil { // should never end up here
return nil, errors.New("getTaskClassList: repo not found for " + taskClass)
}
taskTemplatePath := repo.GetTaskTemplatePath(taskClassFile)
yamlData, err = os.ReadFile(taskTemplatePath)
if err != nil {
return nil, err
}
taskClassStruct := taskclass.Class{}
err = yaml.Unmarshal(yamlData, &taskClassStruct)
if err != nil {
return nil, fmt.Errorf("task template load error (template=%s): %w", taskTemplatePath, err)
}
var taskFilename, taskPath string
taskRev := strings.Split(taskClass, "@")
if len(taskRev) == 2 {
taskPath = taskRev[0]
} else {
taskPath = taskClass
}
taskInfo := strings.Split(taskPath, "/tasks/")
if len(taskInfo) == 1 {
taskFilename = taskInfo[0]
} else {
taskFilename = taskInfo[1]
}
if taskClassStruct.Identifier.Name != taskFilename {
err = fmt.Errorf("the name of the task template file (%s) and the name of the task (%s) don't match", taskFilename, taskClassStruct.Identifier.Name)
return
}
taskClassStruct.Identifier.RepoIdentifier = repo.GetIdentifier()
taskClassStruct.Identifier.Hash = repo.GetHash()
taskClassList = append(taskClassList, &taskClassStruct)
}
return taskClassList, nil
}
func (m *Manager) GetState() string {
return m.schedulerState.sm.Current()
}
func (m *Manager) GetFrameworkID() string {
return m.schedulerState.GetFrameworkID()
}
func (m *Manager) removeInactiveClasses() {
_ = m.classes.Do(func(classMap *map[string]*taskclass.Class) error {
keys := make([]string, 0)
taskClassCacheTTL := viper.GetDuration("taskClassCacheTTL")
// push keys of classes that don't appear in roster any more into a slice
for taskClassIdentifier, class := range *classMap {
if class == nil {
// don't really know what to do with a valid TCI but nil class
continue
}
if time.Since(class.UpdatedTimestamp) < taskClassCacheTTL {
// class is still fresh, skip
continue
}
if len(m.roster.filteredForClass(taskClassIdentifier)) == 0 {
keys = append(keys, taskClassIdentifier)
}
}
// and delete them
for _, k := range keys {
delete(*classMap, k)
}
return nil
})
return
}
func (m *Manager) RemoveReposClasses(repoPath string) { // Currently unused
utils.EnsureTrailingSlash(&repoPath)
_ = m.classes.Do(func(classMap *map[string]*taskclass.Class) error {
for taskClassIdentifier := range *classMap {
if strings.HasPrefix(taskClassIdentifier, repoPath) &&
len(m.roster.filteredForClass(taskClassIdentifier)) == 0 {
delete(*classMap, taskClassIdentifier)
}
}
return nil
})
return
}
func (m *Manager) RefreshClasses(taskClassesRequired []string) (err error) {
log.WithField("taskClassesRequired", len(taskClassesRequired)).
Debug("waiting to refresh task classes")
defer utils.TimeTrackFunction(time.Now(), log.WithField("taskClassesRequired", len(taskClassesRequired)))
m.deployMu.Lock()
defer m.deployMu.Unlock()
log.WithField("taskClassesRequired", len(taskClassesRequired)).
Debug("cleaning up inactive task classes")
m.removeInactiveClasses()
log.WithField("taskClassesRequired", len(taskClassesRequired)).
Debug("loading required task classes")
var taskClassList []*taskclass.Class
taskClassList, err = getTaskClassList(taskClassesRequired)
if err != nil {
return err
}
for _, class := range taskClassList {
taskClassIdentifier := class.Identifier.String()
// If it already exists we update, otherwise we add the new class
m.classes.UpdateClass(taskClassIdentifier, class)
}
return
}
// prefix will be prepended before name of descriptor when printing name of each descriptor
func logDescriptors(prefix string, logFunc func(format string, args ...interface{}), descriptors Descriptors) {
for _, desc := range descriptors {
printname := fmt.Sprintf("%s->%s", desc.TaskRole.GetPath(), desc.TaskClassName)
logFunc("%s%s", prefix, printname)
}
}
func (m *Manager) acquireTasks(envId uid.ID, taskDescriptors Descriptors) (err error) {
/*
Here's what's gonna happen:
1) check if any tasks are already in Roster, whether they are already locked
in an environment, and whether their host has attributes that satisfy the
constraints
1a) TODO: for each of them in Roster with matching attributes but wrong class,
mark for teardown and mesos-deployment
1b) for each of them in Roster with matching attributes and class, mark for
takeover and reconfiguration
3) TODO: teardown the tasks in tasksToTeardown
4) start the tasks in tasksToRun
5) ensure that all of them reach a CONFIGURED state
*/
// TODO: switch to this logger with envId everywhere
logWithId := log.WithField("partition", envId)
claimableTasks := m.roster.filtered(func(task *Task) bool {
return task.IsClaimable()
})
orphanTasks := m.roster.filtered(func(task *Task) bool {
return !task.IsLocked() && !task.IsClaimable()
})
claimableTasksByHostname := claimableTasks.Grouped(func(task *Task) string {
return task.hostname
})
orphanTasksByHostname := orphanTasks.Grouped(func(task *Task) string {
return task.hostname
})
log.WithField("partition", envId.String()).
Info("beginning of task acquisition and deployment for environment")
for hostname, tasks := range claimableTasksByHostname {
shortClassNames := make([]string, len(tasks))
for i, t := range tasks {
if tc := t.GetTaskClass(); tc != nil {
shortClassNames[i] = tc.Identifier.Name
} else {
shortClassNames[i] = "unknown"
}
}
log.WithField("partition", envId.String()).
Infof("host %s has %d claimable tasks [%s]", hostname, len(tasks), strings.Join(shortClassNames, ", "))
}
for hostname, tasks := range orphanTasksByHostname {
shortClassNames := make([]string, len(tasks))
for i, t := range tasks {
if tc := t.GetTaskClass(); tc != nil {
shortClassNames[i] = tc.Identifier.Name
} else {
shortClassNames[i] = "unknown"
}
}
log.WithField("partition", envId.String()).
Warnf("host %s has %d orphan tasks (cleanup needed) [%s]", hostname, len(tasks), strings.Join(shortClassNames, ", "))
}
tasksToRun := make(Descriptors, 0)
// TODO: also filter for tasks that satisfy attributes but are of wrong class,
// to be torn down and mesosed.
// tasksToTeardown := make([]TaskPtr, 0)
tasksAlreadyRunning := make(DeploymentMap)
if viper.GetBool("reuseUnlockedTasks") {
for _, descriptor := range taskDescriptors {
/*
For each descriptor we check m.AgentCache for agent attributes:
this allows us for each idle task in roster, get agentid and plug it in cache to get the
attributes for that host, and then we know whether
1) a running task of the same class on that agent would qualify
2) TODO: given enough resources obtained by freeing tasks, that agent would qualify
*/
// Filter function that accepts a Task if
// a) it's !Locked
// b) has className matching Descriptor
// c) its Agent's Attributes satisfy the Descriptor's Constraints
taskMatches := func(taskPtr *Task) (ok bool) {
if taskPtr != nil {
if taskPtr.IsClaimable() && taskPtr.className == descriptor.TaskClassName {
agentInfo := m.AgentCache.Get(mesos.AgentID{Value: taskPtr.agentId})
taskClass, classFound := m.classes.GetClass(descriptor.TaskClassName)
if classFound && taskClass != nil && agentInfo != nil {
targetConstraints := descriptor.
RoleConstraints.MergeParent(taskClass.Constraints)
if agentInfo.Attributes.Satisfy(targetConstraints) {
ok = true
return
}
}
}
}
return
}
runningTasksForThisDescriptor := m.roster.filtered(taskMatches)
claimed := false
if len(runningTasksForThisDescriptor) > 0 {
// We have received a list of running, unlocked candidates to take over
// the current Descriptor.
// We now go through them, and if one of them is already claimed in
// tasksAlreadyRunning, we go to the next one until we exhaust our options.
for _, taskPtr := range runningTasksForThisDescriptor {
if _, ok := tasksAlreadyRunning[taskPtr]; ok {
continue
} else { // task not claimed yet, we do so now
tasksAlreadyRunning[taskPtr] = descriptor
claimed = true
detector := ""
parent := taskPtr.GetParent()
if parent != nil {
detector, ok = parent.GetUserVars().Get("detector")
if !ok {
detector = ""
}
}
log.WithField("partition", envId.String()).
WithField("detector", detector).
WithField("class", descriptor.TaskClassName).
WithField("task", taskPtr.className).
WithField("taskHost", taskPtr.hostname).
Warn("claiming existing unlocked task for incoming descriptor")
break
}
}
}
if !claimed {
// no task can be claimed for the current descriptor, we add it to the list of
// new tasks to run
tasksToRun = append(tasksToRun, descriptor)
}
}
} else {
// no task reuse at all, just run tasks for all descriptors
tasksToRun = append(tasksToRun, taskDescriptors...)
}
// TODO: fill out tasksToTeardown in the previous loop
//if len(tasksToTeardown) > 0 {
// err = m.TeardownTasks(tasksToTeardown)
// if err != nil {
// return errors.New(fmt.Sprintf("cannot restart roles: %s", err.Error()))
// }
//}
// At this point, all descriptors are either
// - matched to a TaskPtr in tasksAlreadyRunning
// - awaiting Task deployment in tasksToRun
deploymentSuccess := true // hopefully
undeployedDescriptors := make(Descriptors, 0)
undeployableDescriptors := make(Descriptors, 0)
undeployedNonCriticalDescriptors := make(Descriptors, 0)
undeployedCriticalDescriptors := make(Descriptors, 0)
undeployableNonCriticalDescriptors := make(Descriptors, 0)
undeployableCriticalDescriptors := make(Descriptors, 0)
// we are retrying deployment multiple times in case of failure and we don't want
// to rerun tasks already running
tasksToRunThisAttempt := make(Descriptors, len(tasksToRun))
copy(tasksToRunThisAttempt, tasksToRun)
allDeployedTasks := make(DeploymentMap)
if len(tasksToRun) > 0 {
// Alright, so we have some descriptors whose requirements should be met with
// new Tasks we're about to deploy here.
// First we ask Mesos to revive offers and block until done, then upon receiving
// the offers, we ask Mesos to run the required roles - if any.
m.deployMu.Lock()
DEPLOYMENT_ATTEMPTS_LOOP:
for attemptCount := 0; attemptCount < MAX_ATTEMPTS_PER_DEPLOY_REQUEST; attemptCount++ {
// We loop through the deployment attempts until we either succeed or
// reach the maximum number of attempts. In the happy case, we should only
// need to try once. A retry should only be necessary if the Mesos master
// has not been able to provide the resources we need in the offers round
// immediately after reviving.
// We also keep track of the number of attempts made in the request object
// so that the scheduler can decide whether to retry or not.
// The request object is used to pass the tasks to deploy and the outcome
// channel to the deployment routine.
// reset all variable before try
deploymentSuccess = true
undeployedDescriptors = make(Descriptors, 0)
undeployableDescriptors = make(Descriptors, 0)
undeployedNonCriticalDescriptors = make(Descriptors, 0)
undeployedCriticalDescriptors = make(Descriptors, 0)
undeployableNonCriticalDescriptors = make(Descriptors, 0)
undeployableCriticalDescriptors = make(Descriptors, 0)
outcomeCh := make(chan ResourceOffersOutcome)
m.tasksToDeploy <- &ResourceOffersDeploymentRequest{
tasksToDeploy: tasksToRunThisAttempt,
envId: envId,
outcomeCh: outcomeCh,
} // buffered channel, does not block
log.WithField("partition", envId).
Debugf("scheduler has been sent request to deploy %d tasks", len(tasksToRunThisAttempt))
timeReviveOffers := time.Now()
timeDeployMu := time.Now()
m.reviveOffersTrg <- struct{}{} // signal scheduler to revive offers
<-m.reviveOffersTrg // we only continue when it's done
utils.TimeTrack(timeReviveOffers, "acquireTasks: revive offers",
log.WithField("tasksToRunThisAttempt", len(tasksToRunThisAttempt)).
WithField("partition", envId))
roOutcome := <-outcomeCh // blocks until a verdict from resourceOffers comes in
utils.TimeTrack(timeDeployMu, "acquireTasks: deployment critical section",
log.WithField("tasksToRunThisAttempt", len(tasksToRunThisAttempt)).
WithField("partition", envId))
deployedThisAttempt := roOutcome.deployed
undeployedDescriptors = roOutcome.undeployed
undeployableDescriptors = roOutcome.undeployable
logWithId.WithField("tasks", deployedThisAttempt).
Debugf("resourceOffers is done, %d new tasks running", len(deployedThisAttempt))
for deployedTask, deployedDescriptor := range deployedThisAttempt {
allDeployedTasks[deployedTask] = deployedDescriptor
// add deployed tasks to roster, so updates can be distributed properly
m.roster.append(deployedTask)
}
if len(deployedThisAttempt) != len(tasksToRunThisAttempt) {
// ↑ Not all roles could be deployed. If some were critical,
// we cannot proceed with running this environment. Either way,
// we keep the roles running since they might be useful in the future.
logWithId.WithField("level", infologger.IL_Devel).
Errorf("environment deployment failure: %d tasks requested for deployment, but %d deployed", len(tasksToRunThisAttempt), len(deployedThisAttempt))
for _, desc := range undeployedDescriptors {
if desc.TaskRole.GetTaskTraits().Critical == true {
deploymentSuccess = false
undeployedCriticalDescriptors = append(undeployedCriticalDescriptors, desc)
} else {
undeployedNonCriticalDescriptors = append(undeployedNonCriticalDescriptors, desc)
}
}
for _, desc := range undeployableDescriptors {
if desc.TaskRole.GetTaskTraits().Critical == true {
deploymentSuccess = false
undeployableCriticalDescriptors = append(undeployableCriticalDescriptors, desc)
} else {
undeployableNonCriticalDescriptors = append(undeployableNonCriticalDescriptors, desc)
}
}
}
if deploymentSuccess {
// ↑ means all the required critical processes are now running,
// and we are ready to update the envId
for taskPtr, descriptor := range deployedThisAttempt {
taskPtr.SetParent(descriptor.TaskRole)
// Ensure everything is filled out properly
if !taskPtr.IsLocked() {
log.WithField("task", taskPtr.taskId).Warning("cannot lock newly deployed task")
deploymentSuccess = false
}
}
break DEPLOYMENT_ATTEMPTS_LOOP
}
tasksToRunThisAttempt = make(Descriptors, 0, len(undeployableDescriptors)+len(undeployedDescriptors))
tasksToRunThisAttempt = append(tasksToRunThisAttempt, undeployedDescriptors...)
tasksToRunThisAttempt = append(tasksToRunThisAttempt, undeployableDescriptors...)
log.WithField("partition", envId).
WithField("level", infologger.IL_Devel).
Errorf("Deployment failed %d/%d attempts. Check messages in IL to figure out why. Retrying...", attemptCount+1, MAX_ATTEMPTS_PER_DEPLOY_REQUEST)
time.Sleep(time.Second * SLEEP_LENGTH_BETWEEN_PER_DEPLOY_REQUESTS)
}
}
log.Infof("Succeeded to deploy %d/%d tasks", len(allDeployedTasks), len(tasksToRun))
{
logWithIdDev := logWithId.WithField("level", infologger.IL_Devel)
logDescriptors("critical task deployment impossible: ", logWithIdDev.Errorf, undeployableCriticalDescriptors)
logDescriptors("critical task deployment failure: ", logWithIdDev.Errorf, undeployedCriticalDescriptors)
logDescriptors("non-critical task deployment failure: ", logWithIdDev.Warningf, undeployedNonCriticalDescriptors)
logDescriptors("non-critical task deployment impossible: ", logWithIdDev.Warningf, undeployableNonCriticalDescriptors)
}
// After retries notify environment about failed critical tasks
for _, desc := range undeployableDescriptors {
if desc.TaskRole.GetTaskTraits().Critical == true {
desc.TaskRole.UpdateStatus(UNDEPLOYABLE)
}
}
m.deployMu.Unlock()
if !deploymentSuccess {
var deployedTaskIds []string
for taskPtr := range allDeployedTasks {
taskPtr.SetParent(nil)
deployedTaskIds = append(deployedTaskIds, taskPtr.taskId)
}
err = TasksDeploymentError{
tasksErrorBase: tasksErrorBase{taskIds: deployedTaskIds},
failedNonCriticalDescriptors: undeployedNonCriticalDescriptors,
failedCriticalDescriptors: undeployedCriticalDescriptors,
undeployableNonCriticalDescriptors: undeployableNonCriticalDescriptors,
undeployableCriticalDescriptors: undeployableCriticalDescriptors,
}
}
if deploymentSuccess {
for taskPtr := range allDeployedTasks {
taskPtr.GetParent().SetTask(taskPtr)
}
for taskPtr, descriptor := range tasksAlreadyRunning {
taskPtr.SetParent(descriptor.TaskRole)
taskPtr.GetParent().SetTask(taskPtr)
}
}
return
}
func (m *Manager) releaseTasks(envId uid.ID, tasks Tasks) error {
taskReleaseErrors := make(map[string]error)
taskIdsReleased := make([]string, 0)
for _, task := range tasks {
err := m.releaseTask(envId, task)
if err == nil {
taskIdsReleased = append(taskIdsReleased, task.GetTaskId())
} else {
switch err.(type) {
case TaskAlreadyReleasedError:
continue
default:
taskReleaseErrors[task.GetTaskId()] = err
}
}
}
m.internalEventCh <- event.NewTasksReleasedEvent(envId, taskIdsReleased, taskReleaseErrors)
return nil
}
func (m *Manager) releaseTask(envId uid.ID, task *Task) error {
if task == nil {
return TaskNotFoundError{}
}
if task.IsLocked() && task.GetEnvironmentId() != envId {
return TaskLockedError{taskErrorBase: taskErrorBase{taskId: task.name}, envId: envId}
}
task.SetParent(nil)
return nil
}
func (m *Manager) configureTasks(envId uid.ID, tasks Tasks) error {
notify := make(chan controlcommands.MesosCommandResponse)
receivers, err := tasks.GetMesosCommandTargets()
if err != nil {
return err
}
if tasks == nil || len(tasks) == 0 {
return fmt.Errorf("empty task list to configure for environment %s", envId.String())
}
// We fetch each task's local bindMap to generate a global bindMap for the whole Tasks slice,
// i.e. a map of the paths of registered inbound channels and their ports.
bindMap := make(channel.BindMap)
for _, task := range tasks {
if task.GetParent() == nil { // Crash reported here by Roberto 6/2022
return fmt.Errorf("task %s on %s has nil parent, this should never happen", task.GetClassName(), task.GetHostname())
}
taskPath := task.GetParentRolePath()
for inbChName, endpoint := range task.GetLocalBindMap() {
var bindMapKey string
if strings.HasPrefix(inbChName, "::") { // global channel alias
bindMapKey = inbChName
// deduplication
if existingEndpoint, existsAlready := bindMap[bindMapKey]; existsAlready {
if channel.EndpointEquals(existingEndpoint, endpoint) {
// means somewhere something redefines the global channel alias,
// but the endpoint is the same so there's no problem
continue
} else {
return fmt.Errorf("workflow template contains illegal redefinition of global channel alias %s", bindMapKey)
}
}
} else {
bindMapKey = taskPath + TARGET_SEPARATOR + inbChName
}
bindMap[bindMapKey] = endpoint.ToTargetEndpoint(task.GetHostname())
}
}
log.WithFields(logrus.Fields{"bindMap": pp.Sprint(bindMap), "envId": envId.String()}).
Debug("generated inbound bindMap for environment configuration")
src := sm.STANDBY.String()
event := "CONFIGURE"
dest := sm.CONFIGURED.String()
args := make(controlcommands.PropertyMapsMap)
args, err = tasks.BuildPropertyMaps(bindMap)
if err != nil {
return err
}
log.WithField("map", pp.Sprint(args)).
WithField("partition", envId.String()).
Debug("pushing configuration to tasks")
cmd := controlcommands.NewMesosCommand_Transition(envId, receivers, src, event, dest, args)
cmd.ResponseTimeout = 120 * time.Second // The default timeout is 90 seconds, but we need more time for the tasks to configure
_ = m.cq.Enqueue(cmd, notify)
response := <-notify
close(notify)
if response == nil {
return fmt.Errorf("no response from Mesos to CONFIGURE transition request within %ds timeout", int(cmd.ResponseTimeout.Seconds()))
}
if response.IsMultiResponse() {
taskCriticalErrors := make([]string, 0)
taskNonCriticalErrors := make([]string, 0)
i := 0
for k, v := range response.Errors() {
task := m.GetTask(k.TaskId.Value)
var taskDescription string
if task != nil {
taskDescription = fmt.Sprintf("task '%s' on %s (id %s) failed with error: %s", task.GetParent().GetName(), task.GetHostname(), task.GetTaskId(), v.Error())
} else {
taskDescription = fmt.Sprintf("unknown task (id %s) failed with error: %s", k.TaskId.Value, v.Error())
}
if task != nil && task.GetTraits().Critical {
taskCriticalErrors = append(taskCriticalErrors, taskDescription)
} else if task != nil && task.parent != nil && task.parent.GetTaskTraits().Critical {
taskCriticalErrors = append(taskCriticalErrors, taskDescription)
} else {
taskNonCriticalErrors = append(taskNonCriticalErrors, taskDescription)
}
i++
}
if len(taskNonCriticalErrors) > 0 {
log.WithField("partition", envId).
Warnf("CONFIGURE could not complete for non-critical tasks, errors: %s", strings.Join(taskNonCriticalErrors, "; "))
}
if len(taskCriticalErrors) > 0 {
return fmt.Errorf("CONFIGURE could not complete for critical tasks, errors: %s", strings.Join(taskCriticalErrors, "; "))
}
return nil
} else {
respError := response.Err()
if respError != nil {
errText := respError.Error()
if len(strings.TrimSpace(errText)) != 0 {
return errors.New(response.Err().Error())
}
// FIXME: improve error handling ↑
}
}
return nil
}
func (m *Manager) transitionTasks(envId uid.ID, tasks Tasks, src string, event string, dest string, commonArgs controlcommands.PropertyMap) error {
notify := make(chan controlcommands.MesosCommandResponse)
receivers, err := tasks.GetMesosCommandTargets()
if err != nil {
return err
}
args := make(controlcommands.PropertyMapsMap)
// If we're pushing some arg values to all targets...
if len(commonArgs) > 0 {
for _, rec := range receivers {
args[rec] = make(controlcommands.PropertyMap)
for k, v := range commonArgs {
args[rec][k] = v
}
}
}
cmd := controlcommands.NewMesosCommand_Transition(envId, receivers, src, event, dest, args)
_ = m.cq.Enqueue(cmd, notify)
response := <-notify
close(notify)
if response == nil {
return errors.New("unknown MesosCommand error: nil response received")
}
if response.IsMultiResponse() {
taskCriticalErrors := make([]string, 0)
taskNonCriticalErrors := make([]string, 0)
i := 0
for k, v := range response.Errors() {
task := m.GetTask(k.TaskId.Value)
var taskDescription string
if task != nil {
tci := task.GetTaskCommandInfo()
tciValue := "unknown command"
if tci.Value != nil {
tciValue = *tci.Value
}
taskDescription = fmt.Sprintf("task '%s' on %s (id %s) failed with error: %s", tciValue, task.GetHostname(), task.GetTaskId(), v.Error())
} else {
taskDescription = fmt.Sprintf("unknown task (id %s) failed with error: %s", k.TaskId.Value, v.Error())
}
if task != nil && task.GetTraits().Critical {
taskCriticalErrors = append(taskCriticalErrors, taskDescription)
} else if task != nil && task.parent != nil && task.parent.GetTaskTraits().Critical {
taskCriticalErrors = append(taskCriticalErrors, taskDescription)
} else {
taskNonCriticalErrors = append(taskNonCriticalErrors, taskDescription)
}
i++
}
if len(taskNonCriticalErrors) > 0 {
log.WithField("partition", envId).
Warnf("%s could not complete for non-critical tasks, errors: %s", event, strings.Join(taskNonCriticalErrors, "; "))
}
if len(taskCriticalErrors) > 0 {
return fmt.Errorf("%s could not complete for critical tasks, errors: %s", event, strings.Join(taskCriticalErrors, "; "))
}
return nil
} else {
respError := response.Err()
if respError != nil {
errText := respError.Error()
if len(strings.TrimSpace(errText)) != 0 {
return errors.New(response.Err().Error())
}
// FIXME: improve error handling ↑
}
}
return nil
}
func (m *Manager) TriggerHooks(envId uid.ID, tasks Tasks) error {
if len(tasks) == 0 {
return nil
}
notify := make(chan controlcommands.MesosCommandResponse)
receivers, err := tasks.GetMesosCommandTargets()
if err != nil {
return err
}
cmd := controlcommands.NewMesosCommand_TriggerHook(envId, receivers)
err = m.cq.Enqueue(cmd, notify)
if err != nil {
return err
}
response := <-notify
close(notify)
if response == nil {
return errors.New("unknown MesosCommand error: nil response received")
}
respError := response.Err()
if respError != nil {
errText := respError.Error()
if len(strings.TrimSpace(errText)) != 0 {
return errors.New(response.Err().Error())
}
// FIXME: improve error handling ↑
}
return nil
}
func (m *Manager) GetTaskClass(name string) (b *taskclass.Class) {
if m == nil {
return
}
b, _ = m.classes.GetClass(name)
return
}
func (m *Manager) TaskCount() int {
if m == nil {
return -1
}
return len(m.roster.getTasks())
}
func (m *Manager) GetTasks() Tasks {
if m == nil {
return nil
}
return m.roster.getTasks()
}
func (m *Manager) GetTask(id string) *Task {
if m == nil {
return nil
}
for _, t := range m.roster.getTasks() {
if t.taskId == id {
return t
}
}
return nil
}
func (m *Manager) updateTaskState(taskId string, state string) {
taskPtr := m.roster.getByTaskId(taskId)
if taskPtr == nil {
if state != "DONE" {
log.WithField("taskId", taskId).
WithField("state", state).
WithField(infologger.Level, infologger.IL_Support).
Warn("attempted state update of task not in roster")
}
return
}
st := sm.StateFromString(state)
taskPtr.state = st
taskPtr.safeToStop = false
taskPtr.SendEvent(&event.TaskEvent{Name: taskPtr.GetName(), TaskID: taskId, State: state, Hostname: taskPtr.hostname, ClassName: taskPtr.GetClassName()})
if taskPtr.GetParent() != nil {
taskPtr.GetParent().UpdateState(st)
}
}
func (m *Manager) updateTaskStatus(status *mesos.TaskStatus) {
aid := status.GetAgentID()
host := ""
detector := ""
var err error
if aid != nil {
aci := m.AgentCache.Get(*aid)
if aci != nil {
host = aci.Hostname
detector, err = apricot.Instance().GetDetectorForHost(host)
if err != nil {
detector = ""
}
}