pax_global_header 0000666 0000000 0000000 00000000064 14344734771 0014530 g ustar 00root root 0000000 0000000 52 comment=6c4b158c4acd3937e13a6c45134530a525c3ccf7
gofail-0.1.0/ 0000775 0000000 0000000 00000000000 14344734771 0012767 5 ustar 00root root 0000000 0000000 gofail-0.1.0/.github/ 0000775 0000000 0000000 00000000000 14344734771 0014327 5 ustar 00root root 0000000 0000000 gofail-0.1.0/.github/workflows/ 0000775 0000000 0000000 00000000000 14344734771 0016364 5 ustar 00root root 0000000 0000000 gofail-0.1.0/.github/workflows/golangci-lint.yml 0000664 0000000 0000000 00000002646 14344734771 0021646 0 ustar 00root root 0000000 0000000 name: golangci-lint
on:
push:
tags:
- v*
branches:
- master
- main
pull_request:
permissions:
contents: read
# Optional: allow read access to pull request. Use with `only-new-issues` option.
# pull-requests: read
jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/setup-go@v3
with:
go-version: 1.17
- uses: actions/checkout@v3
- name: golangci-lint
uses: golangci/golangci-lint-action@v3
with:
# Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
version: v1.29
# Optional: working directory, useful for monorepos
# working-directory: somedir
# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0
# Optional: show only new issues if it's a pull request. The default value is `false`.
# only-new-issues: true
# Optional: if set to true then the all caching functionality will be complete disabled,
# takes precedence over all other caching options.
# skip-cache: true
# Optional: if set to true then the action don't cache or restore ~/go/pkg.
# skip-pkg-cache: true
# Optional: if set to true then the action don't cache or restore ~/.cache/go-build.
# skip-build-cache: true
gofail-0.1.0/.github/workflows/tests.yml 0000664 0000000 0000000 00000000731 14344734771 0020252 0 ustar 00root root 0000000 0000000 name: tests
on:
push:
tags:
- v*
branches:
- master
- main
pull_request:
permissions:
contents: read
# Optional: allow read access to pull request. Use with `only-new-issues` option.
# pull-requests: read
jobs:
test:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/setup-go@v3
with:
go-version: 1.17
- uses: actions/checkout@v3
- name: tests
run: |
make test
gofail-0.1.0/.gitignore 0000664 0000000 0000000 00000000027 14344734771 0014756 0 ustar 00root root 0000000 0000000 .idea
.DS_Store
gofail
gofail-0.1.0/.golangci.yaml 0000664 0000000 0000000 00000001754 14344734771 0015523 0 ustar 00root root 0000000 0000000 run:
go: '1.17'
timeout: 30m
skip-files:
- "^zz_generated.*"
issues:
max-same-issues: 0
# Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules:
# exclude ineffassing linter for generated files for conversion
- path: conversion\.go
linters:
- ineffassign
linters:
disable-all: true
enable: # please keep this alphabetized
# Don't use soon to deprecated[1] linters that lead to false
# https://github.com/golangci/golangci-lint/issues/1841
# - deadcode
# - structcheck
# - varcheck
- ineffassign
- staticcheck
- stylecheck
- unused
linters-settings: # please keep this alphabetized
staticcheck:
checks:
- "all"
- "-SA1019" # TODO(fix) Using a deprecated function, variable, constant or field
- "-SA2002" # TODO(fix) Called testing.T.FailNow or SkipNow in a goroutine, which isn’t allowed
stylecheck:
checks:
- "ST1019" # Importing the same package multiple times.
gofail-0.1.0/CHANGELOG.md 0000664 0000000 0000000 00000001106 14344734771 0014576 0 ustar 00root root 0000000 0000000 Note that we start to track changes starting from 2022.
## v0.2.0 (TBD)
## v0.1.0 (2022-12-10)
- [Removed gofail-go failpoint](https://github.com/etcd-io/gofail/pull/30).
- [Enhanced the continuous integration pipeline](https://github.com/etcd-io/gofail/pull/24).
- [Added go.mod and set the module name as go.etcd.io/gofail](https://github.com/etcd-io/gofail/pull/21).
- [Added support for dynamically setting multiple failpoints](https://github.com/etcd-io/gofail/pull/38).
- [Removed package path from each failpoint](https://github.com/etcd-io/gofail/pull/44).
gofail-0.1.0/DCO 0000664 0000000 0000000 00000002616 14344734771 0013324 0 ustar 00root root 0000000 0000000 Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
gofail-0.1.0/LICENSE 0000664 0000000 0000000 00000026136 14344734771 0014004 0 ustar 00root root 0000000 0000000
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
gofail-0.1.0/Makefile 0000664 0000000 0000000 00000000440 14344734771 0014425 0 ustar 00root root 0000000 0000000 SRCS=$(filter-out %_test.go, $(wildcard *.go */*.go))
.PHONY: all
all: gofail
.PHONY: clean
clean:
rm -f gofail
.PHONY: test
test:
go test -v --race -cpu=1,2,4 ./code/ ./runtime/
.PHONY: fmt
fmt:
gofmt -w -l -s $(SRCS)
gofail:
GO_BUILD_FLAGS="-v" ./build.sh
./gofail --version
gofail-0.1.0/NOTICE 0000664 0000000 0000000 00000000176 14344734771 0013677 0 ustar 00root root 0000000 0000000 CoreOS Project
Copyright 2018 CoreOS, Inc
This product includes software developed at CoreOS, Inc.
(http://www.coreos.com/).
gofail-0.1.0/README.md 0000664 0000000 0000000 00000004743 14344734771 0014256 0 ustar 00root root 0000000 0000000 # gofail
[](https://travis-ci.com/etcd-io/gofail)
An implementation of [failpoints][failpoint] for golang. Please read [design.md](doc/design.md) for a deeper understanding.
[failpoint]: http://www.freebsd.org/cgi/man.cgi?query=fail
## Add a failpoint
Failpoints are special comments that include a failpoint variable declaration and some trigger code,
```go
func someFunc() string {
// gofail: var SomeFuncString string
// // this is called when the failpoint is triggered
// return SomeFuncString
return "default"
}
```
## Build with failpoints
Building with failpoints will translate gofail comments in place to code that accesses the gofail runtime.
Call gofail in the directory with failpoints to generate gofail runtime bindings, then build as usual,
```sh
gofail enable
go build cmd/
```
The translated code looks something like,
```go
func someFunc() string {
if vSomeFuncString, __fpErr := __fp_SomeFuncString.Acquire(); __fpErr == nil { SomeFuncString, __fpTypeOK := vSomeFuncString.(string); if !__fpTypeOK { goto __badTypeSomeFuncString}
// this is called when the failpoint is triggered
return SomeFuncString; __badTypeSomeFuncString: __fp_SomeFuncString.BadType(vSomeFuncString, "string"); };
return "default"
}
```
To disable failpoints and revert to the original code,
```sh
gofail disable
```
## Triggering a failpoint
After building with failpoints enabled, the program's failpoints can be activated so they may trigger when evaluated.
### Command line
From the command line, trigger the failpoint to set SomeFuncString to `hello`,
```sh
GOFAIL_FAILPOINTS='SomeFuncString=return("hello")' ./cmd
```
Multiple failpoints are set by using ';' for a delimiter,
```sh
GOFAIL_FAILPOINTS='failpoint1=return("hello");failpoint2=sleep(10)' ./cmd
```
### HTTP endpoint
First, enable the HTTP server from the command line,
```sh
GOFAIL_HTTP="127.0.0.1:1234" ./cmd
```
Activate a failpoint with curl,
```sh
$ curl http://127.0.0.1:1234/SomeFuncString -XPUT -d'return("hello")'
```
List the failpoints,
```sh
$ curl http://127.0.0.1:1234/SomeFuncString=return("hello")
```
Deactivate a failpoint,
```sh
$ curl http://127.0.0.1:1234/SomeFuncString -XDELETE
```
### Unit tests
From a unit test,
```go
import (
"testing"
gofail "go.etcd.io/gofail/runtime"
)
func TestWhatever(t *testing.T) {
gofail.Enable("SomeFuncString", `return("hello")`)
defer gofail.Disable("SomeFuncString")
...
}
```
gofail-0.1.0/build.sh 0000775 0000000 0000000 00000000371 14344734771 0014426 0 ustar 00root root 0000000 0000000 #!/usr/bin/env bash
GIT_SHA=$(git rev-parse --short HEAD || echo "GitNotFound")
# Set GO_LDFLAGS="-s" for building without symbols for debugging.
GO_LDFLAGS=("-X 'main.GitSHA=${GIT_SHA}'")
go build $GO_BUILD_FLAGS -ldflags="$GO_LDFLAGS" -o gofail
gofail-0.1.0/code-of-conduct.md 0000664 0000000 0000000 00000005737 14344734771 0016276 0 ustar 00root root 0000000 0000000 ## CoreOS Community Code of Conduct
### Contributor Code of Conduct
As contributors and maintainers of this project, and in the interest of
fostering an open and welcoming community, we pledge to respect all people who
contribute through reporting issues, posting feature requests, updating
documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free
experience for everyone, regardless of level of experience, gender, gender
identity and expression, sexual orientation, disability, personal appearance,
body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing others' private information, such as physical or electronic addresses, without explicit permission
* Other unethical or unprofessional conduct.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct. By adopting this Code of Conduct,
project maintainers commit themselves to fairly and consistently applying these
principles to every aspect of managing this project. Project maintainers who do
not follow or enforce the Code of Conduct may be permanently removed from the
project team.
This code of conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting a project maintainer, Brandon Philips
, and/or Rithu John .
This Code of Conduct is adapted from the Contributor Covenant
(http://contributor-covenant.org), version 1.2.0, available at
http://contributor-covenant.org/version/1/2/0/
### CoreOS Events Code of Conduct
CoreOS events are working conferences intended for professional networking and
collaboration in the CoreOS community. Attendees are expected to behave
according to professional standards and in accordance with their employer’s
policies on appropriate workplace behavior.
While at CoreOS events or related social networking opportunities, attendees
should not engage in discriminatory or offensive speech or actions including
but not limited to gender, sexuality, race, age, disability, or religion.
Speakers should be especially aware of these concerns.
CoreOS does not condone any statements by speakers contrary to these standards.
CoreOS reserves the right to deny entrance and/or eject from an event (without
refund) any individual found to be engaging in discriminatory or offensive
speech or actions.
Please bring any concerns to the immediate attention of designated on-site
staff, Brandon Philips , and/or Rithu John .
gofail-0.1.0/code/ 0000775 0000000 0000000 00000000000 14344734771 0013701 5 ustar 00root root 0000000 0000000 gofail-0.1.0/code/binding.go 0000664 0000000 0000000 00000002365 14344734771 0015650 0 ustar 00root root 0000000 0000000 // Copyright 2016 CoreOS, 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 code
import (
"fmt"
"io"
)
type Binding struct {
pkg string
fps []*Failpoint
}
func NewBinding(pkg string, fps []*Failpoint) *Binding {
return &Binding{pkg, fps}
}
// Write writes the fp.fail.go file for a package.
func (b *Binding) Write(dst io.Writer) error {
hdr := "// GENERATED BY GOFAIL. DO NOT EDIT.\n\n" +
"package " + b.pkg +
"\n\nimport \"go.etcd.io/gofail/runtime\"\n\n"
if _, err := fmt.Fprint(dst, hdr); err != nil {
return err
}
for _, fp := range b.fps {
_, err := fmt.Fprintf(
dst,
"var %s *runtime.Failpoint = runtime.NewFailpoint(%q)\n",
fp.Runtime(),
fp.Name(),
)
if err != nil {
return err
}
}
return nil
}
gofail-0.1.0/code/binding_test.go 0000664 0000000 0000000 00000002317 14344734771 0016704 0 ustar 00root root 0000000 0000000 // Copyright 2022 The etcd Authors
//
// 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 code
import (
"bytes"
"testing"
"github.com/stretchr/testify/assert"
)
func TestBindingWrite(t *testing.T) {
pkg := "testing"
comment := "// gofail: var Test int\n"
expected := "// GENERATED BY GOFAIL. DO NOT EDIT.\n\npackage testing\n\nimport \"go.etcd.io/gofail/runtime\"\n\nvar __fp_Test *runtime.Failpoint = runtime.NewFailpoint(\"Test\")\n"
fp, err := newFailpoint(comment)
assert.Nilf(t, err, "failed to create failpoint from comment: %s", comment)
b := NewBinding(pkg, []*Failpoint{fp})
var buf bytes.Buffer
err = b.Write(&buf)
assert.Nil(t, err)
got := buf.String()
assert.Equal(t, expected, got)
}
gofail-0.1.0/code/failpoint.go 0000664 0000000 0000000 00000005340 14344734771 0016217 0 ustar 00root root 0000000 0000000 // Copyright 2016 CoreOS, 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 code
import (
"fmt"
"io"
"strings"
)
type Failpoint struct {
name string
varType string
code []string
// whitespace for padding
ws string
}
// newFailpoint makes a new failpoint based on the a line containing a
// failpoint comment header.
func newFailpoint(l string) (*Failpoint, error) {
lt := strings.TrimSpace(l)
isGoFail := strings.HasPrefix(lt, pfxGofail)
if !isGoFail {
// not a failpoint
return nil, nil
}
pfx := pfxGofail
cmd := strings.SplitAfter(l, pfx)[1]
fields := strings.Fields(cmd)
if len(fields) != 3 || fields[0] != "var" {
return nil, fmt.Errorf("failpoint: malformed comment header %q", l)
}
return &Failpoint{name: fields[1], varType: fields[2], ws: strings.Split(l, "//")[0]}, nil
}
// flush writes the failpoint code to a buffer
func (fp *Failpoint) flush(dst io.Writer) error {
if len(fp.code) == 0 {
return fp.flushSingle(dst)
}
return fp.flushMulti(dst)
}
func (fp *Failpoint) hdr(varname string) string {
ev := errVarGoFail
hdr := fp.ws + "if v" + fp.name + fmt.Sprintf(", %s := ", ev) + fp.Runtime() + ".Acquire();" + fmt.Sprintf(" %s == nil { ", ev)
if fp.varType == "struct{}" {
// unused
varname = "_"
}
return hdr + varname + ", __fpTypeOK := v" + fp.name +
".(" + fp.varType + "); if !__fpTypeOK { goto __badType" + fp.name + "} "
}
func (fp *Failpoint) footer() string {
return "; __badType" + fp.name + ": " +
fp.Runtime() + ".BadType(v" + fp.name + ", \"" + fp.varType + "\"); };"
}
func (fp *Failpoint) flushSingle(dst io.Writer) error {
if _, err := io.WriteString(dst, fp.hdr("_")); err != nil {
return err
}
_, err := io.WriteString(dst, fp.footer()+"\n")
return err
}
func (fp *Failpoint) flushMulti(dst io.Writer) error {
hdr := fp.hdr(fp.name) + "\n"
if _, err := io.WriteString(dst, hdr); err != nil {
return err
}
for _, code := range fp.code[:len(fp.code)-1] {
if _, err := io.WriteString(dst, code+"\n"); err != nil {
return err
}
}
code := fp.code[len(fp.code)-1]
_, err := io.WriteString(dst, code+fp.footer()+"\n")
return err
}
func (fp *Failpoint) Name() string { return fp.name }
func (fp *Failpoint) Runtime() string { return "__fp_" + fp.name }
gofail-0.1.0/code/rewrite.go 0000664 0000000 0000000 00000010220 14344734771 0015704 0 ustar 00root root 0000000 0000000 // Copyright 2016 CoreOS, 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 code
import (
"bufio"
"fmt"
"io"
"strings"
"unicode"
)
const (
pfxGofail = `// gofail:`
labelGofail = `/* gofail-label */`
errVarGoFail = `__fpErr`
)
// ToFailpoints turns all gofail comments into failpoint code. Returns a list of
// all failpoints it activated.
func ToFailpoints(wdst io.Writer, rsrc io.Reader) (fps []*Failpoint, err error) {
var curfp *Failpoint
dst := bufio.NewWriter(wdst)
defer func() {
if err == nil && curfp != nil {
err = curfp.flush(dst)
}
if err == nil {
err = dst.Flush()
}
}()
src := bufio.NewReader(rsrc)
for err == nil {
l, rerr := src.ReadString('\n')
if curfp != nil {
if strings.HasPrefix(strings.TrimSpace(l), "//") {
if len(l) > 0 && l[len(l)-1] == '\n' {
l = l[:len(l)-1]
}
curfp.code = append(curfp.code, strings.Replace(l, "//", "\t", 1))
continue
} else {
curfp.flush(dst)
fps = append(fps, curfp)
curfp = nil
}
} else if label := gofailLabel(l, pfxGofail, labelGofail); label != "" {
// expose gofail label
l = label
} else if curfp, err = newFailpoint(l); err != nil {
return
} else if curfp != nil {
// found a new failpoint
continue
}
if _, err = dst.WriteString(l); err != nil {
return
}
if rerr == io.EOF {
break
}
}
return
}
// ToComments turns all failpoint code into GOFAIL comments. It returns
// a list of all failpoints it deactivated.
func ToComments(wdst io.Writer, rsrc io.Reader) (fps []*Failpoint, err error) {
src := bufio.NewReader(rsrc)
dst := bufio.NewWriter(wdst)
ws := ""
unmatchedBraces := 0
for err == nil {
l, rerr := src.ReadString('\n')
err = rerr
lTrim := strings.TrimSpace(l)
if unmatchedBraces > 0 {
opening, closing := numBraces(l)
unmatchedBraces += opening - closing
if unmatchedBraces == 0 {
// strip off badType footer
lTrim = strings.Split(lTrim, "; __badType")[0]
}
s := ws + "//" + wsPrefix(l, ws)[1:] + lTrim + "\n"
dst.WriteString(s)
continue
}
isErrVarGoFail := strings.Contains(l, fmt.Sprintf(", %s := __fp_", errVarGoFail))
isHdr := isErrVarGoFail && strings.HasPrefix(lTrim, "if")
if isHdr {
pfx := pfxGofail
ws = strings.Split(l, "i")[0]
n := strings.Split(strings.Split(l, "__fp_")[1], ".")[0]
t := strings.Split(strings.Split(l, ".(")[1], ")")[0]
dst.WriteString(ws + pfx + " var " + n + " " + t + "\n")
if !strings.Contains(l, "; __badType") {
// not single liner
unmatchedBraces = 1
}
fps = append(fps, &Failpoint{name: n, varType: t})
continue
}
if isLabel := strings.Contains(l, "\t"+labelGofail); isLabel {
l = strings.Replace(l, labelGofail, pfxGofail, 1)
}
if _, werr := dst.WriteString(l); werr != nil {
return fps, werr
}
}
if err == io.EOF {
err = nil
}
dst.Flush()
return
}
func gofailLabel(l string, pfx string, lb string) string {
if !strings.HasPrefix(strings.TrimSpace(l), pfx) {
return ""
}
label := strings.SplitAfter(l, pfx)[1]
if len(label) == 0 || !strings.Contains(label, ":") {
return ""
}
return strings.Replace(l, pfx, lb, 1)
}
func numBraces(l string) (opening int, closing int) {
for i := 0; i < len(l); i++ {
switch l[i] {
case '{':
opening++
case '}':
closing++
}
}
return
}
// wsPrefix computes the left padding of a line given a whitespace prefix.
func wsPrefix(l, wsPfx string) string {
lws := ""
if len(wsPfx) == 0 {
lws = l
} else {
wsSplit := strings.SplitAfter(l, wsPfx)
if len(wsSplit) < 2 {
return ""
}
lws = strings.Join(wsSplit[1:], "")
}
for i, c := range lws {
if !unicode.IsSpace(c) {
return lws[:i]
}
}
return lws
}
gofail-0.1.0/code/rewrite_test.go 0000664 0000000 0000000 00000005432 14344734771 0016754 0 ustar 00root root 0000000 0000000 // Copyright 2016 CoreOS, 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 code
import (
"bytes"
"strings"
"testing"
)
var examples = []struct {
code string
wfps int
}{
{"func f() {\n\t// gofail: var Test int\n\t// fmt.Println(Test)\n}", 1},
{"func f() {\n\t\t// gofail: var Test int\n\t\t// \tfmt.Println(Test)\n}", 1},
{"func f() {\n// gofail: var Test int\n// \tfmt.Println(Test)\n}", 1},
{"func f() {\n\t// gofail: var Test int\n\t// fmt.Println(Test)\n}\n", 1},
{"func f() {\n\t// gofail: var Test int\n\t// fmt.Println(Test)// return\n}\n", 1},
{"func f() {\n\t// gofail: var OneLineTest int\n}\n", 1},
{"func f() {\n\t// gofail: var Test int\n\t// fmt.Println(Test)\n\n\t// gofail: var Test2 int\n\t// fmt.Println(Test2)\n}\n", 2},
{"func f() {\n\t// gofail: var NoTypeTest struct{}\n\t// fmt.Println(`hi`)\n}\n", 1},
{"func f() {\n\t// gofail: var NoTypeTest struct{}\n}\n", 1},
{"func f() {\n\t// gofail: var NoTypeTest struct{}\n\t// fmt.Println(`hi`)\n\t// fmt.Println(`bye`)\n}\n", 1},
{`
func f() {
// gofail: labelTest:
for {
if g() {
// gofail: var testLabel struct{}
// continue labelTest
return
}
}
}
`, 1},
}
func TestToFailpoint(t *testing.T) {
for i, ex := range examples {
dst := bytes.NewBuffer(make([]byte, 0, 1024))
src := strings.NewReader(ex.code)
fps, err := ToFailpoints(dst, src)
if err != nil {
t.Fatalf("%d: %v", i, err)
}
if len(fps) != ex.wfps {
t.Fatalf("%d: got %d failpoints but expected %d", i, len(fps), ex.wfps)
}
dstOut := dst.String()
if len(strings.Split(dstOut, "\n")) != len(strings.Split(ex.code, "\n")) {
t.Fatalf("%d: bad line count %q", i, dstOut)
}
}
}
func TestToComment(t *testing.T) {
for i, ex := range examples {
dst := bytes.NewBuffer(make([]byte, 0, 1024))
src := strings.NewReader(ex.code)
_, err := ToFailpoints(dst, src)
if err != nil {
t.Fatalf("%d: %v", i, err)
}
src = strings.NewReader(dst.String())
dst.Reset()
fps, err := ToComments(dst, src)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
plainCode := dst.String()
if plainCode != ex.code {
t.Fatalf("%d: non-preserving ToComments(); got %q, want %q", i, plainCode, ex.code)
}
if len(fps) != ex.wfps {
t.Fatalf("%d: got %d failpoints but expected %d", i, len(fps), ex.wfps)
}
}
}
gofail-0.1.0/doc/ 0000775 0000000 0000000 00000000000 14344734771 0013534 5 ustar 00root root 0000000 0000000 gofail-0.1.0/doc/design.md 0000664 0000000 0000000 00000024674 14344734771 0015344 0 ustar 00root root 0000000 0000000 # Gofail
## Table of Contents
- **[Workflow](#workflow)**
- [Step 1: Add failpoints](#step-1-add-failpoints)
- [Step 2: Build your application with failpoints](#step-2-build-your-application-with-failpoints)
- [Step 3: Trigger failpoints](#step-3-trigger-failpoints)
- **[Generated code](#generated-code)**
- [Overview](#overview)
- [Example 1: No customized code](#example-1-no-customized-code)
- [Example 2: With customized code](#example-2-with-customized-code)
- [Example 3: With multiple lines of customized code](#example-3-with-multiple-lines-of-customized-code)
- [Example 4: With gofail label](#example-4-with-gofail-label)
- **[Gofail Term](#gofail-term)**
- [Syntax](#syntax)
- [Design diagram](#design-diagram)
## Workflow
### Step 1: Add failpoints
Add special comments like below into your code where you want to inject failpoints,
```
// gofail: var SomeFuncString string
```
### Step 2: Build your application with failpoints
Translate the gofail comments using command below. Note that `gofail` needs to be installed beforehand using command `go install go.etcd.io/gofail@latest`.
```
$ gofail enable
```
`gofail` translates all gofail comments in the provided `` in place and also generates some variable
declarations in separate files. If no `` is provided, then the current directory is used. See [Generated code](#generated-code)
below to get examples on the translated & generated code.
Afterwards, add gofail runtime package into your application as a dependency module,
```
$ go get go.etcd.io/gofail/runtime
```
Finally, build your application using command `go build`.
### Step 3: Trigger failpoints
There are two ways to trigger failpoints, which are static and dynamic ways.
The static way is to set [gofail terms](#gofail-term) using environment variable `GOFAIL_FAILPOINTS` directly when starting your application. See example below,
```
$ GOFAIL_FAILPOINTS='SomeFuncString=sleep("600s")' ./cmd
```
You can set multiple failpoints by using ";" as the delimiter,
```
GOFAIL_FAILPOINTS='failpoint1=return("hello");failpoint2=sleep(10)' ./cmd
```
The dynamic way is to set an HTTP endpoint using environment variable `GOFAIL_HTTP` when starting your application,
and add [gofail terms](#gofail-term) via the endpoint afterwards. See example below,
```
$ GOFAIL_HTTP="127.0.0.1:22381" ./cmd
$ curl http://127.0.0.1:22381/SomeFuncString -XPUT -d'sleep("600s")'
```
Similarly, you can set multiple failpoints using endpoint `/failpoints`,
```
curl http://127.0.0.1:22381/failpoints -X PUT -d'failpoint1=return("hello");failpoint2=sleep(10)'
```
## Generated code
### Overview
`gofail enable ` makes the following two changes for each provided go source file, which contains the "gofail" comments,
1. Translate the "gofail" comments in place to code that accesses the gofail runtime;
2. Generate code that constructs failpoint variables and registers them to the "gofail" runtime.
The high level format of the translated code (#1) is below,
```
customized code