-
Notifications
You must be signed in to change notification settings - Fork 23
/
environment.go
462 lines (414 loc) · 11.9 KB
/
environment.go
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
/*
* === This file is part of ALICE O² ===
*
* Copyright 2017-2018 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 defines Environment, environment.Manager and
// other types and methods related to handling O² environments.
package environment
import (
"errors"
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/AliceO2Group/Control/common/event"
"github.com/AliceO2Group/Control/common/gera"
"github.com/AliceO2Group/Control/common/logger"
"github.com/AliceO2Group/Control/common/utils/uid"
"github.com/AliceO2Group/Control/core/task"
"github.com/AliceO2Group/Control/core/the"
"github.com/AliceO2Group/Control/core/workflow"
"github.com/gobwas/glob"
"github.com/looplab/fsm"
"github.com/pborman/uuid"
"github.com/sirupsen/logrus"
)
var log = logger.New(logrus.StandardLogger(),"env")
type Environment struct {
Mu sync.RWMutex
once sync.Once
Sm *fsm.FSM
name string
id uid.ID
ts time.Time
workflow workflow.Role
wfAdapter *workflow.ParentAdapter
currentRunNumber uint32
hookHandlerF func(hooks task.Tasks) error
incomingEvents chan event.DeviceEvent
GlobalDefaults gera.StringMap // From Consul
GlobalVars gera.StringMap // From Consul
UserVars gera.StringMap // From user input
stateChangedCh chan *event.TasksStateChangedEvent
unsubscribe chan struct{}
eventStream Subscription
}
func (env *Environment) NotifyEvent(e event.DeviceEvent) {
if e != nil && env.incomingEvents != nil {
select {
case env.incomingEvents <- e:
default:
}
}
}
func newEnvironment(userVars map[string]string) (env *Environment, err error) {
envId := uid.New()
env = &Environment{
id: envId,
workflow: nil,
ts: time.Now(),
incomingEvents: make(chan event.DeviceEvent),
// Every Environment instantiation performs a ConfSvc query for defaults and vars
// these key-values stay frozen throughout the lifetime of the environment
GlobalDefaults: gera.MakeStringMapWithMap(the.ConfSvc().GetDefaults()),
GlobalVars: gera.MakeStringMapWithMap(the.ConfSvc().GetVars()),
UserVars: gera.MakeStringMapWithMap(userVars),
stateChangedCh: make(chan *event.TasksStateChangedEvent),
}
// Make the KVs accessible to the workflow via ParentAdapter
env.wfAdapter = workflow.NewParentAdapter(
func() uid.ID { return env.Id() },
func() uint32 { return env.GetCurrentRunNumber() },
func() gera.StringMap { return env.GlobalDefaults },
func() gera.StringMap { return env.GlobalVars },
func() gera.StringMap { return env.UserVars },
func(ev event.Event) {
if env.eventStream != nil{
env.eventStream.Send(ev)
}},
)
env.Sm = fsm.NewFSM(
"STANDBY",
fsm.Events{
{Name: "CONFIGURE", Src: []string{"STANDBY"}, Dst: "CONFIGURED"},
{Name: "RESET", Src: []string{"CONFIGURED"}, Dst: "STANDBY"},
{Name: "START_ACTIVITY", Src: []string{"CONFIGURED"}, Dst: "RUNNING"},
{Name: "STOP_ACTIVITY", Src: []string{"RUNNING"}, Dst: "CONFIGURED"},
{Name: "EXIT", Src: []string{"CONFIGURED", "STANDBY"}, Dst: "DONE"},
{Name: "GO_ERROR", Src: []string{"CONFIGURED", "RUNNING"}, Dst: "ERROR"},
{Name: "RECOVER", Src: []string{"ERROR"}, Dst: "STANDBY"},
},
fsm.Callbacks{
"before_event": func(e *fsm.Event) {
errHooks := env.handleHooks(env.Workflow(), fmt.Sprintf("before_%s", e.Event))
if errHooks != nil {
e.Cancel(errHooks)
}
},
"leave_state": func(e *fsm.Event) {
errHooks := env.handleHooks(env.Workflow(), fmt.Sprintf("leave_%s", e.Src))
if errHooks != nil {
e.Cancel(errHooks)
return
}
env.handlerFunc()(e)
},
"enter_state": func(e *fsm.Event) {
errHooks := env.handleHooks(env.Workflow(), fmt.Sprintf("enter_%s", e.Dst))
if errHooks != nil {
e.Cancel(errHooks)
return
}
log.WithFields(logrus.Fields{
"event": e.Event,
"src": e.Src,
"dst": e.Dst,
"partition": envId,
}).Debug("environment.sm entering state")
},
"after_event": func(e *fsm.Event) {
errHooks := env.handleHooks(env.Workflow(), fmt.Sprintf("after_%s", e.Event))
if errHooks != nil {
e.Cancel(errHooks)
}
},
},
)
return
}
func (env *Environment) handleHooks(workflow workflow.Role, trigger string) (err error) {
allHooks := workflow.GetHooksForTrigger(trigger)
allHooks.FilterCalls().CallAll()
hooksToTrigger := allHooks.FilterTasks()
if len(hooksToTrigger) == 0 {
return nil
}
err = env.hookHandlerF(hooksToTrigger)
if err != nil {
return
}
timeoutCh := make(chan *task.Task)
hookTimers := make(map[*task.Task]*time.Timer)
for _, hook := range hooksToTrigger {
timeout, _ := time.ParseDuration(hook.GetTraits().Timeout)
hookTimers[hook] = time.AfterFunc(timeout,
func() {
thisHook := hook
timeoutCh <- thisHook
})
}
successfulHooks := make(task.Tasks, 0)
failedHooksById := make(map[string]*task.Task)
for {
select {
case e := <- env.incomingEvents:
switch evt := e.(type) {
case *event.BasicTaskTerminated:
tid := evt.GetOrigin().TaskId
thisHook := hooksToTrigger.GetByTaskId(tid.Value)
if thisHook == nil {
continue
}
hookTimers[thisHook].Stop()
delete(hookTimers, thisHook)
if evt.ExitCode != 0 || !evt.VoluntaryTermination {
failedHooksById[thisHook.GetTaskId()] = thisHook
log.WithField("task", thisHook.GetName()).
WithFields(logrus.Fields{
"exitCode": evt.ExitCode,
"stdout": evt.Stdout,
"stderr": evt.Stderr,
"partition": env.Id().String(),
"finalMesosState": evt.FinalMesosState.String(),
}).
Warn("hook failed")
} else {
successfulHooks = append(successfulHooks, thisHook)
log.WithField("partition", env.Id().String()).
WithField("task", thisHook.GetName()).Trace("hook completed")
}
default:
continue
}
case thisHook := <- timeoutCh:
log.WithField("partition", env.Id().String()).
WithField("task", thisHook.GetName()).Warn("hook response timed out")
delete(hookTimers, thisHook)
failedHooksById[thisHook.GetTaskId()] = thisHook
}
if len(hookTimers) == 0 {
break
}
}
if len(hooksToTrigger) == len(successfulHooks) {
err = nil
return
}
// We only report non-nil error if at least one CRITICAL HOOK failed
failedCriticalHookNames := make([]string, 0)
for _, thisHook := range failedHooksById {
if thisHook.GetTraits().Critical {
failedCriticalHookNames = append(failedCriticalHookNames, thisHook.GetParentRolePath())
}
}
sort.Strings(failedCriticalHookNames)
if len(failedCriticalHookNames) > 0 {
err = fmt.Errorf("%d critical hooks failed: %s",
len(failedCriticalHookNames),
strings.Join(failedCriticalHookNames, ", "))
}
return
}
func (env *Environment) TryTransition(t Transition) (err error) {
err = t.check()
if err != nil {
return
}
err = env.Sm.Event(t.eventName(), t)
return
}
func (env *Environment) handlerFunc() func(e *fsm.Event) {
if env == nil {
return nil
}
return func(e *fsm.Event) {
if e.Err != nil { // If the event was already cancelled
return
}
log.WithFields(logrus.Fields{
"event": e.Event,
"src": e.Src,
"dst": e.Dst,
"partition": env.id.String(),
}).Debug("environment.sm starting transition")
transition, ok := e.Args[0].(Transition)
if !ok {
e.Cancel(errors.New("transition wrapping error"))
return
}
if transition.eventName() == e.Event {
transErr := transition.do(env)
if transErr != nil {
e.Cancel(transErr)
}
}
}
}
// Accessors
func (env *Environment) Id() uid.ID {
if env == nil {
return uid.NilID()
}
env.Mu.RLock()
defer env.Mu.RUnlock()
return env.id
}
func (env *Environment) CreatedWhen() time.Time {
if env == nil {
return time.Unix(0,0)
}
env.Mu.RLock()
defer env.Mu.RUnlock()
return env.ts
}
func (env *Environment) CurrentState() string {
if env == nil {
return ""
}
env.Mu.RLock()
defer env.Mu.RUnlock()
return env.Sm.Current()
}
func (env *Environment) IsSafeToStop() bool {
tasks := env.Workflow().GetTasks()
for _, t := range tasks {
if !t.IsSafeToStop() {
return false
}
}
return true
}
func (env *Environment) Workflow() workflow.Role {
if env == nil {
return nil
}
env.Mu.RLock()
defer env.Mu.RUnlock()
return env.workflow
}
func (env *Environment) QueryRoles(pathSpec string) (rs []workflow.Role) {
env.Mu.RLock()
defer env.Mu.RUnlock()
g := glob.MustCompile(pathSpec, workflow.PATH_SEPARATOR_RUNE)
rs = env.workflow.GlobFilter(g)
return
}
func (env *Environment) GetPath() string {
return ""
}
func (env *Environment) GetCurrentRunNumber() (rn uint32) {
env.Mu.RLock()
defer env.Mu.RUnlock()
if env.Sm.Current() != "RUNNING" {
return 0
}
return env.currentRunNumber
}
// setState will move environment to a given state from current state.
// The call does not trigger any callbacks, if defined.
func (env *Environment) setState(state string) {
if env == nil {
return
}
env.Mu.Lock()
defer env.Mu.Unlock()
env.Sm.SetState(state)
}
func (env *Environment) subscribeToWfState(taskman *task.Manager) {
go func() {
wf := env.Workflow()
notify := make(chan task.State)
subscriptionId := uuid.NewUUID().String()
env.wfAdapter.SubscribeToStateChange(subscriptionId, notify)
defer env.wfAdapter.UnsubscribeFromStateChange(subscriptionId)
env.unsubscribe = make(chan struct{})
wfState := wf.GetState()
if wfState != task.ERROR {
WORKFLOW_STATE_LOOP:
for {
select {
case wfState = <-notify:
if wfState == task.ERROR {
env.setState(wfState.String())
toStop := env.Workflow().GetTasks().Filtered(func(t *task.Task) bool {
t.SetSafeToStop(true)
return t.IsSafeToStop()
})
if len(toStop) > 0 {
taskmanMessage := task.NewTransitionTaskMessage(
toStop,
task.RUNNING.String(),
task.STOP.String(),
task.CONFIGURED.String(),
nil,
env.Id(),
)
taskman.MessageChannel <- taskmanMessage
<-env.stateChangedCh
}
break WORKFLOW_STATE_LOOP
}
if wfState == task.DONE {
break WORKFLOW_STATE_LOOP
}
case <- env.unsubscribe:
break WORKFLOW_STATE_LOOP
}
}
}
}()
}
func (env *Environment) unsubscribeFromWfState() {
// Use select to unblock in case the above goroutine
// exits due to an ERROR state. If that's the case
// we close the channel.
env.once.Do(func() {
select {
case env.unsubscribe <- struct{}{}:
default:
if env.unsubscribe != nil {
close(env.unsubscribe)
}
}
})
}
func (env *Environment) addSubscription(sub Subscription) {
env.Mu.Lock()
env.eventStream = sub
env.Mu.Unlock()
}
func (env *Environment) sendEnvironmentEvent(ev event.Event) {
env.Mu.Lock()
if env.eventStream != nil {
env.eventStream.Send(ev)
}
env.Mu.Unlock()
}
func (env *Environment) closeStream() {
env.Mu.Lock()
if env.eventStream != nil {
env.eventStream.Unsubscribe()
env.eventStream = nil
}
env.Mu.Unlock()
}