-
Notifications
You must be signed in to change notification settings - Fork 392
/
Copy pathsession.go
557 lines (457 loc) · 14.8 KB
/
session.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
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
package service
import (
"context"
"sync"
"time"
"github.com/cortezaproject/corteza-server/automation/types"
"github.com/cortezaproject/corteza-server/pkg/actionlog"
"github.com/cortezaproject/corteza-server/pkg/auth"
"github.com/cortezaproject/corteza-server/pkg/errors"
"github.com/cortezaproject/corteza-server/pkg/expr"
"github.com/cortezaproject/corteza-server/pkg/options"
"github.com/cortezaproject/corteza-server/pkg/sentry"
"github.com/cortezaproject/corteza-server/pkg/wfexec"
"github.com/cortezaproject/corteza-server/store"
"go.uber.org/zap"
)
type (
promptSender interface {
Send(kind string, payload interface{}, userIDs ...uint64) error
}
session struct {
store store.Storer
actionlog actionlog.Recorder
ac sessionAccessController
opt options.WorkflowOpt
log *zap.Logger
mux sync.RWMutex
pool map[uint64]*types.Session
spawnQueue chan *spawn
promptSender promptSender
}
spawn struct {
workflowID uint64
session chan *wfexec.Session
graph *wfexec.Graph
invoker auth.Identifiable
runner auth.Identifiable
trace bool
callStack []uint64
}
sessionAccessController interface {
CanSearchSessions(context.Context) bool
CanManageSessionsOnWorkflow(context.Context, *types.Workflow) bool
}
WaitFn func(ctx context.Context) (*expr.Vars, uint64, wfexec.SessionStatus, types.Stacktrace, error)
)
const (
// when the state changes, state-change-handler is called and for non-fatal,
// non-interactive or non-delay steps (that are much more frequent) we need
// to limit how often the store is updated with the updated session info
//
// We use the size of the stacktrace and for every F (see the value of the constant)
// we flush the session info to the store.
sessionStateFlushFrequency = 1000
)
func Session(log *zap.Logger, opt options.WorkflowOpt, ps promptSender) *session {
return &session{
log: log,
opt: opt,
actionlog: DefaultActionlog,
store: DefaultStore,
ac: DefaultAccessControl,
pool: make(map[uint64]*types.Session),
spawnQueue: make(chan *spawn),
promptSender: ps,
}
}
func (svc *session) Search(ctx context.Context, filter types.SessionFilter) (rr types.SessionSet, f types.SessionFilter, err error) {
var (
sap = &sessionActionProps{filter: &filter}
)
err = func() (err error) {
if !svc.ac.CanSearchSessions(ctx) {
return SessionErrNotAllowedToSearch()
}
if rr, f, err = store.SearchAutomationSessions(ctx, svc.store, filter); err != nil {
return err
}
return nil
}()
return rr, f, svc.recordAction(ctx, sap, SessionActionSearch, err)
}
func (svc *session) LookupByID(ctx context.Context, sessionID uint64) (res *types.Session, err error) {
var (
sap = &sessionActionProps{session: &types.Session{ID: sessionID}}
wf *types.Workflow
)
err = store.Tx(ctx, svc.store, func(ctx context.Context, s store.Storer) error {
if !svc.ac.CanSearchSessions(ctx) {
return SessionErrNotAllowedToRead()
}
if res, err = loadSession(ctx, s, sessionID); err != nil {
return err
}
if wf, err = loadWorkflow(ctx, s, res.WorkflowID); err != nil {
return err
}
if !svc.ac.CanManageSessionsOnWorkflow(ctx, wf) {
return SessionErrNotAllowedToManage()
}
return nil
})
return res, svc.recordAction(ctx, sap, SessionActionLookup, err)
}
func (svc *session) resumeAll(ctx context.Context) error {
// In theory we could resume active/pending/prompt sessions from persistent store
// so that they can survive server termination
// @todo resume active sessions from storage
// load all active sessions from store and load them into the pool
//
return nil
}
func (svc *session) suspendAll(ctx context.Context) error {
// In theory we could suspend active/pending/prompt sessions to persistent store
// so that they can survive server termination
// @todo suspend active sessions to storage:
// stop watcher queue
// run gc
// stop worker on each session
// flush session to store (like we're doing in the status handler
return nil
}
// PendingPrompts returns all prompts on all sessions owned by current user
func (svc *session) PendingPrompts(ctx context.Context) (pp []*wfexec.PendingPrompt) {
var (
i = auth.GetIdentityFromContext(ctx)
)
if i == nil {
return
}
svc.mux.RLock()
defer svc.mux.RUnlock()
pp = make([]*wfexec.PendingPrompt, 0, len(svc.pool))
for _, s := range svc.pool {
pp = append(pp, s.PendingPrompts(i.Identity())...)
}
return
}
// Start new workflow session on a specific step with a given identity and scope
//
// Start is an asynchronous operation
//
// Please note that context passed to the function is NOT the the one that is
// used for the execution of the workflow. See watch function!
//
// It does not check user's permissions to execute workflow(s) so it should be used only when !
func (svc *session) Start(ctx context.Context, g *wfexec.Graph, ssp types.SessionStartParams) (wait WaitFn, _ uint64, err error) {
var (
start wfexec.Step
)
if g == nil {
return nil, 0, errors.InvalidData("cannot start workflow, uninitialized graph")
}
if len(ssp.CallStack) > svc.opt.CallStackSize {
return nil, 0, WorkflowErrMaximumCallStackSizeExceeded()
}
ssp.CallStack = append(ssp.CallStack, ssp.WorkflowID)
if ssp.Invoker == nil {
return nil, 0, errors.InvalidData("cannot start workflow without user")
}
if ssp.Runner == nil {
ssp.Runner = ssp.Invoker
}
if ssp.StepID == 0 {
// starting step is not explicitly set
// find orphan step
switch oo := g.Orphans(); len(oo) {
case 1:
start = oo[0]
case 0:
return nil, 0, errors.InvalidData("could not find starting step")
default:
return nil, 0, errors.InvalidData("cannot start workflow session multiple starting steps found")
}
} else if start = g.StepByID(ssp.StepID); start == nil {
return nil, 0, errors.InvalidData("trigger staring step references non-existing step")
} else if len(g.Parents(g.StepByID(ssp.StepID))) > 0 {
return nil, 0, errors.InvalidData("cannot start workflow on a step with parents")
}
var (
ses = svc.spawn(g, ssp.WorkflowID, ssp.Trace, ssp.CallStack, ssp.Runner, ssp.Invoker)
)
ses.CreatedAt = *now()
ses.CreatedBy = ssp.Invoker.Identity()
ses.Status = types.SessionStarted
ses.Apply(ssp)
_ = ssp.Input.AssignFieldValue("eventType", expr.Must(expr.NewString(ssp.EventType)))
_ = ssp.Input.AssignFieldValue("resourceType", expr.Must(expr.NewString(ssp.ResourceType)))
_ = ssp.Input.AssignFieldValue("invoker", expr.Must(expr.NewAny(ssp.Invoker)))
_ = ssp.Input.AssignFieldValue("runner", expr.Must(expr.NewAny(ssp.Runner)))
if err = ses.Exec(ctx, start, ssp.Input); err != nil {
return
}
return func(ctx context.Context) (scope *expr.Vars, sessionID uint64, status wfexec.SessionStatus, stacktrace types.Stacktrace, err error) {
sessionID = ses.ID
scope, status, stacktrace, err = ses.WaitResults(ctx)
return
}, ses.ID, nil
}
// Resume resumes suspended session/state
//
// Session can only be resumed by knowing session and state ID. Resume is an asynchronous operation
//
// There is minimum access-control deep inside wfexec.Session.Resume function
// that compares identity with state owner
func (svc *session) Resume(sessionID, stateID uint64, i auth.Identifiable, input *expr.Vars) error {
var (
ctx = auth.SetIdentityToContext(context.Background(), i)
)
svc.mux.RLock()
defer svc.mux.RUnlock()
ses := svc.pool[sessionID]
if ses == nil {
return errors.NotFound("session not found")
}
resPrompt, err := ses.Resume(ctx, stateID, input)
if err != nil {
return err
}
if err = svc.promptSender.Send("workflowSessionResumed", resPrompt, resPrompt.OwnerId); err != nil {
svc.log.Error("failed to send prompt resume status to user", zap.Error(err))
}
return nil
}
// Terminates session ID
func (svc *session) Cancel(ctx context.Context, sessionID uint64) (err error) {
svc.mux.RLock()
var (
wf *types.Workflow
ses = svc.pool[sessionID]
)
// unlock right away!
// when session is canceled, handler pick it up and
// locks it again
svc.mux.RUnlock()
if ses == nil {
return errors.NotFound("session not found or already canceled")
}
if wf, err = loadWorkflow(ctx, svc.store, ses.WorkflowID); err != nil {
return
}
if !svc.ac.CanManageSessionsOnWorkflow(ctx, wf) {
return SessionErrNotAllowedToManage()
}
ses.Cancel()
return nil
}
// spawns a new session
//
// We need initial context for the session because we want to catch all cancellations or timeouts from there
// and not from any potential HTTP requests or similar temporary context that can prematurely destroy a workflow session
func (svc *session) spawn(g *wfexec.Graph, workflowID uint64, trace bool, callStack []uint64, runner, invoker auth.Identifiable) (ses *types.Session) {
s := &spawn{
workflowID: workflowID,
session: make(chan *wfexec.Session, 1),
graph: g,
trace: trace,
callStack: callStack,
invoker: invoker,
runner: runner,
}
// Send new-session request
svc.spawnQueue <- s
// blocks until session is set
ses = types.NewSession(<-s.session)
if !svc.opt.StackTraceEnabled {
ses.DisableStacktrace()
}
svc.mux.Lock()
svc.pool[ses.ID] = ses
svc.mux.Unlock()
return ses
}
// Watch looks over session's spawn queue
func (svc *session) Watch(ctx context.Context) {
gcTicker := time.NewTicker(time.Second)
lpTicker := time.NewTicker(time.Second * 30)
go func() {
defer sentry.Recover()
defer gcTicker.Stop()
defer svc.log.Info("stopped")
for {
select {
case <-ctx.Done():
return
case s := <-svc.spawnQueue:
var execCtx = context.Background()
opts := []wfexec.SessionOpt{
wfexec.SetWorkflowID(s.workflowID),
wfexec.SetCallStack(s.callStack...),
wfexec.SetHandler(svc.stateChangeHandler(ctx)),
}
if svc.opt.ExecDebug {
log := svc.log.
Named("exec").
With(zap.Uint64("workflowID", s.workflowID)).
With(zap.Uint64("runnerID", s.runner.Identity())).
With(zap.Uint64s("runnerRoles", s.runner.Roles()))
opts = append(
opts,
wfexec.SetLogger(log),
wfexec.SetDumpStacktraceOnPanic(true),
)
}
// Encode runner into execution context
// runner is used as identity and for access control
execCtx = auth.SetIdentityToContext(execCtx, s.runner)
// Encode invoker into execution context
// invoker is used
execCtx = context.WithValue(execCtx, workflowInvokerCtxKey{}, s.invoker)
s.session <- wfexec.NewSession(execCtx, s.graph, opts...)
// case time for a pool cleanup
// @todo cleanup pool when sessions are complete
case <-gcTicker.C:
svc.gc()
case <-lpTicker.C:
svc.logPending()
}
}
// @todo serialize sessions & suspended states
//svc.suspendAll(ctx)
}()
svc.log.Debug("watcher initialized")
}
// garbage collection for stale sessions
func (svc *session) gc() {
svc.mux.Lock()
defer svc.mux.Unlock()
for _, s := range svc.pool {
if s.GC() {
delete(svc.pool, s.ID)
}
}
}
// garbage collection for stale sessions
func (svc *session) logPending() {
svc.mux.RLock()
defer svc.mux.RUnlock()
var (
total = len(svc.pool)
pending, pending1m, pending1h, pending1d int
)
for _, s := range svc.pool {
switch {
case s.CreatedAt.Sub(*now()) > time.Hour*24:
pending1d++
case s.CreatedAt.Sub(*now()) > time.Hour:
pending1h++
case s.CreatedAt.Sub(*now()) > time.Minute:
pending1m++
default:
pending++
}
}
if total > 0 {
svc.log.Info(
"workflow session garbage collector stats",
zap.Int("total", total),
zap.Int("pending", pending),
zap.Int("pending1m", pending1m),
zap.Int("pending1h", pending1h),
zap.Int("pending1d", pending1d),
)
}
}
// stateChangeHandler keeps track of session status changes and frequently stores session into db
func (svc *session) stateChangeHandler(ctx context.Context) wfexec.StateChangeHandler {
return func(i wfexec.SessionStatus, state *wfexec.State, s *wfexec.Session) {
svc.mux.Lock()
defer svc.mux.Unlock()
log := svc.log.With(
zap.Uint64("sessionID", s.ID()),
zap.Stringer("status", i),
)
ses := svc.pool[s.ID()]
if ses == nil {
log.Warn("could not find session to update")
return
}
log = log.With(zap.Uint64("workflowID", ses.WorkflowID))
log.Debug("state change handler")
var (
// By default, we want to update session when new status is prompted, delayed, completed, canceled or failed
// But if status is active, we'll flush it every X frames (sessionStateFlushFrequency)
update = true
frame *wfexec.Frame
)
if state != nil {
frame = state.MakeFrame()
// Stacktrace will be set to !nil if frame collection is needed
if len(ses.RuntimeStacktrace) > 0 {
// calculate how long it took to get to this step
frame.ElapsedTime = uint(frame.CreatedAt.Sub(ses.RuntimeStacktrace[0].CreatedAt) / time.Millisecond)
}
}
ses.AppendRuntimeStacktrace(frame)
switch i {
case wfexec.SessionPrompted:
ses.SuspendedAt = now()
ses.Status = types.SessionPrompted
// Send the pending prompts to user
if svc.promptSender != nil {
for _, pp := range s.UnsentPendingPrompts() {
// Prevent prompts from being re-sent
//
// This here collects all of the pending prompts and (re-)sends them.
// The problem occurs if you display multiple prompts in parallel --
// they get duplicated.
//
// Patching back-end with this simple fix, but we should probably
// refactor the logic that handles prompting a bit.
pp.Original.MarkSent()
if err := svc.promptSender.Send("workflowSessionPrompt", pp, pp.OwnerId); err != nil {
svc.log.Error("failed to send prompt to user", zap.Error(err))
}
}
}
case wfexec.SessionDelayed:
ses.SuspendedAt = now()
ses.Status = types.SessionSuspended
case wfexec.SessionCompleted:
ses.SuspendedAt = nil
ses.CompletedAt = now()
ses.Status = types.SessionCompleted
case wfexec.SessionFailed:
ses.SuspendedAt = nil
ses.CompletedAt = now()
if state != nil {
ses.Error = state.Error()
}
ses.Status = types.SessionFailed
case wfexec.SessionCanceled:
ses.SuspendedAt = nil
ses.CompletedAt = now()
ses.Status = types.SessionCanceled
default:
// force update on every F new frames (F=sessionStateFlushFrequency) but only when stacktrace is not nil
update = ses.RuntimeStacktrace != nil && len(ses.RuntimeStacktrace)%sessionStateFlushFrequency == 0
}
if !update {
return
}
ses.CopyRuntimeStacktrace()
if err := store.UpsertAutomationSession(ctx, svc.store, ses); err != nil {
log.Error("failed to update session", zap.Error(err))
}
}
}
func loadSession(ctx context.Context, s store.Storer, sessionID uint64) (res *types.Session, err error) {
if sessionID == 0 {
return nil, SessionErrInvalidID()
}
if res, err = store.LookupAutomationSessionByID(ctx, s, sessionID); errors.IsNotFound(err) {
return nil, SessionErrNotFound()
}
return
}