From 1363a1b2b316c87644c07a952ea52a59eb09eea2 Mon Sep 17 00:00:00 2001 From: D3Hunter Date: Sat, 25 May 2024 19:41:39 +0800 Subject: [PATCH 1/3] change --- Makefile | 6 ++ README.md | 7 ++ code/expr_rewriter.go | 69 ++++++++++++++++ code/rewriter.go | 1 + code/rewriter_test.go | 102 +++++++++++++++++++++--- examples/injectcall/inject_call.go | 35 ++++++++ examples/injectcall/inject_call_test.go | 49 ++++++++++++ failpoint.go | 38 +++++++++ failpoints.go | 45 +++++++++++ failpoints_test.go | 12 +++ go.mod | 12 ++- go.sum | 35 -------- marker.go | 6 ++ 13 files changed, 370 insertions(+), 47 deletions(-) create mode 100644 examples/injectcall/inject_call.go create mode 100644 examples/injectcall/inject_call_test.go diff --git a/Makefile b/Makefile index 5b656ef..060a530 100644 --- a/Makefile +++ b/Makefile @@ -66,3 +66,9 @@ gotest: tools/bin/gometalinter: cd tools; \ curl -L https://git.io/vp6lP | sh + +test-examples: + @ echo "----------- go test examples ---------------" + $(GO) run failpoint-ctl/main.go enable ./examples + $(GOTEST) -covermode=atomic -coverprofile=coverage.txt -coverpkg=./... -v ./examples/... + $(GO) run failpoint-ctl/main.go disable ./examples diff --git a/README.md b/README.md index b6ed271..5fea838 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ An implementation of [failpoints][failpoint] for Golang. Fail points are used to GO_FAILPOINTS="main/testPanic=return(true)" ./your-program ``` + Note: `GO_FAILPOINTS` does not work with `InjectCall` type of marker. + 6. If you use `go run` to run the test, don't forget to add the generated `binding__failpoint_binding__.go` in your command, like: ```bash @@ -137,6 +139,7 @@ An implementation of [failpoints][failpoint] for Golang. Fail points are used to - `func Inject(fpname string, fpblock func(val Value)) {}` - `func InjectContext(fpname string, ctx context.Context, fpblock func(val Value)) {}` + - `func InjectCall(fpname string, fn any) {}` - `func Break(label ...string) {}` - `func Goto(label string) {}` - `func Continue(label ...string) {}` @@ -148,6 +151,8 @@ An implementation of [failpoints][failpoint] for Golang. Fail points are used to failpoint can be enabled by export environment variables with the following patten, which is quite similar to [freebsd failpoint SYSCTL VARIABLES](https://www.freebsd.org/cgi/man.cgi?query=fail) + Note: `InjectCall` cannot be enabled by environment variables. + ```regexp [%][*][(args...)][->] ``` @@ -240,6 +245,8 @@ active in parallel tests or other cases. For example, } ``` +- You can use `failpoint.InjectCall` to inject a function call, this type of marker can only be enabled using `failpoint.EnableCall` and it must be called in the same process as the `InjectCall` call site. Using this marker, you can avoid failpoint code pollute you source code. See [examples](./examples/injectcall/inject_call.go). + - You can control a failpoint by failpoint.WithHook ```go diff --git a/code/expr_rewriter.go b/code/expr_rewriter.go index 6f592fd..0fd6a8b 100644 --- a/code/expr_rewriter.go +++ b/code/expr_rewriter.go @@ -26,6 +26,7 @@ type exprRewriter func(rewriter *Rewriter, call *ast.CallExpr) (rewritten bool, var exprRewriters = map[string]exprRewriter{ "Inject": (*Rewriter).rewriteInject, "InjectContext": (*Rewriter).rewriteInjectContext, + "InjectCall": (*Rewriter).rewriteInjectCall, "Break": (*Rewriter).rewriteBreak, "Continue": (*Rewriter).rewriteContinue, "Label": (*Rewriter).rewriteLabel, @@ -220,6 +221,74 @@ func (r *Rewriter) rewriteInjectContext(call *ast.CallExpr) (bool, ast.Stmt, err return true, stmt, nil } +func (r *Rewriter) rewriteInjectCall(call *ast.CallExpr) (bool, ast.Stmt, error) { + if len(call.Args) < 1 { + return false, nil, fmt.Errorf("failpoint.InjectCall: expect at least 1 arguments but got %v in %s", len(call.Args), r.pos(call.Pos())) + } + // First argument need not to be a string literal, any string type stuff is ok. + // Type safe is convinced by compiler. + fpname, ok := call.Args[0].(ast.Expr) + if !ok { + return false, nil, fmt.Errorf("failpoint.InjectCall: first argument expect a valid expression in %s", r.pos(call.Pos())) + } + + fpnameExtendCall := &ast.CallExpr{ + Fun: ast.NewIdent(ExtendPkgName), + Args: []ast.Expr{fpname}, + } + + // failpoint.InjectFn("name", a, b, c) + // | + // v + // if _, _err_ := failpoint.Eval(_curpkg_("name")); _err_ == nil { + // failpoint.Call(_curpkg_("name"), a, b, c) + // } + fnArgs := make([]ast.Expr, 0, len(call.Args)) + fnArgs = append(fnArgs, fpnameExtendCall) + fnArgs = append(fnArgs, call.Args[1:]...) + fnCall := &ast.ExprStmt{ + X: &ast.CallExpr{ + Fun: &ast.SelectorExpr{ + X: &ast.Ident{NamePos: call.Pos(), Name: r.failpointName}, + Sel: ast.NewIdent(callFunction), + }, + Args: fnArgs, + }, + } + ifBody := &ast.BlockStmt{ + Lbrace: call.Pos(), + List: []ast.Stmt{fnCall}, + Rbrace: call.End(), + } + + checkCall := &ast.CallExpr{ + Fun: &ast.SelectorExpr{ + X: &ast.Ident{NamePos: call.Pos(), Name: r.failpointName}, + Sel: ast.NewIdent(evalFunction), + }, + Args: []ast.Expr{fpnameExtendCall}, + } + err := ast.NewIdent("_err_") + init := &ast.AssignStmt{ + Lhs: []ast.Expr{ast.NewIdent("_"), err}, + Rhs: []ast.Expr{checkCall}, + Tok: token.DEFINE, + } + + cond := &ast.BinaryExpr{ + X: err, + Op: token.EQL, + Y: ast.NewIdent("nil"), + } + stmt := &ast.IfStmt{ + If: call.Pos(), + Init: init, + Cond: cond, + Body: ifBody, + } + return true, stmt, nil +} + func (r *Rewriter) rewriteBreak(call *ast.CallExpr) (bool, ast.Stmt, error) { if count := len(call.Args); count > 1 { return false, nil, fmt.Errorf("failpoint.Break expect 1 or 0 arguments, but got %v in %s", count, r.pos(call.Pos())) diff --git a/code/rewriter.go b/code/rewriter.go index f0bd812..0fabc5a 100644 --- a/code/rewriter.go +++ b/code/rewriter.go @@ -31,6 +31,7 @@ const ( packagePath = "github.com/pingcap/failpoint" packageName = "failpoint" evalFunction = "Eval" + callFunction = "Call" evalCtxFunction = "EvalContext" ExtendPkgName = "_curpkg_" // It is an indicator to indicate the label is converted from `failpoint.Label("...")` diff --git a/code/rewriter_test.go b/code/rewriter_test.go index 7ddb15d..a0db3f8 100644 --- a/code/rewriter_test.go +++ b/code/rewriter_test.go @@ -15,6 +15,7 @@ package code_test import ( + "fmt" "io/ioutil" "os" "path/filepath" @@ -26,12 +27,15 @@ import ( "github.com/pingcap/failpoint/code" ) +type rewriteCase struct { + filepath string + errormsg string + original string + expected string +} + func TestRewrite(t *testing.T) { - var cases = []struct { - filepath string - original string - expected string - }{ + var cases = []rewriteCase{ { filepath: "func-args-test.go", original: ` @@ -2477,11 +2481,7 @@ func unittest() { } func TestRewriteBad(t *testing.T) { - var cases = []struct { - filepath string - errormsg string - original string - }{ + var cases = []rewriteCase{ { filepath: "bad-basic-test.go", @@ -3627,3 +3627,85 @@ label: require.Equalf(t, cs.original, string(content), "%v", cs.filepath) } } + +func TestRewriteInjectCall(t *testing.T) { + cases := []rewriteCase{ + + { + filepath: "test.go", + original: ` +package rewriter_test + +import ( + "fmt" + + "github.com/pingcap/failpoint" +) + +func main() { + var ( + a int + b string + c []float64 + ) + a, b, c = 1, "hello", []float64{1.0, 2.0} + failpoint.InjectCall("test", a, b, c) +} +`, + expected: ` +package rewriter_test + +import ( + "fmt" + + "github.com/pingcap/failpoint" +) + +func main() { + var ( + a int + b string + c []float64 + ) + a, b, c = 1, "hello", []float64{1.0, 2.0} + if _, _err_ := failpoint.Eval(_curpkg_("test")); _err_ == nil { + failpoint.Call(_curpkg_("test"), a, b, c) + } +} +`, + }, + } + tempDir := t.TempDir() + for i, cs := range cases { + t.Run(fmt.Sprintf("case-%d", i), func(t *testing.T) { + caseDir := filepath.Join(tempDir, fmt.Sprintf("case-%d", i)) + require.NoError(t, os.Mkdir(caseDir, 0755)) + caseFileName := filepath.Join(caseDir, cs.filepath) + require.NoError(t, os.WriteFile(caseFileName, []byte(cs.original), 0644)) + + rewriter := code.NewRewriter(caseDir) + err := rewriter.Rewrite() + if cs.errormsg != "" { + require.Error(t, err) + require.Regexp(t, cs.errormsg, err.Error(), "%v", cs.filepath) + + content, err := os.ReadFile(caseFileName) + require.NoError(t, err) + require.Equalf(t, cs.original, string(content), "%v", cs.filepath) + } else { + require.NoError(t, err) + + content, err := os.ReadFile(caseFileName) + require.NoError(t, err) + require.Equalf(t, strings.TrimSpace(cs.expected), strings.TrimSpace(string(content)), "%v", cs.filepath) + + restorer := code.NewRestorer(caseDir) + err = restorer.Restore() + require.NoError(t, err) + content, err = os.ReadFile(caseFileName) + require.NoError(t, err) + require.Equal(t, cs.original, string(content)) + } + }) + } +} diff --git a/examples/injectcall/inject_call.go b/examples/injectcall/inject_call.go new file mode 100644 index 0000000..737fbba --- /dev/null +++ b/examples/injectcall/inject_call.go @@ -0,0 +1,35 @@ +// Copyright 2024 PingCAP, Inc. +// +// 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 injectcall + +import ( + "context" + "fmt" + + "github.com/pingcap/failpoint" +) + +func foo(ctx context.Context, count int) int { + for i := 0; i < count; i++ { + fmt.Println(i) + failpoint.InjectCall("test", ctx, i, count) + select { + case <-ctx.Done(): + return i + default: + } + } + return count +} diff --git a/examples/injectcall/inject_call_test.go b/examples/injectcall/inject_call_test.go new file mode 100644 index 0000000..fea4da3 --- /dev/null +++ b/examples/injectcall/inject_call_test.go @@ -0,0 +1,49 @@ +// Copyright 2024 PingCAP, Inc. +// +// 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 injectcall + +import ( + "context" + "testing" + + "github.com/pingcap/failpoint" + "github.com/stretchr/testify/require" +) + +func TestFoo(t *testing.T) { + ctx := context.WithValue(context.Background(), "key", "ctx-value") + ctx, cancel := context.WithCancel(ctx) + var ( + capturedCtxVal string + capturedArgCount int + ) + require.NoError(t, failpoint.EnableCall("github.com/pingcap/failpoint/examples/injectcall/test", + func(ctx context.Context, i, count int) { + if i == 5 { + cancel() + capturedCtxVal = ctx.Value("key").(string) + capturedArgCount = count + } + }, + )) + t.Cleanup(func() { + require.NoError(t, failpoint.Disable("github.com/pingcap/failpoint/examples/injectcall/test")) + }) + + loopCount := foo(ctx, 123) + require.EqualValues(t, "ctx-value", capturedCtxVal) + require.EqualValues(t, 5, loopCount) + require.EqualValues(t, 123, capturedArgCount) +} diff --git a/failpoint.go b/failpoint.go index 4a5ce26..e31182f 100644 --- a/failpoint.go +++ b/failpoint.go @@ -16,6 +16,8 @@ package failpoint import ( "context" + "fmt" + "reflect" "sync" ) @@ -41,6 +43,8 @@ type ( mu sync.RWMutex t *terms waitChan chan struct{} + // fn is the function to be called for InjectCall type failpoint. + fn *reflect.Value } ) @@ -81,6 +85,24 @@ func (fp *Failpoint) EnableWith(inTerms string, action func() error) error { return nil } +// EnableCall enables a failpoint which is a InjectCall type failpoint. +func (fp *Failpoint) EnableCall(fn any) error { + value := reflect.ValueOf(fn) + if value.Kind() != reflect.Func { + return fmt.Errorf("failpoint: not a function") + } + t, err := newTerms("return(true)", fp) + if err != nil { + return err + } + fp.mu.Lock() + fp.t = t + fp.waitChan = make(chan struct{}) + fp.fn = &value + fp.mu.Unlock() + return nil +} + // Disable stops a failpoint func (fp *Failpoint) Disable() { select { @@ -110,3 +132,19 @@ func (fp *Failpoint) Eval() (Value, error) { } return v, nil } + +// Call calls the function passed by EnableCall with args supplied in InjectCall. +func (fp *Failpoint) Call(args ...any) { + fp.mu.RLock() + fn := fp.fn + fp.mu.RUnlock() + + if fn == nil { + return + } + argVals := make([]reflect.Value, 0, len(args)) + for _, a := range args { + argVals = append(argVals, reflect.ValueOf(a)) + } + fn.Call(argVals) +} diff --git a/failpoints.go b/failpoints.go index 904bc41..bb4724a 100644 --- a/failpoints.go +++ b/failpoints.go @@ -133,6 +133,27 @@ func (fps *Failpoints) EnableWith(failpath, inTerms string, action func() error) return nil } +// EnableCall enables a failpoint which is a InjectCall type failpoint. +func (fps *Failpoints) EnableCall(failpath string, fn any) error { + fps.mu.Lock() + defer fps.mu.Unlock() + + if fps.reg == nil { + fps.reg = make(map[string]*Failpoint) + } + + fp := fps.reg[failpath] + if fp == nil { + fp = &Failpoint{} + fps.reg[failpath] = fp + } + err := fp.EnableCall(fn) + if err != nil { + return errors.Wrapf(err, "error on %s", failpath) + } + return nil +} + // Disable a failpoint on failpath func (fps *Failpoints) Disable(failpath string) error { fps.mu.Lock() @@ -214,6 +235,18 @@ func (fps *Failpoints) Eval(failpath string) (Value, error) { return val, nil } +// Call calls the function passed by EnableCall with args supplied in InjectCall. +func (fps *Failpoints) Call(failpath string, args ...any) { + fps.mu.RLock() + fp, found := fps.reg[failpath] + fps.mu.RUnlock() + if !found { + return + } + + fp.Call(args...) +} + // failpoints is the default var failpoints Failpoints @@ -230,6 +263,13 @@ func EnableWith(failpath, inTerms string, action func() error) error { return failpoints.EnableWith(failpath, inTerms, action) } +// EnableCall enables a failpoint which is a InjectCall type failpoint. +// The failpoint will call the function passed by EnableCall with args supplied in InjectCall. +// this type of failpoint does not support terms, you should control the behavior in the function. +func EnableCall(failpath string, fn any) error { + return failpoints.EnableCall(failpath, fn) +} + // Disable stops a failpoint from firing. func Disable(failpath string) error { return failpoints.Disable(failpath) @@ -274,3 +314,8 @@ func Eval(failpath string) (Value, error) { } return val, err } + +// Call calls the function passed by EnableCall with args supplied in InjectCall. +func Call(failpath string, args ...any) { + failpoints.Call(failpath, args...) +} diff --git a/failpoints_test.go b/failpoints_test.go index cdcf1aa..000fef9 100644 --- a/failpoints_test.go +++ b/failpoints_test.go @@ -228,3 +228,15 @@ func testPanic() { _ = failpoint.Enable("test-panic", `panic`) _, _ = failpoint.Eval("test-panic") } + +func TestCall(t *testing.T) { + var capturedArg int + require.NoError(t, failpoint.EnableCall("test", func(a int) { + capturedArg = a + })) + t.Cleanup(func() { + require.NoError(t, failpoint.Disable("test")) + }) + failpoint.Call("test", 123) + require.Equal(t, 123, capturedArg) +} diff --git a/go.mod b/go.mod index 0b4a5e0..b1b6207 100644 --- a/go.mod +++ b/go.mod @@ -2,11 +2,19 @@ module github.com/pingcap/failpoint require ( github.com/pingcap/errors v0.11.4 - github.com/pkg/errors v0.9.1 // indirect github.com/sergi/go-diff v1.1.0 github.com/stretchr/testify v1.7.0 go.uber.org/goleak v1.1.10 golang.org/x/mod v0.17.0 ) -go 1.13 +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/lint v0.0.0-20190930215403-16217165b5de // indirect + golang.org/x/tools v0.13.0 // indirect + gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect +) + +go 1.18 diff --git a/go.sum b/go.sum index b011b34..9faf95c 100644 --- a/go.sum +++ b/go.sum @@ -18,57 +18,22 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.uber.org/goleak v1.1.10 h1:z+mqJhf6ss6BSfSM671tgKyZBFPTTJM+HLxnhPC3wu0= go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= -golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o= -golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/marker.go b/marker.go index 640a7cb..fdb17c5 100644 --- a/marker.go +++ b/marker.go @@ -34,6 +34,12 @@ func Inject(fpname string, fpbody interface{}) {} // failpoint.InjectContext(ctx, "fail-point-name", func(_ failpoint.Value) (...){} func InjectContext(ctx context.Context, fpname string, fpbody interface{}) {} +// InjectCall marks a fail point routine, which will be rewrite to a `if` statement +// and be triggered by fail point name specified `fpname` using EnableCall. +// Note: this function can only be used when EnableCall is used in the same process +// as the InjectCall, otherwise it's a noop. +func InjectCall(fpname string, args ...any) {} + // Break will generate a break statement in a loop, e.g: // case1: // From bb473d99fc8ab53fe373e19aaa1f779820c8732a Mon Sep 17 00:00:00 2001 From: D3Hunter Date: Mon, 27 May 2024 10:39:13 +0800 Subject: [PATCH 2/3] makefile --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 060a530..9703ac2 100644 --- a/Makefile +++ b/Makefile @@ -61,7 +61,7 @@ check-static: tools/bin/gometalinter gotest: @ echo "----------- go test ---------------" - $(GOTEST) -covermode=atomic -coverprofile=coverage.txt -coverpkg=./... -v ./... + $(GOTEST) -covermode=atomic -coverprofile=coverage.txt -coverpkg=./... -v $(go list ./... | grep -v examples) tools/bin/gometalinter: cd tools; \ From 1041eff8d99eef4ae668edf347468864f4d6b45f Mon Sep 17 00:00:00 2001 From: D3Hunter Date: Mon, 27 May 2024 12:09:59 +0800 Subject: [PATCH 3/3] move eval inside to avoid line number change --- Makefile | 4 ++++ README.md | 2 +- code/expr_rewriter.go | 39 +++------------------------------------ failpoints.go | 3 +++ 4 files changed, 11 insertions(+), 37 deletions(-) diff --git a/Makefile b/Makefile index 9703ac2..22a2c1c 100644 --- a/Makefile +++ b/Makefile @@ -72,3 +72,7 @@ test-examples: $(GO) run failpoint-ctl/main.go enable ./examples $(GOTEST) -covermode=atomic -coverprofile=coverage.txt -coverpkg=./... -v ./examples/... $(GO) run failpoint-ctl/main.go disable ./examples + +test-examples-toolexec: build + @ echo "----------- go test examples using toolexec ---------------" + GOCACHE=/tmp/failpoint-cache $(GOTEST) -covermode=atomic -coverprofile=coverage.txt -coverpkg=./... -toolexec="$(PWD)/bin/failpoint-toolexec" -v ./examples/... diff --git a/README.md b/README.md index 5fea838..95046e4 100644 --- a/README.md +++ b/README.md @@ -139,7 +139,7 @@ An implementation of [failpoints][failpoint] for Golang. Fail points are used to - `func Inject(fpname string, fpblock func(val Value)) {}` - `func InjectContext(fpname string, ctx context.Context, fpblock func(val Value)) {}` - - `func InjectCall(fpname string, fn any) {}` + - `func InjectCall(fpname string, args ...any) {}` - `func Break(label ...string) {}` - `func Goto(label string) {}` - `func Continue(label ...string) {}` diff --git a/code/expr_rewriter.go b/code/expr_rewriter.go index 0fd6a8b..fd540e3 100644 --- a/code/expr_rewriter.go +++ b/code/expr_rewriter.go @@ -237,12 +237,10 @@ func (r *Rewriter) rewriteInjectCall(call *ast.CallExpr) (bool, ast.Stmt, error) Args: []ast.Expr{fpname}, } - // failpoint.InjectFn("name", a, b, c) + // failpoint.InjectCall("name", a, b, c) // | // v - // if _, _err_ := failpoint.Eval(_curpkg_("name")); _err_ == nil { - // failpoint.Call(_curpkg_("name"), a, b, c) - // } + // failpoint.Call(_curpkg_("name"), a, b, c) fnArgs := make([]ast.Expr, 0, len(call.Args)) fnArgs = append(fnArgs, fpnameExtendCall) fnArgs = append(fnArgs, call.Args[1:]...) @@ -255,38 +253,7 @@ func (r *Rewriter) rewriteInjectCall(call *ast.CallExpr) (bool, ast.Stmt, error) Args: fnArgs, }, } - ifBody := &ast.BlockStmt{ - Lbrace: call.Pos(), - List: []ast.Stmt{fnCall}, - Rbrace: call.End(), - } - - checkCall := &ast.CallExpr{ - Fun: &ast.SelectorExpr{ - X: &ast.Ident{NamePos: call.Pos(), Name: r.failpointName}, - Sel: ast.NewIdent(evalFunction), - }, - Args: []ast.Expr{fpnameExtendCall}, - } - err := ast.NewIdent("_err_") - init := &ast.AssignStmt{ - Lhs: []ast.Expr{ast.NewIdent("_"), err}, - Rhs: []ast.Expr{checkCall}, - Tok: token.DEFINE, - } - - cond := &ast.BinaryExpr{ - X: err, - Op: token.EQL, - Y: ast.NewIdent("nil"), - } - stmt := &ast.IfStmt{ - If: call.Pos(), - Init: init, - Cond: cond, - Body: ifBody, - } - return true, stmt, nil + return true, fnCall, nil } func (r *Rewriter) rewriteBreak(call *ast.CallExpr) (bool, ast.Stmt, error) { diff --git a/failpoints.go b/failpoints.go index bb4724a..3ebc4f4 100644 --- a/failpoints.go +++ b/failpoints.go @@ -317,5 +317,8 @@ func Eval(failpath string) (Value, error) { // Call calls the function passed by EnableCall with args supplied in InjectCall. func Call(failpath string, args ...any) { + if _, err := failpoints.Eval(failpath); err != nil { + return + } failpoints.Call(failpath, args...) }