/
helpers.go
183 lines (161 loc) · 4.9 KB
/
helpers.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
/*
* Copyright 2018-2022, CS Systemes d'Information, http://csgroup.eu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package concurrency
import (
"fmt"
"math"
mrand "math/rand"
"sync"
"time"
"github.com/CS-SI/SafeScale/v21/lib/utils/fail"
"golang.org/x/exp/rand"
)
// waitTimeout waits for the WaitGroup for the specified max timeout.
// Returns true if waiting timed out.
func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
c := make(chan struct{})
go func() {
var crash error
defer fail.OnPanic(&crash)
defer close(c)
wg.Wait()
}()
select {
case <-c:
return false // completed normally or panic in Wait
case <-time.After(timeout):
return true // timed out
}
}
// randomInt will return a random integer between a specified range.
func randomInt(min, max int) int {
if min == max {
return min
}
return mrand.Intn(max-min) + min // nolint
}
// randomIntWithReseed restarts pseudorandom seed then returns a random integer between a specified range.
func randomIntWithReseed(min, max int) int { // nolint
if min == max {
return min
}
mrand.Seed(time.Now().UnixNano())
return mrand.Intn(max-min) + min // nolint
}
func taskgenWithCustomFunc(low int, high int, latency int, cleanfactor int, probError float32, probPanic float32, actionHandlesPanicByItself bool, custom func(chan string) error) TaskAction {
return func(t Task, parameters TaskParameters) (_ TaskResult, ferr fail.Error) {
traceR := newTracer(t, false) // change to true to display traces
type internalRes struct {
ir interface{}
err error
}
if actionHandlesPanicByItself {
defer fail.OnPanic(&ferr)
}
ctx := t.Context()
weWereAborted := false
rd := randomInt(low, high)
resch := make(chan internalRes)
go func() {
var crash error
defer func() {
if crash != nil {
resch <- internalRes{
ir: "InternalPanic",
err: fail.ConvertError(crash),
}
}
}()
defer fail.OnPanic(&crash)
iterations := int64(math.Ceil(float64(rd) / float64(latency)))
tempo := time.Duration(math.Min(float64(latency), float64(rd))) * time.Millisecond
count := int64(0)
begin := time.Now()
defer func() {
traceR.trace("low=%d, high=%d, tempo=%v, iterations=%d, took %v", low, high, tempo, iterations, time.Since(begin))
}()
wrongTest := false
realTime := time.Now()
for { // do some work, then look for aborted, again and again
if count >= iterations {
break
}
// some work
time.Sleep(tempo) // that is actually the latency between abortion and its check t.Aborted() in the line below
count++
if t.Aborted() {
// if so, we shouldn't be still running, sleep adds too much overhead
if time.Since(realTime) > time.Duration(rd+latency)*time.Millisecond {
wrongTest = true
}
traceR.trace("aborted after %d iterations (max allowed=%d)", count, iterations)
// Cleaning up first before leaving... ;)
if cleanfactor > 0 {
time.Sleep(time.Duration(randomInt(cleanfactor*low, cleanfactor*high)) * time.Millisecond)
}
weWereAborted = true
if custom != nil {
_ = custom(parameters.(chan string)) // for side-effects
}
break
}
}
// simulation of error conditions, starting by panic
coinFlip := rand.Float32() < probPanic
if coinFlip {
panic("it hurts")
}
if weWereAborted {
if wrongTest {
resch <- internalRes{
ir: "",
err: fail.AbortedError(nil, "inconsistent"),
}
return
}
resch <- internalRes{
ir: "we were killed",
err: fail.AbortedError(nil, "we were killed"),
}
return
}
if custom != nil {
_ = custom(parameters.(chan string)) // for side-effects
}
coinFlip = rand.Float32() < probError
var iErr error
if coinFlip {
iErr = fmt.Errorf("it was head")
}
resch <- internalRes{
ir: "Ahhhh",
err: fail.ConvertError(iErr),
}
return // nolint
}()
select {
case res := <-resch:
return res.ir, fail.ConvertError(res.err)
case <-time.After(time.Duration(rd-1) * time.Millisecond):
return "Ahhhh", nil
case <-ctx.Done():
return "we were killed", fail.AbortedError(nil, "we were killed")
}
}
}
func taskgen(low int, high int, latency int, cleanfactor int, probError float32, probPanic float32, actionHandlesPanicByItself bool) TaskAction {
return taskgenWithCustomFunc(low, high, latency, cleanfactor, probError, probPanic, actionHandlesPanicByItself, nil)
}