-
Notifications
You must be signed in to change notification settings - Fork 8
/
monitoring.go
82 lines (71 loc) · 2.13 KB
/
monitoring.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
/*
* Copyright (C) 2020-2022 Arm Limited or its affiliates and Contributors. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package subprocess
import (
"context"
"time"
"go.uber.org/atomic"
"github.com/ARM-software/golang-utils/utils/parallelisation"
)
// INTERNAL
// Object in charge of monitoring subprocesses.
type subprocessMonitoring struct {
cancelStore *parallelisation.CancelFunctionStore
parentCtx context.Context
cancellableCtx atomic.Value
monitoringOn atomic.Bool
monitoringStopping atomic.Bool
}
func newSubprocessMonitoring(parentCtx context.Context) *subprocessMonitoring {
m := &subprocessMonitoring{
cancelStore: parallelisation.NewCancelFunctionsStore(),
parentCtx: parentCtx,
}
m.Reset()
return m
}
// CancelSubprocess interrupts an on-going process.
func (s *subprocessMonitoring) CancelSubprocess() {
s.monitoringStopping.Store(true)
s.cancelStore.Cancel()
}
func (s *subprocessMonitoring) RunMonitoring(stopProcess func() error) {
timeoutCtx, cancel := context.WithTimeout(s.parentCtx, time.Second)
defer cancel()
for s.IsOn() {
// if monitoring is already on, either wait until it is stopped to relaunch it or do not do anything
if !s.monitoringStopping.Load() {
return
}
parallelisation.SleepWithContext(timeoutCtx, time.Millisecond)
err := parallelisation.DetermineContextError(timeoutCtx)
if err != nil {
return
}
}
s.Reset()
s.runProcessMonitoring(stopProcess)
}
func (s *subprocessMonitoring) Reset() {
s.monitoringStopping.Store(false)
subctx, cancelFunc := context.WithCancel(s.parentCtx)
s.cancellableCtx.Store(subctx)
s.cancelStore.RegisterCancelFunction(cancelFunc)
}
func (s *subprocessMonitoring) IsOn() bool {
return s.monitoringOn.Load()
}
func (s *subprocessMonitoring) ProcessContext() context.Context {
return s.cancellableCtx.Load().(context.Context)
}
func (s *subprocessMonitoring) runProcessMonitoring(stopProcess func() error) {
go func(m *subprocessMonitoring, stop func() error) {
m.monitoringOn.Store(true)
<-s.ProcessContext().Done()
m.CancelSubprocess()
_ = stop()
m.monitoringOn.Store(false)
}(s, stopProcess)
}