-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathmanager.go
More file actions
1570 lines (1398 loc) · 52.2 KB
/
manager.go
File metadata and controls
1570 lines (1398 loc) · 52.2 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-2022 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 environment
import (
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/AliceO2Group/Control/common"
"github.com/AliceO2Group/Control/common/controlmode"
"github.com/AliceO2Group/Control/common/event"
"github.com/AliceO2Group/Control/common/event/topic"
"github.com/AliceO2Group/Control/common/logger/infologger"
evpb "github.com/AliceO2Group/Control/common/protos"
"github.com/AliceO2Group/Control/common/system"
"github.com/AliceO2Group/Control/common/utils"
"github.com/AliceO2Group/Control/common/utils/uid"
lhcevent "github.com/AliceO2Group/Control/core/integration/lhc/event"
event2 "github.com/AliceO2Group/Control/core/integration/odc/event"
"github.com/AliceO2Group/Control/core/task"
"github.com/AliceO2Group/Control/core/task/sm"
"github.com/AliceO2Group/Control/core/task/taskop"
"github.com/AliceO2Group/Control/core/the"
"github.com/AliceO2Group/Control/core/workflow"
pb "github.com/AliceO2Group/Control/executor/protos"
"github.com/sirupsen/logrus"
)
type Manager struct {
mu sync.RWMutex
m map[uid.ID]*Environment
taskman *task.Manager
incomingEventCh chan event.Event
pendingTeardownsCh map[uid.ID]chan *event.TasksReleasedEvent
pendingStateChangeCh map[uid.ID]chan *event.TasksStateChangedEvent
}
var instance *Manager
func ManagerInstance() *Manager {
return instance
}
func NewEnvManager(tm *task.Manager, incomingEventCh chan event.Event) *Manager {
instance = &Manager{
m: make(map[uid.ID]*Environment),
taskman: tm,
incomingEventCh: incomingEventCh,
pendingTeardownsCh: make(map[uid.ID]chan *event.TasksReleasedEvent),
pendingStateChangeCh: make(map[uid.ID]chan *event.TasksStateChangedEvent),
}
go func() {
for {
select {
case incomingEvent := <-instance.incomingEventCh:
switch typedEvent := incomingEvent.(type) {
case event.DeviceEvent:
instance.handleDeviceEvent(typedEvent)
case event.IntegratedServiceEvent:
instance.handleIntegratedServiceEvent(typedEvent)
case *event.ExecutorFailedEvent:
envIdsAffected := tm.HandleExecutorFailed(typedEvent)
for envId := range envIdsAffected {
env, err := instance.environment(envId)
if err != nil {
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithField("executorId", typedEvent.GetId().Value).
WithError(err).
Error("cannot find environment for incoming executor failed event")
}
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithField("executorId", typedEvent.GetId().Value).
WithField("envState", env.CurrentState()).
Debug("received executor failed event")
}
case *event.AgentFailedEvent:
envIdsAffected := tm.HandleAgentFailed(typedEvent)
for envId := range envIdsAffected {
env, err := instance.environment(envId)
if err != nil {
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithField("agentId", typedEvent.GetId().Value).
WithError(err).
Error("cannot find environment for incoming agent failed event")
}
log.WithPrefix("scheduler").
WithField("partition", envId.String()).
WithField("agentId", typedEvent.GetId().Value).
WithField("envState", env.CurrentState()).
Debug("received agent failed event")
}
case *event.TasksReleasedEvent:
// If we got a TasksReleasedEvent, it must be matched with a pending
// environment teardown.
instance.mu.RLock()
thisEnvCh, ok := instance.pendingTeardownsCh[typedEvent.GetEnvironmentId()]
instance.mu.RUnlock()
if ok {
thisEnvCh <- typedEvent
instance.mu.Lock()
close(thisEnvCh)
delete(instance.pendingTeardownsCh, typedEvent.GetEnvironmentId())
instance.mu.Unlock()
} else {
// If there is no pending environment teardown, it means that the released task stopped
// unexpectedly. In that case, the environment should get torn-down only if the task
// is critical.
releaseCriticalTask := false
for _, v := range typedEvent.GetTaskIds() {
if tm.GetTask(v) != nil {
if tm.GetTask(v).GetTraits().Critical == true {
//|| tm.GetTask(v).GetParent().GetTaskTraits().Critical == true
releaseCriticalTask = true
}
}
}
if releaseCriticalTask {
thisEnvCh <- typedEvent
instance.mu.Lock()
close(thisEnvCh)
delete(instance.pendingTeardownsCh, typedEvent.GetEnvironmentId())
instance.mu.Unlock()
}
}
case *event.TasksStateChangedEvent:
// If we got a TasksStateChangedEvent, it must be matched with a pending
// environment transition.
instance.mu.RLock()
thisEnvCh, ok := instance.pendingStateChangeCh[typedEvent.GetEnvironmentId()]
instance.mu.RUnlock()
// If environment is not in state transition message is being propagated through task/manager
if ok {
thisEnvCh <- typedEvent
}
default:
// noop
}
}
}
}()
return instance
}
func (envs *Manager) NotifyIntegratedServiceEvent(event event.IntegratedServiceEvent) {
envs.incomingEventCh <- event
}
func (envs *Manager) GetActiveDetectors() system.IDMap {
envs.mu.RLock()
defer envs.mu.RUnlock()
response := make(system.IDMap)
for _, env := range envs.m {
if env.workflow == nil { // we can only query for detectors post-workflow-load
continue
}
envDetectors := env.GetActiveDetectors()
for det := range envDetectors {
response[det] = struct{}{}
}
}
return response
}
func (envs *Manager) CreateEnvironment(workflowPath string, userVars map[string]string, public bool, newId uid.ID, autoTransition bool) (resultEnvId uid.ID, resultErr error) {
// Before we load the workflow, we get the list of currently active detectors. This query must be performed before
// loading the workflow in order to compare the currently used detectors with the detectors required by the newly
// created environment.
alreadyActiveDetectors := envs.GetActiveDetectors()
lastRequestUser := &evpb.User{}
lastRequestUserJ, ok := userVars["last_request_user"]
if ok {
_ = json.Unmarshal([]byte(lastRequestUserJ), lastRequestUser)
}
// CreateEnvironment() is not transition from state machine, so we need to emit the same message as in TryTransition
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: newId.String(),
State: "PENDING",
Transition: "CREATE",
TransitionStatus: evpb.OpStatus_STARTED,
LastRequestUser: lastRequestUser,
Message: "transition starting",
})
// report error of the CreateEnvironment() in the same way as in TryTransition
defer func() {
if resultErr != nil {
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: newId.String(),
Error: resultErr.Error(),
LastRequestUser: lastRequestUser,
Message: "transition error",
State: "PENDING",
Transition: "CREATE",
TransitionStatus: evpb.OpStatus_DONE_ERROR,
})
}
}()
// in case of err==nil, env will be false unless user
// set it to True which will be overwritten in server.go
workflowPublicInfo, err := parseWorkflowPublicInfo(workflowPath)
if err != nil {
log.WithField("public info", public).
WithField("workflow path", workflowPath).
WithError(err).
Warn("parse workflow public info failed.")
resultEnvId = newId
resultErr = fmt.Errorf("workflow public info parsing failed: %w", err)
return
}
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: newId.String(),
State: "PENDING",
Transition: "CREATE",
TransitionStep: "before_CREATE",
TransitionStatus: evpb.OpStatus_STARTED,
Message: "instantiating",
LastRequestUser: lastRequestUser,
WorkflowTemplateInfo: &evpb.WorkflowTemplateInfo{
Path: workflowPath,
Public: workflowPublicInfo.IsPublic,
Name: workflowPublicInfo.Name,
Description: workflowPublicInfo.Description,
},
})
// userVar identifiers come in 2 forms:
// environment user var: "someKey"
// workflow user var: "path.to.some.role:someKey"
// We need to split them into 2 structures, the first of which is passed to newEnvironment and the other one
// to loadWorkflow as its keys must be injected into one or more specific roles.
envUserVars := make(map[string]string)
workflowUserVars := make(map[string]string)
for k, v := range userVars {
// If the key contains a ':', means we have a var associated with a specific workflow role
if strings.ContainsRune(k, task.TARGET_SEPARATOR_RUNE) {
workflowUserVars[k] = v
} else {
envUserVars[k] = v
}
}
cleanedUpTasks, runningTasks, err := envs.taskman.Cleanup()
if err != nil {
log.WithError(err).
Warnf("pre-deployment cleanup failed, continuing anyway")
err = nil
} else {
cleanedUpTaskIds, runningTaskIds := make([]string, 0), make([]string, 0)
for _, t := range cleanedUpTasks {
cleanedUpTaskIds = append(cleanedUpTaskIds, fmt.Sprintf("%s.%s#%s", t.GetHostname(), t.GetClassName(), t.GetTaskId()))
}
for _, t := range runningTasks {
runningTaskIds = append(runningTaskIds, fmt.Sprintf("%s.%s#%s", t.GetHostname(), t.GetClassName(), t.GetTaskId()))
}
log.WithField("tasksCleanedUp", strings.Join(cleanedUpTaskIds, ", ")).
WithField("level", infologger.IL_Devel).
Debug("tasks cleaned up during pre-deployment cleanup")
log.WithField("tasksStillRunning", strings.Join(runningTaskIds, ", ")).
WithField("level", infologger.IL_Devel).
Debug("tasks still running after pre-deployment cleanup")
log.WithField("level", infologger.IL_Ops).
Infof("pre-deployment cleanup completed (%d tasks cleaned up, %d tasks still running)", len(cleanedUpTasks), len(runningTasks))
}
var env *Environment
env, err = newEnvironment(envUserVars, newId)
if public {
env.Public = true
}
gotEnvId := uid.NilID()
if err == nil {
if env != nil {
gotEnvId = env.Id()
} else {
err = errors.New("newEnvironment returned nil environment")
log.WithError(err).
WithField("partition", newId.String()).
Logf(logrus.FatalLevel, "environment creation failed")
}
}
if err != nil || env == nil {
if env == nil {
err = errors.New("newEnvironment returned nil environment")
}
log.WithError(err).
WithField("partition", gotEnvId.String()).
Logf(logrus.FatalLevel, "environment creation failed")
resultEnvId = gotEnvId
resultErr = err
return
}
log.WithFields(logrus.Fields{
"workflow": workflowPath,
"partition": gotEnvId.String(),
}).Info("creating new environment")
env.Public = workflowPublicInfo.IsPublic
env.name = workflowPublicInfo.Name
env.Description = workflowPublicInfo.Description
env.WorkflowPath = workflowPath
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: newId.String(),
State: "PENDING",
Transition: "CREATE",
TransitionStep: "before_CREATE",
TransitionStatus: evpb.OpStatus_ONGOING,
Message: "running hooks",
LastRequestUser: lastRequestUser,
WorkflowTemplateInfo: env.GetWorkflowInfo(),
})
env.hookHandlerF = func(hooks task.Tasks) error {
return envs.taskman.TriggerHooks(gotEnvId, hooks)
}
// Ensure the environment_id is available to all
env.UserVars.Set("environment_id", env.id.String())
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: newId.String(),
State: "PENDING",
Transition: "CREATE",
TransitionStep: "CREATE",
TransitionStatus: evpb.OpStatus_ONGOING,
Message: "loading workflow",
LastRequestUser: lastRequestUser,
WorkflowTemplateInfo: env.GetWorkflowInfo(),
})
// We load the workflow (includes template processing)
env.workflow, err = envs.loadWorkflow(workflowPath, env.wfAdapter, workflowUserVars, env.BaseConfigStack)
if err != nil {
err = fmt.Errorf("cannot load workflow template: %w", err)
resultEnvId = env.id
resultErr = err
return
}
// Ensure we provide a very defaulty `detectors` variable
detectors, err := the.ConfSvc().GetDetectorsForHosts(env.GetFLPs())
if err != nil {
err = fmt.Errorf("cannot acquire detectors in loaded workflow template: %w", err)
resultEnvId = env.id
resultErr = err
return
}
detectorsStr, err := SliceToJSONSlice(detectors)
if err != nil {
err = fmt.Errorf("cannot process detectors in loaded workflow template: %w", err)
resultEnvId = env.id
resultErr = err
return
}
env.GlobalDefaults.Set("detectors", detectorsStr)
log.WithFields(logrus.Fields{
"partition": gotEnvId.String(),
}).Infof("detectors in environment: %s", strings.Join(detectors, " "))
// env.GetActiveDetectors() is valid starting now, so we can check for detector exclusion
neededDetectors := env.GetActiveDetectors()
for det := range neededDetectors {
if _, contains := alreadyActiveDetectors[det]; contains {
// required detector det is already active in some other environment
resultEnvId = env.id
resultErr = fmt.Errorf("detector %s is already in use", det.String())
return
}
}
cvs, _ := env.Workflow().ConsolidatedVarStack()
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: newId.String(),
State: env.CurrentState(),
Transition: "CREATE",
TransitionStep: "after_CREATE",
TransitionStatus: evpb.OpStatus_DONE_OK,
Message: "workflow loaded",
Vars: cvs, // we push the full var stack of the root role in the workflow loaded event
LastRequestUser: lastRequestUser,
WorkflowTemplateInfo: env.GetWorkflowInfo(),
})
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: newId.String(),
LastRequestUser: lastRequestUser,
Message: "transition completed successfully",
State: env.CurrentState(),
Transition: "CREATE",
TransitionStatus: evpb.OpStatus_DONE_OK,
})
log.WithField("method", "CreateEnvironment").
WithField("level", infologger.IL_Devel).
Debug("envman write lock")
envs.mu.Lock()
envs.m[env.id] = env
envs.pendingStateChangeCh[env.id] = env.stateChangedCh
envs.mu.Unlock()
log.WithField("method", "CreateEnvironment").
WithField("level", infologger.IL_Devel).
Debug("envman write unlock")
err = env.TryTransition(NewDeployTransition(
envs.taskman,
nil, // roles,
nil),
)
if err == nil {
err = env.TryTransition(NewConfigureTransition(
envs.taskman),
)
}
if err == nil {
// CONFIGURE transition successful!
env.subscribeToWfState(envs.taskman)
if autoTransition {
// We now return the configured environment from CreateEnvironment, but if autoTransition is set to true
// then the auto-transitioner starts here.
// Sequence:
// * CONFIGURED×START_ACTIVITY→RUNNING
// * wait for RUNNING to finish as required by tasks (RUNNING×STOP_ACTIVITY→CONFIGURED)
// * safe DESTROY path
go func() {
defer env.unsubscribeFromWfState()
goErrorKillDestroy := func(op string) {
envState := env.CurrentState()
log.WithField("state", envState).
WithField("partition", env.Id().String()).
WithError(err).
Errorf("auto-transitioning environment failed %s, cleanup in progress", op)
the.EventWriterWithTopic(topic.Environment).WriteEvent(
NewEnvGoErrorEvent(env, fmt.Sprintf("%s failed: %v", op, err)),
)
err := env.TryTransition(NewGoErrorTransition(
envs.taskman),
)
if err != nil {
HandleFailedGoError(err, env)
}
envTasks := env.Workflow().GetTasks()
// TeardownEnvironment manages the envs.mu internally
_ = envs.TeardownEnvironment(env.Id(), true /*force*/)
killedTasks, _, rlsErr := envs.taskman.KillTasks(envTasks.GetTaskIds())
if rlsErr != nil {
log.WithError(rlsErr).Warn("task teardown error")
}
log.WithFields(logrus.Fields{
"killedCount": len(killedTasks),
"lastEnvState": envState,
"level": infologger.IL_Support,
"partition": env.Id().String(),
}).
Infof("auto-environment failed at %s, tasks were cleaned up", op)
log.WithField("partition", env.Id().String()).Info("environment teardown complete")
}
// now we have the environment we should transition to start
trans := NewStartActivityTransition(envs.taskman)
if trans == nil {
goErrorKillDestroy("transition START_ACTIVITY")
return
}
err = env.TryTransition(trans)
if err != nil {
goErrorKillDestroy("transition START_ACTIVITY")
return
}
for {
// we know we performed START_ACTIVITY, so we poll at 1Hz for the run to finish
time.Sleep(1 * time.Second)
if env == nil {
// must've died during the loop
return
}
envState := env.CurrentState()
switch envState {
case "CONFIGURED":
// RUN finished so we can reset and delete the environment
err = env.TryTransition(NewResetTransition(envs.taskman))
if err != nil {
goErrorKillDestroy("transition RESET")
return
}
err = envs.TeardownEnvironment(env.id, false)
if err != nil {
goErrorKillDestroy("teardown")
return
}
tasksForEnv := env.Workflow().GetTasks().GetTaskIds()
_, _, err = envs.taskman.KillTasks(tasksForEnv)
if err != nil {
return
}
return
case "ERROR":
fallthrough
case "STANDBY":
fallthrough
case "DEPLOYED":
goErrorKillDestroy("transition STOP_ACTIVITY")
return
case "MIXED":
continue
case "":
continue
}
}
}()
}
resultEnvId = env.id
resultErr = err
return
}
// Deployment/configuration failure code path starts here
envState := env.CurrentState()
log.WithField("partition", env.Id().String()).
Errorf("environment deployment and configuration failed (%s)", workflowPath)
log.WithField("state", envState).
WithField("partition", env.Id().String()).
WithError(err).
WithField("level", infologger.IL_Devel).
Error("environment deployment and configuration error, cleanup in progress")
the.EventWriterWithTopic(topic.Environment).WriteEvent(
NewEnvGoErrorEvent(env, fmt.Sprintf("deployment or configuration failed: %v", err)),
)
errTxErr := env.TryTransition(NewGoErrorTransition(
envs.taskman),
)
if errTxErr != nil {
HandleFailedGoError(errTxErr, env)
}
envTasks := env.Workflow().GetTasks()
// TeardownEnvironment manages the envs.mu internally
// We do not get the error here cause it overwrites the failed deployment error
// with <nil> which results to server.go to report back
// cannot get newly created environment: no environment with id <env id>
_ = envs.TeardownEnvironment(env.Id(), true /*force*/)
killedTasks, _, rlsErr := envs.taskman.KillTasks(envTasks.GetTaskIds())
if rlsErr != nil {
log.WithError(rlsErr).Warn("task teardown error")
}
log.WithFields(logrus.Fields{
"killedCount": len(killedTasks),
"lastEnvState": envState,
"level": infologger.IL_Support,
"partition": env.Id().String(),
}).
Info("environment deployment failed, tasks were cleaned up")
log.WithField("partition", env.Id().String()).Info("environment teardown complete")
return env.id, err
}
func (envs *Manager) TeardownEnvironment(environmentId uid.ID, force bool) error {
log.WithFields(logrus.Fields{
"partition": environmentId.String(),
}).Info("tearing down environment")
envs.mu.RLock()
env, err := envs.environment(environmentId)
envs.mu.RUnlock()
if err != nil {
return err
}
if !env.transitionMutex.TryLock() {
log.WithField("partition", environmentId.String()).
Warnf("environment teardown attempt delayed: transition '%s' in progress. waiting for completion or failure", env.currentTransition)
env.transitionMutex.Lock()
log.WithField("level", infologger.IL_Support).
WithField("partition", environmentId.String()).
Infof("environment teardown attempt resumed")
}
defer env.transitionMutex.Unlock()
if env.CurrentState() == "DONE" {
return errors.New("attempting to teardown an environment which is already in DONE, doing nothing")
}
if env.CurrentState() != "STANDBY" && env.CurrentState() != "DEPLOYED" && !force {
return errors.New(fmt.Sprintf("cannot teardown environment in state %s", env.CurrentState()))
}
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: environmentId.String(),
State: env.CurrentState(),
Transition: "DESTROY",
TransitionStep: "before_DESTROY",
TransitionStatus: evpb.OpStatus_STARTED,
Message: "workflow teardown started",
LastRequestUser: env.GetLastRequestUser(),
WorkflowTemplateInfo: env.GetWorkflowInfo(),
})
env.Mu.Lock()
env.currentTransition = "DESTROY"
env.Mu.Unlock()
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: environmentId.String(),
State: env.CurrentState(),
Transition: "DESTROY",
TransitionStep: "leave_" + env.CurrentState(),
TransitionStatus: evpb.OpStatus_ONGOING,
Message: "workflow teardown ongoing",
LastRequestUser: env.GetLastRequestUser(),
WorkflowTemplateInfo: env.GetWorkflowInfo(),
})
err = env.handleAllHooks(env.Workflow(), "leave_"+env.CurrentState())
if err != nil {
log.WithFields(logrus.Fields{
"partition": environmentId.String(),
}).Error(fmt.Errorf("could not handle hooks for the trigger leave_%s, error: %w", env.CurrentState(), err))
}
if env.CurrentState() == "RUNNING" {
endTime, ok := env.workflow.GetUserVars().Get("run_end_time_ms")
if ok && endTime == "" {
runEndTime := time.Now()
runEndTimeS := strconv.FormatInt(runEndTime.UnixMilli(), 10)
env.workflow.SetRuntimeVar("run_end_time_ms", runEndTimeS)
the.EventWriterWithTopic(topic.Run).WriteEventWithTimestamp(&evpb.Ev_RunEvent{
EnvironmentId: environmentId.String(),
RunNumber: env.GetCurrentRunNumber(),
State: env.Sm.Current(),
Error: "",
Transition: "TEARDOWN",
TransitionStatus: evpb.OpStatus_STARTED,
}, runEndTime)
} else {
log.WithField("partition", environmentId.String()).
Debug("O2 End time already set before DESTROY")
}
endCompletionTime, ok := env.workflow.GetUserVars().Get("run_end_completion_time_ms")
if ok && endCompletionTime == "" {
runEndCompletionTime := time.Now()
runEndCompletionTimeS := strconv.FormatInt(runEndCompletionTime.UnixMilli(), 10)
env.workflow.SetRuntimeVar("run_end_completion_time_ms", runEndCompletionTimeS)
the.EventWriterWithTopic(topic.Run).WriteEventWithTimestamp(&evpb.Ev_RunEvent{
EnvironmentId: environmentId.String(),
RunNumber: env.GetCurrentRunNumber(),
State: env.Sm.Current(),
Error: "",
Transition: "TEARDOWN",
TransitionStatus: evpb.OpStatus_STARTED,
}, runEndCompletionTime)
} else {
log.WithField("partition", environmentId.String()).
Debug("O2 End Completion time already set before DESTROY")
}
}
tasksToRelease := env.Workflow().GetTasks()
// we gather all DESTROY/after_DESTROY hooks, as these require special treatment
hooksMapForDestroy := env.Workflow().GetHooksMapForTrigger("DESTROY")
for k, v := range env.Workflow().GetHooksMapForTrigger("after_DESTROY") {
hooksMapForDestroy[k] = v
}
allWeights := hooksMapForDestroy.GetWeights()
// for each weight within DESTROY
// for each found DESTROY hook,
// for each of *all* tasks last-to-first
// if the pointed task is one of the known cleanup hooks, remove it
for _, weight := range allWeights {
hooksForWeight, ok := hooksMapForDestroy[weight]
if ok {
for _, hook := range hooksForWeight {
for i := len(tasksToRelease) - 1; i >= 0; i-- {
if hook == tasksToRelease[i] {
tasksToRelease = append(tasksToRelease[:i], tasksToRelease[i+1:]...)
}
}
}
}
}
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: environmentId.String(),
State: env.CurrentState(),
Transition: "DESTROY",
TransitionStep: "DESTROY",
TransitionStatus: evpb.OpStatus_ONGOING,
Message: "releasing tasks",
LastRequestUser: env.GetLastRequestUser(),
WorkflowTemplateInfo: env.GetWorkflowInfo(),
})
log.WithField("method", "TeardownEnvironment").
WithField("level", infologger.IL_Devel).
Debug("envman write lock")
envs.mu.Lock()
// we kill all tasks that aren't cleanup hooks
taskmanMessage := task.NewEnvironmentMessage(taskop.ReleaseTasks, environmentId, tasksToRelease, nil)
// close state channel
if ch := envs.pendingStateChangeCh[environmentId]; ch != nil {
close(envs.pendingStateChangeCh[environmentId])
}
delete(envs.pendingStateChangeCh, environmentId)
envs.mu.Unlock()
log.WithField("method", "TeardownEnvironment").
WithField("level", infologger.IL_Devel).
Debug("envman write lock")
// We set all callRoles to INACTIVE right now, because there's no task activation for them.
// This is the callRole equivalent of AcquireTasks, which only pushes updates to taskRoles.
allHooks := env.Workflow().GetAllHooks()
callHooks := allHooks.FilterCalls() // get the calls
if len(callHooks) > 0 {
for _, h := range callHooks {
pr, ok := h.GetParentRole().(workflow.PublicUpdatable)
if !ok {
continue
}
go pr.UpdateStatus(task.INACTIVE)
}
}
pendingCh := make(chan *event.TasksReleasedEvent)
log.WithField("method", "TeardownEnvironment").
WithField("level", infologger.IL_Devel).
Debug("envman write lock")
envs.mu.Lock()
envs.pendingTeardownsCh[environmentId] = pendingCh
envs.mu.Unlock()
log.WithField("method", "TeardownEnvironment").
WithField("level", infologger.IL_Devel).
Debug("envman write lock")
envs.taskman.MessageChannel <- taskmanMessage
incomingEv := <-pendingCh
// If some tasks failed to release
if taskReleaseErrors := incomingEv.GetTaskReleaseErrors(); len(taskReleaseErrors) > 0 {
for taskId, err := range taskReleaseErrors {
log.WithFields(logrus.Fields{
"taskId": taskId,
"partition": environmentId,
}).
WithError(err).
Warn("task failed to release")
}
err = fmt.Errorf("%d tasks failed to release for environment %s",
len(taskReleaseErrors), environmentId)
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: environmentId.String(),
State: "DONE",
Transition: "DESTROY",
TransitionStep: "after_DESTROY",
TransitionStatus: evpb.OpStatus_DONE_ERROR,
Message: "environment teardown finished with error",
Error: err.Error(),
LastRequestUser: env.GetLastRequestUser(),
WorkflowTemplateInfo: env.GetWorkflowInfo(),
})
return err
}
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: environmentId.String(),
State: env.CurrentState(),
Transition: "DESTROY",
TransitionStep: "after_DESTROY",
TransitionStatus: evpb.OpStatus_ONGOING,
Message: "running DESTROY hooks",
LastRequestUser: env.GetLastRequestUser(),
WorkflowTemplateInfo: env.GetWorkflowInfo(),
})
// we trigger all cleanup hooks, first calls, then tasks immediately after
for _, weight := range allWeights {
hooksForWeight, ok := hooksMapForDestroy[weight]
if ok {
hooksForWeight.FilterCalls().CallAll()
// calls done, we start the task hooks...
cleanupTaskHooks := hooksForWeight.FilterTasks()
// ...but only if their parent role is still ACTIVE (i.e. not killed or executor failed)
cleanupTaskHooks = cleanupTaskHooks.Filtered(func(t *task.Task) bool {
if pr, prOk := t.GetParentRole().(workflow.Role); prOk {
return pr.GetStatus() == task.ACTIVE
}
return false
})
err = envs.taskman.TriggerHooks(environmentId, cleanupTaskHooks)
if err != nil {
log.WithField("partition", environmentId.String()).
WithError(err).
Warn("environment post-destroy hooks failed")
}
// and then we kill them too
taskmanMessage = task.NewEnvironmentMessage(taskop.ReleaseTasks, environmentId, cleanupTaskHooks, nil)
}
}
envs.cancelCallsPendingAwait(env)
// we remake the pending teardown channel too, because each completed TasksReleasedEvent
// automatically closes it
pendingCh = make(chan *event.TasksReleasedEvent)
log.WithField("method", "TeardownEnvironment").
WithField("level", infologger.IL_Devel).
Debug("envman write lock")
envs.mu.Lock()
envs.pendingTeardownsCh[environmentId] = pendingCh
envs.mu.Unlock()
log.WithField("method", "TeardownEnvironment").
WithField("level", infologger.IL_Devel).
Debug("envman write lock")
envs.taskman.MessageChannel <- taskmanMessage
incomingEv = <-pendingCh
// If some cleanup hooks failed to release
if taskReleaseErrors := incomingEv.GetTaskReleaseErrors(); len(taskReleaseErrors) > 0 {
for taskId, err := range taskReleaseErrors {
log.WithFields(logrus.Fields{
"taskId": taskId,
"partition": environmentId,
}).
WithError(err).
Warn("task failed to release")
}
err = fmt.Errorf("%d tasks failed to release for environment %s",
len(taskReleaseErrors), environmentId)
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: environmentId.String(),
State: "DONE",
Transition: "DESTROY",
TransitionStep: "after_DESTROY",
TransitionStatus: evpb.OpStatus_DONE_ERROR,
Message: "environment teardown finished with error",
Error: err.Error(),
LastRequestUser: env.GetLastRequestUser(),
WorkflowTemplateInfo: env.GetWorkflowInfo(),
})
return err
}
env.setState("DONE")
env.sendEnvironmentEvent(&event.EnvironmentEvent{EnvironmentID: env.Id().String(), Message: "teardown complete", State: "DONE"})
log.WithField("method", "TeardownEnvironment").
WithField("level", infologger.IL_Devel).
Debug("envman write lock")
envs.mu.Lock()
defer envs.mu.Unlock()
delete(envs.m, environmentId)
env.unsubscribeFromWfState()
log.WithField("method", "TeardownEnvironment").
WithField("level", infologger.IL_Devel).
Debug("envman write lock")
the.EventWriterWithTopic(topic.Environment).WriteEvent(&evpb.Ev_EnvironmentEvent{
EnvironmentId: environmentId.String(),
State: "DONE",
Transition: "DESTROY",
TransitionStep: "after_DESTROY",
TransitionStatus: evpb.OpStatus_DONE_OK,
Message: "environment teardown complete",
LastRequestUser: env.GetLastRequestUser(),
WorkflowTemplateInfo: env.GetWorkflowInfo(),
})
log.WithFields(logrus.Fields{
"partition": environmentId.String(),
infologger.Level: infologger.IL_Ops,
}).Info("environment teardown complete")
return err
}
func (envs *Manager) cancelCallsPendingAwait(env *Environment) {
// unblock all calls which are stuck waiting for an await trigger which never happened
if env == nil {
return
}
for _, callMapForAwait := range env.callsPendingAwait {
for _, callsForWeight := range callMapForAwait {
for _, call := range callsForWeight {
if call != nil {
call.Cancel()
}
}
}
}
}
/*func (envs *Manager) Configuration(environmentId uuid.UUID) EnvironmentCfg {
envs.mu.RLock()
defer envs.mu.RUnlock()
return envs.m[environmentId.Array()].cfg
}*/
func (envs *Manager) Ids() (keys []uid.ID) {
envs.mu.RLock()
defer envs.mu.RUnlock()
keys = make([]uid.ID, len(envs.m))
i := 0
for k := range envs.m {
keys[i] = k
i++
}
return
}
func (envs *Manager) Environment(environmentId uid.ID) (env *Environment, err error) {
return envs.environment(environmentId)
}
func (envs *Manager) environment(environmentId uid.ID) (env *Environment, err error) {
if len(environmentId) == 0 { // invalid id
return nil, fmt.Errorf("empty env ID")