blob: ea8db3fc016ed6f53ec890e223e96c54750187fa [file] [log] [blame]
Abhay Kumara61c5222025-11-10 07:32:50 +00001// Copyright 2016 CoreOS, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package runtime
16
17import (
18 "fmt"
19 "sync"
20)
21
22type Failpoint struct {
23 t *terms
24 mux sync.RWMutex
25}
26
27func NewFailpoint(name string) *Failpoint {
28 return register(name)
29}
30
31// Acquire gets evalutes the failpoint terms; if the failpoint
32// is active, it will return a value. Otherwise, returns a non-nil error.
33//
34// Notice that during the exection of Acquire(), the failpoint can be disabled,
35// but the already in-flight execution won't be terminated
36func (fp *Failpoint) Acquire() (interface{}, error) {
37 fp.mux.RLock()
38 // terms are locked during execution, so deepcopy is not required as no change can be made during execution
39 cachedT := fp.t
40 fp.mux.RUnlock()
41
42 if cachedT == nil {
43 return nil, ErrDisabled
44 }
45 result := cachedT.eval()
46 if result == nil {
47 return nil, ErrDisabled
48 }
49 return result, nil
50}
51
52// BadType is called when the failpoint evaluates to the wrong type.
53func (fp *Failpoint) BadType(v interface{}, t string) {
54 fmt.Printf("failpoint: %q got value %v of type \"%T\" but expected type %q\n", fp.t.fpath, v, v, t)
55}
56
57func (fp *Failpoint) SetTerm(t *terms) {
58 fp.mux.Lock()
59 defer fp.mux.Unlock()
60
61 fp.t = t
62}
63
64func (fp *Failpoint) ClearTerm() error {
65 fp.mux.Lock()
66 defer fp.mux.Unlock()
67
68 if fp.t == nil {
69 return ErrDisabled
70 }
71 fp.t = nil
72
73 return nil
74}
75
76func (fp *Failpoint) Status() (string, int, error) {
77 fp.mux.RLock()
78 defer fp.mux.RUnlock()
79
80 t := fp.t
81 if t == nil {
82 return "", 0, ErrDisabled
83 }
84
85 return t.desc, t.counter, nil
86}