├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── workflows
│ └── build-test-workflow.yml
├── .gitignore
├── .idea
├── vcs.xml
└── watcherTasks.xml
├── Breaker.go
├── CODE_OF_CONDUCTS.md
├── CONTRIBUTING.md
├── Config.go
├── LICENSE
├── Main.go
├── Makefile
├── README.md
├── Server.go
├── Server_test.go
├── Transaction.go
├── cache
├── Caching.go
└── Caching_test.go
├── go.mod
├── go.sum
└── test
└── DummyHttpServer.go
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. I create code for this and that
16 | 2. With a test for this and that
17 | 3. Instead of seeng this
18 | 4. I see that
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Additional context**
24 | Add any other context about the problem here.
25 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/workflows/build-test-workflow.yml:
--------------------------------------------------------------------------------
1 | name: retter-ci
2 |
3 | on:
4 | pull_request:
5 | branches:
6 | - main
7 | push:
8 | branches:
9 | - main
10 |
11 | jobs:
12 | build:
13 | runs-on: ubuntu-latest
14 | steps:
15 | - name: Install Go
16 | uses: actions/setup-go@v2
17 | with:
18 | go-version: 1.13
19 | - name: Checkout code
20 | uses: actions/checkout@v2
21 | - name: Fetching dependencies
22 | run : go get -v -t -d ./...
23 | - name: Install GoLint and Goornogo
24 | run : |
25 | go get -u golang.org/x/lint/golint
26 | - name: Execute test
27 | run : make test
28 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.toptal.com/developers/gitignore/api/intellij,vscode,go,vim,macos,windows,linux
3 | # Edit at https://www.toptal.com/developers/gitignore?templates=intellij,vscode,go,vim,macos,windows,linux
4 |
5 | ### Go ###
6 | # Binaries for programs and plugins
7 | *.exe
8 | *.exe~
9 | *.dll
10 | *.so
11 | *.dylib
12 |
13 | # Test binary, built with `go test -c`
14 | *.test
15 |
16 | # Output of the go coverage tool, specifically when used with LiteIDE
17 | *.out
18 |
19 | # Dependency directories (remove the comment below to include it)
20 | # vendor/
21 |
22 | ### Go Patch ###
23 | /vendor/
24 | /Godeps/
25 |
26 | ### Intellij ###
27 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
28 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
29 |
30 | # User-specific stuff
31 | .idea/**/workspace.xml
32 | .idea/**/tasks.xml
33 | .idea/**/usage.statistics.xml
34 | .idea/**/dictionaries
35 | .idea/**/shelf
36 |
37 | # Generated files
38 | .idea/**/contentModel.xml
39 |
40 | # Sensitive or high-churn files
41 | .idea/**/dataSources/
42 | .idea/**/dataSources.ids
43 | .idea/**/dataSources.local.xml
44 | .idea/**/sqlDataSources.xml
45 | .idea/**/dynamic.xml
46 | .idea/**/uiDesigner.xml
47 | .idea/**/dbnavigator.xml
48 |
49 | # Gradle
50 | .idea/**/gradle.xml
51 | .idea/**/libraries
52 |
53 | # Gradle and Maven with auto-import
54 | # When using Gradle or Maven with auto-import, you should exclude module files,
55 | # since they will be recreated, and may cause churn. Uncomment if using
56 | # auto-import.
57 | # .idea/artifacts
58 | # .idea/compiler.xml
59 | # .idea/jarRepositories.xml
60 | # .idea/modules.xml
61 | # .idea/*.iml
62 | # .idea/modules
63 | # *.iml
64 | # *.ipr
65 |
66 | # CMake
67 | cmake-build-*/
68 |
69 | # Mongo Explorer plugin
70 | .idea/**/mongoSettings.xml
71 |
72 | # File-based project format
73 | *.iws
74 |
75 | # IntelliJ
76 | out/
77 |
78 | # mpeltonen/sbt-idea plugin
79 | .idea_modules/
80 |
81 | # JIRA plugin
82 | atlassian-ide-plugin.xml
83 |
84 | # Cursive Clojure plugin
85 | .idea/replstate.xml
86 |
87 | # Crashlytics plugin (for Android Studio and IntelliJ)
88 | com_crashlytics_export_strings.xml
89 | crashlytics.properties
90 | crashlytics-build.properties
91 | fabric.properties
92 |
93 | # Editor-based Rest Client
94 | .idea/httpRequests
95 |
96 | # Android studio 3.1+ serialized cache file
97 | .idea/caches/build_file_checksums.ser
98 |
99 | ### Intellij Patch ###
100 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
101 |
102 | *.iml
103 | modules.xml
104 | .idea/misc.xml
105 | *.ipr
106 |
107 | # Sonarlint plugin
108 | # https://plugins.jetbrains.com/plugin/7973-sonarlint
109 | .idea/**/sonarlint/
110 |
111 | # SonarQube Plugin
112 | # https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
113 | .idea/**/sonarIssues.xml
114 |
115 | # Markdown Navigator plugin
116 | # https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
117 | .idea/**/markdown-navigator.xml
118 | .idea/**/markdown-navigator-enh.xml
119 | .idea/**/markdown-navigator/
120 |
121 | # Cache file creation bug
122 | # See https://youtrack.jetbrains.com/issue/JBR-2257
123 | .idea/$CACHE_FILE$
124 |
125 | # CodeStream plugin
126 | # https://plugins.jetbrains.com/plugin/12206-codestream
127 | .idea/codestream.xml
128 |
129 | ### Linux ###
130 | *~
131 |
132 | # temporary files which can be created if a process still has a handle open of a deleted file
133 | .fuse_hidden*
134 |
135 | # KDE directory preferences
136 | .directory
137 |
138 | # Linux trash folder which might appear on any partition or disk
139 | .Trash-*
140 |
141 | # .nfs files are created when an open file is removed but is still being accessed
142 | .nfs*
143 |
144 | ### macOS ###
145 | # General
146 | .DS_Store
147 | .AppleDouble
148 | .LSOverride
149 |
150 | # Icon must end with two \r
151 | Icon
152 |
153 |
154 | # Thumbnails
155 | ._*
156 |
157 | # Files that might appear in the root of a volume
158 | .DocumentRevisions-V100
159 | .fseventsd
160 | .Spotlight-V100
161 | .TemporaryItems
162 | .Trashes
163 | .VolumeIcon.icns
164 | .com.apple.timemachine.donotpresent
165 |
166 | # Directories potentially created on remote AFP share
167 | .AppleDB
168 | .AppleDesktop
169 | Network Trash Folder
170 | Temporary Items
171 | .apdisk
172 |
173 | ### Vim ###
174 | # Swap
175 | [._]*.s[a-v][a-z]
176 | !*.svg # comment out if you don't need vector files
177 | [._]*.sw[a-p]
178 | [._]s[a-rt-v][a-z]
179 | [._]ss[a-gi-z]
180 | [._]sw[a-p]
181 |
182 | # Session
183 | Session.vim
184 | Sessionx.vim
185 |
186 | # Temporary
187 | .netrwhist
188 | # Auto-generated tag files
189 | tags
190 | # Persistent undo
191 | [._]*.un~
192 |
193 | ### vscode ###
194 | .vscode/*
195 | !.vscode/settings.json
196 | !.vscode/tasks.json
197 | !.vscode/launch.json
198 | !.vscode/extensions.json
199 | *.code-workspace
200 |
201 | ### Windows ###
202 | # Windows thumbnail cache files
203 | Thumbs.db
204 | Thumbs.db:encryptable
205 | ehthumbs.db
206 | ehthumbs_vista.db
207 |
208 | # Dump file
209 | *.stackdump
210 |
211 | # Folder config file
212 | [Dd]esktop.ini
213 |
214 | # Recycle Bin used on file shares
215 | $RECYCLE.BIN/
216 |
217 | # Windows Installer files
218 | *.cab
219 | *.msi
220 | *.msix
221 | *.msm
222 | *.msp
223 |
224 | # Windows shortcuts
225 | *.lnk
226 |
227 | # End of https://www.toptal.com/developers/gitignore/api/intellij,vscode,go,vim,macos,windows,linux
228 |
229 | build/**
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/watcherTasks.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/Breaker.go:
--------------------------------------------------------------------------------
1 | /*-----------------------------------------------------------------------------------
2 | -- RETTER --
3 | -- Copyright (C) 2021 RETTER's Contributors --
4 | -- --
5 | -- This program is free software: you can redistribute it and/or modify --
6 | -- it under the terms of the GNU Affero General Public License as published --
7 | -- by the Free Software Foundation, either version 3 of the License, or --
8 | -- (at your option) any later version. --
9 | -- --
10 | -- This program is distributed in the hope that it will be useful, --
11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of --
12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --
13 | -- GNU Affero General Public License for more details. --
14 | -- --
15 | -- You should have received a copy of the GNU Affero General Public License --
16 | -- along with this program. If not, see . --
17 | -----------------------------------------------------------------------------------*/
18 |
19 | package main
20 |
21 | import (
22 | "github.com/sirupsen/logrus"
23 | "github.com/sony/gobreaker"
24 | "net/http"
25 | "time"
26 | )
27 |
28 | var (
29 | breakerLog = logrus.WithFields(logrus.Fields{
30 | "module": "GoBreaker",
31 | "file": "Breaker.go",
32 | })
33 |
34 | // PathBreakers is a map of string to gobreaker.CircuitBreaker.
35 | // The string key is a full path + session key information.
36 | // This makes each user's accessible path is circuit breaked.
37 | PathBreakers = make(map[string]*gobreaker.CircuitBreaker)
38 | )
39 |
40 | // GetBreakerSettingForRequest will create a grobreaker.Setting for each created CircuitBreaker.
41 | func GetBreakerSettingForRequest(req *http.Request) gobreaker.Settings {
42 | key := getKey(req)
43 | return gobreaker.Settings{
44 | Name: key,
45 | MaxRequests: 1,
46 | Interval: 10 * time.Second,
47 | Timeout: 0,
48 | ReadyToTrip: func(counts gobreaker.Counts) bool {
49 | done := counts.TotalFailures + counts.TotalSuccesses
50 | if done > 0 && counts.Requests > 4 {
51 | breakerLog.Tracef("[%s] ready to trip. totalFail %d of %d", key, counts.TotalFailures, done)
52 | failRate := float64(counts.TotalFailures) / float64(done)
53 | return failRate > Config.GetFloat(FailureRate)
54 | }
55 | return int(counts.ConsecutiveFailures) > Config.GetInt(ConsecutiveFail)
56 | },
57 | OnStateChange: func(name string, from gobreaker.State, to gobreaker.State) {
58 | breakerLog.Tracef("[%s] changed state from %s to %s", key, from.String(), to.String())
59 | },
60 | }
61 | }
62 |
63 | // GetBreakerForRequest returns a CircuitBreaker to be use for circuit breaking
64 | // each particular request.
65 | func GetBreakerForRequest(req *http.Request) *gobreaker.CircuitBreaker {
66 | key := getKey(req)
67 | if b, ok := PathBreakers[key]; ok {
68 | return b
69 | }
70 | newBreaker := gobreaker.NewCircuitBreaker(GetBreakerSettingForRequest(req))
71 | PathBreakers[key] = newBreaker
72 | return newBreaker
73 | }
74 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCTS.md:
--------------------------------------------------------------------------------
1 | ## Code of Conduct
2 |
3 | ### Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, gender identity and expression, level of experience,
9 | nationality, personal appearance, race, religion, or sexual identity and
10 | orientation.
11 |
12 | ### Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ### Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ### Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ### Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at `oss@hyperjump.tech`. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ### Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at [http://contributor-covenant.org/version/1/4][version]
72 |
73 | [homepage]: http://contributor-covenant.org
74 | [version]: http://contributor-covenant.org/version/1/4/
75 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | When contributing to this repository, please first discuss the change you wish to make via issue,
4 | email, or any other method with the owners of this repository before making a change.
5 |
6 | Please note we have a code of conduct, please follow it in all your interactions with the project.
7 |
8 | ## Fork Process
9 |
10 | 1. Ensure that you've installed the Golang (minimum 1.13) in your system.
11 | 2. For this project into your own Github account.
12 | 3. Clone the `retter` forked repository on your account.
13 | 4. Enter the cloned directory.
14 | 5. Apply new "upstream" to original `hyperjumptech/retter` git
15 | 4. Now you can work on your account
16 | 5. Remember to pull from your upstream often. `git pull upstream master`
17 |
18 | ## Pull Request Process
19 |
20 | 1. Make sure you always have the most recent update from your upstream. `git pull upstream master`
21 | 2. Resolve all conflict, if any.
22 | 3. Make sure `make test` always successful (you wont be able to create pull request if this fail, circle-ci, travis-ci and azure-devops will make sure of this.)
23 | 4. Push your code to your project's master repository.
24 | 5. Create PullRequest.
25 | * Go to `hithub.com/hyperjumptech/retter`
26 | * Select `Pull Request` tab
27 | * Click "New pull request" button
28 | * Click "compare across fork"
29 | * Change the source head repository from your fork and target is `hyperjumptech/retter`
30 | * Hit the "Create pull request" button
31 | * Fill in all necessary information to help us understand about your pull request.
32 |
33 |
--------------------------------------------------------------------------------
/Config.go:
--------------------------------------------------------------------------------
1 | /*-----------------------------------------------------------------------------------
2 | -- RETTER --
3 | -- Copyright (C) 2021 RETTER's Contributors --
4 | -- --
5 | -- This program is free software: you can redistribute it and/or modify --
6 | -- it under the terms of the GNU Affero General Public License as published --
7 | -- by the Free Software Foundation, either version 3 of the License, or --
8 | -- (at your option) any later version. --
9 | -- --
10 | -- This program is distributed in the hope that it will be useful, --
11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of --
12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --
13 | -- GNU Affero General Public License for more details. --
14 | -- --
15 | -- You should have received a copy of the GNU Affero General Public License --
16 | -- along with this program. If not, see . --
17 | -----------------------------------------------------------------------------------*/
18 |
19 | package main
20 |
21 | import (
22 | "github.com/sirupsen/logrus"
23 | "github.com/spf13/viper"
24 | "reflect"
25 | "strconv"
26 | "strings"
27 | )
28 |
29 | const (
30 | // CacheTTL is key config for number of TTL in second
31 | CacheTTL = "cache.ttl"
32 |
33 | // CacheDetectQuery is key config for specifying whether to include session detection or not
34 | CacheDetectQuery = "cache.detect.query"
35 |
36 | // CacheDetectSession is key config for specifying whether to include session detection or not
37 | CacheDetectSession = "cache.detect.session"
38 |
39 | // BackendURL is key config for the base URL to call to backend
40 | BackendURL = "backend.baseurl"
41 |
42 | // ServerListen is key config for the server listening setting (bind host and port)
43 | ServerListen = "server.listen"
44 |
45 | // FailureRate is key config for the failure rate detection in the CircuitBreaker.
46 | // If the request to backend has reached this failure rate, circuit will open.
47 | // The fail rate will reset every 10 second
48 | FailureRate = "breaker.fail.rate"
49 |
50 | // ConsecutiveFail is key config for the number of consecutive backend http call fails.
51 | ConsecutiveFail = "breaker.consecutive.fail"
52 | )
53 |
54 | var (
55 | configLog = logrus.WithFields(logrus.Fields{
56 | "module": "Configuration",
57 | "file": "Config.go",
58 | })
59 |
60 | // Config is the configuration instance
61 | Config = Configuration{
62 | CacheTTL: "60", // time to live in seconds
63 | CacheDetectSession: "false", // always account session cookie in the cache
64 | CacheDetectQuery: "true", // always account request URL query in the cache
65 | BackendURL: "http://localhost:8088",
66 | ServerListen: ":8089",
67 | "server.timeout.write": "15 seconds",
68 | "server.timeout.read": "15 seconds",
69 | "server.timeout.idle": "60 seconds",
70 | "server.timeout.graceshut": "15 seconds",
71 | FailureRate: "0.66",
72 | ConsecutiveFail: "5",
73 | }
74 | )
75 |
76 | func init() {
77 | viper.SetEnvPrefix("retter")
78 | viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
79 | viper.AutomaticEnv()
80 | for k := range Config {
81 | err := viper.BindEnv(k)
82 | if err != nil {
83 | configLog.Errorf("Failed to bind env \"%s\" into configuration. Got %s", k, err)
84 | }
85 | }
86 | }
87 |
88 | // Configuration configuration is a simple string to string map to store RETTER configuration.
89 | // Although its a string to string map, developer should not access this map directly to obtain configuration value.
90 | // Use GetString, GetInt, GetBool or GetFloat function as it uses Viper to sync configuration with environment variable.
91 | type Configuration map[string]string
92 |
93 | // GetString will return string configuration value of a string key
94 | func (c Configuration) GetString(key string) string {
95 | if valStr, ok := c[key]; ok {
96 | ret := viper.GetString(key)
97 | if len(ret) == 0 {
98 | return valStr
99 | }
100 | return ret
101 | }
102 | return ""
103 | }
104 |
105 | // GetInt will return integer configuration value of a string key
106 | func (c Configuration) GetInt(key string) int {
107 | if valStr, ok := c[key]; ok {
108 | ret := viper.GetInt(key)
109 | if reflect.ValueOf(ret).IsZero() {
110 | i, err := strconv.Atoi(valStr)
111 | if err != nil {
112 | return 0
113 | }
114 | return i
115 | }
116 | return ret
117 | }
118 | return 0
119 | }
120 |
121 | // GetFloat will return float64 configuration value of a string key
122 | func (c Configuration) GetFloat(key string) float64 {
123 | if valStr, ok := c[key]; ok {
124 | ret := viper.GetFloat64(key)
125 | if reflect.ValueOf(ret).IsZero() {
126 | f, err := strconv.ParseFloat(valStr, 64)
127 | if err != nil {
128 | return 0
129 | }
130 | return f
131 | }
132 | return ret
133 | }
134 | return 0
135 | }
136 |
137 | // GetBoolean will return bool configuration value of a string key
138 | func (c Configuration) GetBoolean(key string) bool {
139 | if valStr, ok := c[key]; ok {
140 | ret := viper.GetBool(key)
141 | if reflect.ValueOf(ret).IsZero() {
142 | b, err := strconv.ParseBool(valStr)
143 | if err != nil {
144 | return false
145 | }
146 | return b
147 | }
148 | return ret
149 | }
150 | return false
151 | }
152 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------
/Main.go:
--------------------------------------------------------------------------------
1 | /*-----------------------------------------------------------------------------------
2 | -- RETTER --
3 | -- Copyright (C) 2021 RETTER's Contributors --
4 | -- --
5 | -- This program is free software: you can redistribute it and/or modify --
6 | -- it under the terms of the GNU Affero General Public License as published --
7 | -- by the Free Software Foundation, either version 3 of the License, or --
8 | -- (at your option) any later version. --
9 | -- --
10 | -- This program is distributed in the hope that it will be useful, --
11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of --
12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --
13 | -- GNU Affero General Public License for more details. --
14 | -- --
15 | -- You should have received a copy of the GNU Affero General Public License --
16 | -- along with this program. If not, see . --
17 | -----------------------------------------------------------------------------------*/
18 |
19 | package main
20 |
21 | import (
22 | "context"
23 | "fmt"
24 | "github.com/hyperjumptech/jiffy"
25 | "github.com/hyperjumptech/retter/test"
26 | log "github.com/sirupsen/logrus"
27 | "net/http"
28 | "os"
29 | "os/signal"
30 | "time"
31 | )
32 |
33 | func splash() {
34 | fmt.Println("________________________________________________________________ ")
35 | fmt.Println(`\______ \_ _____/\__ ___/\__ ___/\_ _____/\______ \`)
36 | fmt.Println(" | _/| __)_ | | | | | __)_ | _/")
37 | fmt.Println(` | | \| \ | | | | | \ | | \`)
38 | fmt.Println(" |____|_ /_______ / |____| |____| /_______ / |____|_ /")
39 | fmt.Println(` \/ \/ \/ \/ `)
40 | }
41 |
42 | func main() {
43 | if len(os.Args) == 1 {
44 | splash()
45 | startServer()
46 | } else if len(os.Args) == 2 {
47 | test.StartDummyServer(os.Args[1], true)
48 | }
49 | }
50 |
51 | func startServer() {
52 | startTime := time.Now()
53 | listen := Config.GetString(ServerListen)
54 | if len(listen) == 0 {
55 | panic("server.listen not configured")
56 | }
57 |
58 | if len(listen) == 0 {
59 | panic("backend.baseurl not configured")
60 | }
61 |
62 | var wait time.Duration
63 |
64 | graceShut, err := jiffy.DurationOf(Config.GetString("server.timeout.graceshut"))
65 | if err != nil {
66 | panic(err)
67 | }
68 | wait = graceShut
69 | WriteTimeout, err := jiffy.DurationOf(Config.GetString("server.timeout.write"))
70 | if err != nil {
71 | panic(err)
72 | }
73 | ReadTimeout, err := jiffy.DurationOf(Config.GetString("server.timeout.read"))
74 | if err != nil {
75 | panic(err)
76 | }
77 | IdleTimeout, err := jiffy.DurationOf(Config.GetString("server.timeout.idle"))
78 | if err != nil {
79 | panic(err)
80 | }
81 |
82 | srv := &http.Server{
83 | Addr: listen,
84 | // Good practice to set timeouts to avoid Slowloris attacks.
85 | WriteTimeout: WriteTimeout,
86 | ReadTimeout: ReadTimeout,
87 | IdleTimeout: IdleTimeout,
88 | Handler: NewRetterHTTPHandler(), // Pass our instance of gorilla/mux in.
89 | }
90 |
91 | // Run our server in a goroutine so that it doesn't block.
92 | go func() {
93 | l := Config.GetString(ServerListen)
94 | if l[0:1] == ":" {
95 | l = "http://0.0.0.0" + l
96 | }
97 | log.Infof("This RETTER instance will forwards GET request...")
98 | log.Infof(" From : %s/*", l)
99 | log.Infof(" To : %s/*", Config.GetString(BackendURL))
100 | log.Infof("URL Query Detect : %s", Config.GetString(CacheDetectQuery))
101 | log.Infof("URL Session Detect : %s", Config.GetString(CacheDetectSession))
102 | log.Infof("RETTER is listening on : [%s]", l)
103 | if err := srv.ListenAndServe(); err != nil {
104 | log.Println(err)
105 | }
106 | }()
107 |
108 | c := make(chan os.Signal, 1)
109 | // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
110 | // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
111 | signal.Notify(c, os.Interrupt)
112 |
113 | // Block until we receive our signal.
114 | <-c
115 |
116 | // Create a deadline to wait for.
117 | ctx, cancel := context.WithTimeout(context.Background(), wait)
118 | defer cancel()
119 |
120 | // Doesn't block if no connections, but will otherwise wait
121 | // until the timeout deadline.
122 | srv.Shutdown(ctx)
123 |
124 | // Optionally, you could run srv.Shutdown in a goroutine and block on
125 | // <-ctx.Done() if your application should wait for other services
126 | // to finalize based on context cancellation.
127 | dur := time.Now().Sub(startTime)
128 | durDesc := jiffy.DescribeDuration(dur, jiffy.NewWant())
129 | log.Infof("Shutting down. This RETTER been protecting the backend service for %s", durDesc)
130 | os.Exit(0)
131 | }
132 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | GO111MODULE=on
2 |
3 | .PHONY: all test test-short fix-antlr4-bug build
4 |
5 | build-linux:
6 | mkdir -p build/linux
7 | env GOOS=linux GOARCH=amd64 go build -o build/linux ./...
8 |
9 | build-windows:
10 | mkdir -p build/windows
11 | env GOOS=windows GOARCH=amd64 go build -o build/windows ./...
12 |
13 | lint: build-linux build-windows
14 | go get -u golang.org/x/lint/golint
15 | golint -set_exit_status .
16 |
17 | test: lint
18 | go test ./... -covermode=count -coverprofile=coverage.out
19 |
20 | test-coverage: test
21 | go tool cover -html=coverage.out
22 |
23 | clean:
24 | rm -f build/retter.*
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ```
2 | ________________________________________________________________
3 | \______ \_ _____/\__ ___/\__ ___/\_ _____/\______ \
4 | | _/| __)_ | | | | | __)_ | _/
5 | | | \| \ | | | | | \ | | \
6 | |____|_ /_______ / |____| |____| /_______ / |____|_ /
7 | \/ \/github.com/hyperjumptech/retter\/ \/
8 | ```
9 |
10 | [](https://github.com/hyperjumptech/grule-rule-engine/actions)
11 |
12 | - **RETTER** is ... a Great Savior for your great web solution.
13 | - **RETTER** is ... a German word for "Savior"
14 | - **RETTER** is ... technically its a Circuit Breaker server. Yes. [Circuit Breaker as explained by Martin Fowler](https://martinfowler.com/bliki/CircuitBreaker.html)
15 |
16 | ## Problem Statement
17 |
18 | - My HTTP server now being hit by gazillion request per-second.
19 | - When this happen, my user start to suffer. As their experience becoming worse and worse overtime.
20 | - As response time grew longer, request time-out started to creep to my user.
21 | - My Web App logs shows errors like "DB Error : Too many connection open" appears like hell.
22 | - People told me to do a Horizontal or Vertical scaling toward my web or database server. But I only have a budget for none, may be I can squeeze 1 small server.
23 | - I need my user to slowdown a bit. To give my server time to breathe. But I don't want to sacrifice my user experiences.
24 | - I don't want to code my Web App further since I already optimize the hell out of it.
25 |
26 | ## How RETTER can help?
27 |
28 | - Retter is a server application that implements Circuit Breaker pattern.
29 | - It sits infront of your Web Server receiving HTTP requests and forward them to your server.
30 | - When it sees that your server start to get overwhelmed by requests, for the next incoming request, RETTER will reply back to the requester with the last known success response.
31 | - This way, RETTER give time for your Web App (and all connected server, eg. DB Server) to finish its piling tasks and recover back resources such as memory and database connections.
32 |
33 | In normal condition (CIRCUIT CLOSE):
34 |
35 | ```text
36 | RETTER forwards request and response to your webapp
37 | _______ +--------+ +--------+ +--------+
38 | / \ --request-->| |--request-->| |--query-->| |
39 | | Internet | | RETTER | | WEBAPP | | DB |
40 | \_________/ <--request--| cache |<-response--| |<-result--| |
41 | +--------+ +--------+ +--------+
42 | ```
43 |
44 | In ugly condition (CIRCUIT OPEN):
45 |
46 | ```text
47 | RETTER immediately respond to new requests with last known success response
48 | _______ +--------+ +--------+ +--------+
49 | / \ --request-->| |-----+ | |--query-->| |
50 | | Internet | | RETTER | v | WEBAPP | | DB |
51 | \_________/ <--request--| cache |<-response--| |<-result--| |
52 | +--------+ +--------+ +--------+
53 | Thus gives time to your server to finish their works
54 | ```
55 |
56 | # Installation
57 |
58 | ## Using available binary
59 |
60 | Go to **RETTER** release page, download the executable on the version you preffer.
61 |
62 | ## Use Golang to automatically install.
63 |
64 | Install Golang on your server. Once installed, you can simply...
65 |
66 | ```shell script
67 | go install github.com/hyperjumptech/retter
68 | ```
69 |
70 | The executable binnary will be located at `$GOPATH/bin/retter`, Make sure your `$GOPATH/bin` is in your `$PATH`
71 | You can run the server straight away.
72 |
73 | # Running RETTER
74 |
75 | Once you get a hand on the binnary. You can simply execute them. If your configuration is correct, it will run smoothly.
76 |
77 | # Configuring RETTER
78 |
79 | **RETTER** configuration are all done through Environment Variables.
80 | Please put in the following environment variables if you want to change some of **RETTER** behavior.
81 |
82 |
83 | | Envorinment Variable | Description | Example / Default |
84 | |------------------------------------|---------------------------------------------------------|----------------------|
85 | | RETTER_CACHE_TTL | The cache Time To Live in Seconds | 5 |
86 | | RETTER_CACHE_DETECT_QUERY | Take query parameter (if exist) as cache key | false |
87 | | RETTER_CACHE_DETECT_SESSION | Take Cookie header for session as cache key | true |
88 | | RETTER_BACKEND_BASEURL | The base url of your server to protect | http://localhost:8088|
89 | | RETTER_SERVER_LISTEN | The address where this RETTE server will be accessible | :8089 |
90 | | RETTER_BREAKER_FAIL_RATE | The failrate to which will trigger the circuit OPEN | 0.66 |
91 | | RETTER_BREAKER_CONSECUTIVE_FAIL | The number of consecutive error to trigger circuit OPEN | 5 |
92 | | RETTER_SERVER_TIMEOUT_WRITE | The retter's server write timeout | 15 seconds, |
93 | | RETTER_SERVER_TIMEOUT_READ | The retter's server read timeout | 15 seconds, |
94 | | RETTER_SERVER_TIMEOUT_IDLE | The retter's idle timeout | 60 seconds, |
95 | | RETTER_SERVER_TIMEOUT_GRACESHUT | The retter's grace shutdown time | 15 seconds, |
96 |
97 | # Benchmark
98 |
99 | Please notice that this benchmark is greatly influenced by the network limitation.
100 |
101 | ```text
102 | goos: windows
103 | goarch: amd64
104 | pkg: github.com/hyperjumptech/retter
105 | BenchmarkRetterHTTPHandler_ServeHTTP
106 | BenchmarkRetterHTTPHandler_ServeHTTP-6 6 450803033 ns/op
107 | ```
108 |
109 | # Tasks and Help Wanted
110 |
111 | Yes. We need contributors to make **RETTER** even better and useful to the Open Source Community.
112 |
113 | * Need to do more and more and more tests.
114 | * Better code coverage test.
115 | * Better commenting for go doc best practice.
116 | * Improve function argument handling to be more fluid and intuitive.
117 |
118 | If you really want to help us, simply `Fork` the project and apply for Pull Request.
119 | Please read our [Contribution Manual](CONTRIBUTING.md) and [Code of Conduct](CODE_OF_CONDUCTS.md)
120 |
121 | # FAQ
122 |
123 | **Q1** : Is it guaranteed that my web performance increases ?
124 | **A1** : Slight increase, Yes!. What is more important is "Resilience" to your web server.
125 |
126 | **Q2** : Is it good for streaming server? Or servers that provides huge content (eg. movie)?
127 | **A2** : Nope. RETTER will easily running out of memory and it give delays as it need to get the full response first for caching.
128 |
129 | **Q3** : I have multiple WebApp, its like a cluster. Can 1 RETTER server instance serve them all?
130 | **A3** : Nope. RETTER can sit infront of a WEB balancer though. It will forward all headers such as `X-Real-IP` or `X-Forwarded-For`
131 |
132 | **Q4** : Do RETTER remember HTTP sessions (eg `PHPSESSID`)? I do *sticky session* and content are delivered per-user basis, different content for different user.
133 | **A4** : Yup. RETTER caches responses based on the URL Paths and Cookie of `PHPSESSID`, `JSESSIONID` and `ci_session`
134 |
135 | **Q5** : Do RETTER support response compression?
136 | **A5** : Yup. Only if the HTTP client requested using `Accept-Encoding: gzip` header.
137 |
138 | **Q6** : Do RETTER support response compression?
139 | **A6** : Yup. Only if the HTTP client requested using `Accept-Encoding: gzip` header.
140 |
141 | **Q7** : My API-Gateway already have Circuit Breaker, should I use RETTER? or is using RETTER do any better?
142 | **A7** : Go away !! You are just trolling me.
143 |
144 | **Q8** : RETTER is buggy, you noob golang programmer, can you do any better?
145 | **A8** : Nope, Until you put an Issue. Or even better, a PR!
146 |
147 | **Q9** : What is being cached by RETTER?
148 | **A9** : RETTER will cache all response of all **GET**..., Yes **GET** method, identified by its `URL path + queries + session cookies`.
149 |
150 | **Q10** : If the circuit breaker only works for `GET` request, how about the other?
151 | **A10** : Other `method` WILL NOT BE circuit breaked; that means all `POST`, `PUT`, `DELETE`, `OPTIONS`, `HEAD`, `PATCH` will be forwarded to your web-app normally.
152 |
153 | **Q11** : Could you make RETTER to use Redis for caching, instead of its own implementation?
154 | **A11** : Good idea, I bet you could help me, please take a look at the `Caching.go` and create Redis implementation. Don't forget to make a PR! Thanks.
155 |
--------------------------------------------------------------------------------
/Server.go:
--------------------------------------------------------------------------------
1 | /*-----------------------------------------------------------------------------------
2 | -- RETTER --
3 | -- Copyright (C) 2021 RETTER's Contributors --
4 | -- --
5 | -- This program is free software: you can redistribute it and/or modify --
6 | -- it under the terms of the GNU Affero General Public License as published --
7 | -- by the Free Software Foundation, either version 3 of the License, or --
8 | -- (at your option) any later version. --
9 | -- --
10 | -- This program is distributed in the hope that it will be useful, --
11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of --
12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --
13 | -- GNU Affero General Public License for more details. --
14 | -- --
15 | -- You should have received a copy of the GNU Affero General Public License --
16 | -- along with this program. If not, see . --
17 | -----------------------------------------------------------------------------------*/
18 |
19 | package main
20 |
21 | import (
22 | "bytes"
23 | "compress/gzip"
24 | "fmt"
25 | "github.com/hyperjumptech/jiffy"
26 | "github.com/hyperjumptech/retter/cache"
27 | "github.com/sirupsen/logrus"
28 | "github.com/sony/gobreaker"
29 | "io/ioutil"
30 | "net/http"
31 | "net/http/httptest"
32 | "net/url"
33 | "reflect"
34 | "runtime"
35 | "strings"
36 | "time"
37 | )
38 |
39 | const (
40 | // RetterStatusBackendTimeout is a custom HTTP response code if
41 | // the http client timed out while trying to call the backend server
42 | RetterStatusBackendTimeout = 1000
43 | )
44 |
45 | var (
46 | serverLog = logrus.WithFields(logrus.Fields{
47 | "module": "RetterHTTPHandler",
48 | "file": "Server.go",
49 | })
50 |
51 | lastKnownSuccess = make(map[string]HTTPTransaction)
52 |
53 | // ServerStarTime is a variable to store server start time.
54 | ServerStarTime time.Time
55 |
56 | // RequestCount to store total served request, with exception to /health health check path.
57 | RequestCount uint16
58 |
59 | // TotalResponseTime is a total response time in millisecond been recorded by this RETTER server
60 | TotalResponseTime uint64
61 |
62 | // SlowestResponseTime is the number of milliseconds of the slowest response time.
63 | SlowestResponseTime uint64
64 |
65 | // FastestResponseTime is the number of milliseconds of the fastest response time.
66 | FastestResponseTime uint64
67 | )
68 |
69 | func init() {
70 | ServerStarTime = time.Now()
71 | }
72 |
73 | // NewRetterHTTPHandler create new http.Handler for this Retter server
74 | func NewRetterHTTPHandler() http.Handler {
75 | return &RetterHTTPHandler{
76 | BackendBaseURL: Config.GetString(BackendURL),
77 | }
78 | }
79 |
80 | // RetterHTTPHandler an implementation of http.Handler
81 | type RetterHTTPHandler struct {
82 | BackendBaseURL string
83 | }
84 |
85 | // ServeHTTP is the handling method of incoming HTTP request and response
86 | func (rhh *RetterHTTPHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
87 | if strings.ToUpper(req.Method) == "GET" && req.URL.Path == "/health" {
88 | res.Header().Add("Content-Type", "application/json")
89 | res.WriteHeader(http.StatusOK)
90 |
91 | uptime := jiffy.DescribeDuration(time.Since(ServerStarTime), jiffy.NewWant())
92 | cacheCount := cache.CacheSize()
93 | timerCount := cache.TimerSize()
94 | breakerCount := len(PathBreakers)
95 |
96 | AverageResponseTime := float64(TotalResponseTime) / float64(RequestCount)
97 |
98 | memStat := &runtime.MemStats{}
99 | runtime.ReadMemStats(memStat)
100 |
101 | body := fmt.Sprintf("{\"status\":\"OK\", "+
102 | "\"server-uptime\": \"%s\", "+
103 | "\"cache-count\":%d, "+
104 | "\"ttl-timer-count\":%d, "+
105 | "\"breaker-count\":%d, "+
106 | "\"total-request-served\":%d, "+
107 | "\"total-response-time-ms\":%d, "+
108 | "\"average-response-time-ms\":%f,"+
109 | "\"slowest-response-time-ms\":%d,"+
110 | "\"fastest-response-time-ms\":%d,"+
111 | "\"memory\":{"+
112 | "\"sys-memory-byte\":%d, "+
113 | "\"alloc-memory-byte\":%d, "+
114 | "\"total-alloc-memory-byte\":%d"+
115 | "}}", uptime, cacheCount, timerCount, breakerCount,
116 | RequestCount, TotalResponseTime, AverageResponseTime,
117 | SlowestResponseTime, FastestResponseTime,
118 | memStat.Sys, memStat.Alloc, memStat.TotalAlloc)
119 | res.Write([]byte(body))
120 | return
121 | }
122 |
123 | RequestCount++
124 | StartTime := time.Now()
125 |
126 | defer func() {
127 | processDuration := time.Since(StartTime)
128 | msDuration := uint64(processDuration / time.Millisecond)
129 | TotalResponseTime += msDuration
130 | if reflect.ValueOf(SlowestResponseTime).IsZero() {
131 | SlowestResponseTime = msDuration
132 | } else {
133 | if SlowestResponseTime < msDuration {
134 | SlowestResponseTime = msDuration
135 | }
136 | }
137 | if reflect.ValueOf(FastestResponseTime).IsZero() {
138 | FastestResponseTime = msDuration
139 | } else {
140 | if FastestResponseTime > msDuration {
141 | FastestResponseTime = msDuration
142 | }
143 | }
144 | }()
145 |
146 | if strings.ToUpper(req.Method) != "GET" {
147 | recorder := httptest.NewRecorder()
148 | Execute(15*time.Second, rhh.BackendBaseURL, recorder, req)
149 | ReturnRecorder(req, recorder, res)
150 | return
151 | }
152 |
153 | breaker := GetBreakerForRequest(req)
154 | switch breaker.State() {
155 | case gobreaker.StateOpen:
156 | ServeFailedProcess(http.StatusBadGateway, res, req, breaker.State())
157 | default:
158 | l := serverLog.WithFields(logrus.Fields{
159 | "Method": req.Method,
160 | })
161 | key := getKey(req)
162 | timeStart := time.Now()
163 | val, err := breaker.Execute(func() (interface{}, error) {
164 | l.Debugf("PATH:%s RAWQUERY:%s", req.URL.Path, req.URL.RawQuery)
165 | recorder := httptest.NewRecorder()
166 | Execute(15*time.Second, rhh.BackendBaseURL, recorder, req)
167 | if recorder.Result().StatusCode >= 500 {
168 | return recorder, fmt.Errorf("response code %d", recorder.Result().StatusCode)
169 | }
170 | return recorder, nil
171 | })
172 | timeEnd := time.Now()
173 | recorder := val.(*httptest.ResponseRecorder)
174 | if err != nil {
175 | // logrus.Errorf("Error in breaker execution. got %s - code : %d", err.Error(), recorder.Result().StatusCode)
176 | ServeFailedProcess(recorder.Result().StatusCode, res, req, breaker.State())
177 | } else {
178 | if len(recorder.Header().Get("X-Circuit")) == 0 {
179 | recorder.Header().Set("X-Circuit", getGoBreakerString(breaker.State()))
180 | }
181 | if len(recorder.Header().Get("X-Retter")) == 0 {
182 | recorder.Header().Set("X-Retter", "backend")
183 | }
184 | ReturnRecorder(req, recorder, res)
185 | tx := &DefaultHTTPTransaction{
186 | TimeStart: timeStart,
187 | TimeEnd: timeEnd,
188 | Rec: req,
189 | Res: recorder,
190 | }
191 | cache.Store(key, tx, time.Duration(Config.GetInt(CacheTTL))*time.Second)
192 | lastKnownSuccess[key] = &DefaultHTTPTransaction{
193 | TimeStart: timeStart,
194 | TimeEnd: timeEnd,
195 | Rec: req,
196 | Res: recorder,
197 | }
198 | }
199 | }
200 | }
201 |
202 | func getGoBreakerString(state gobreaker.State) string {
203 | switch state {
204 | case gobreaker.StateOpen:
205 | return "OPEN"
206 | case gobreaker.StateHalfOpen:
207 | return "HALF-OPEN"
208 | default:
209 | return "CLOSED"
210 | }
211 | }
212 |
213 | // ServeFailedProcess will be invoked if a call to the Backend server
214 | // failed to be done due to timeout or 5xx errors.
215 | // It will try to look into cache for the cached successful response or
216 | // into history of last known response that was successful
217 | // If no cache or last successful response were found, it will then emit
218 | // 5xx error
219 | func ServeFailedProcess(erroneousResponseCode int, res http.ResponseWriter, req *http.Request, state gobreaker.State) {
220 | key := getKey(req)
221 | val := cache.Get(key, false, 0)
222 | if val == nil {
223 | if lastSuccessTx, ok := lastKnownSuccess[key]; ok {
224 | recorder := lastSuccessTx.Response()
225 |
226 | recorder.Header().Del("X-Circuit")
227 | recorder.Header().Set("X-Circuit", getGoBreakerString(state))
228 | recorder.Header().Del("X-Retter")
229 | recorder.Header().Set("X-Retter", "last-known-success")
230 | ReturnRecorder(req, recorder, res)
231 | serverLog.Debugf("returned from last success for key %s", key)
232 | } else {
233 | res.Header().Del("X-Circuit")
234 | res.Header().Set("X-Circuit", getGoBreakerString(state))
235 | res.Header().Del("X-Retter")
236 | res.Header().Set("X-Retter", "no-cache")
237 | res.WriteHeader(erroneousResponseCode)
238 | res.Write([]byte("Backend is down, please try again in few minutes"))
239 | }
240 | return
241 | }
242 | cachedTx := val.(HTTPTransaction)
243 |
244 | cachedTx.Response().Header().Del("X-Circuit")
245 | cachedTx.Response().Header().Set("X-Circuit", getGoBreakerString(state))
246 | cachedTx.Response().Header().Del("X-Retter")
247 | cachedTx.Response().Header().Set("X-Retter", "cache")
248 |
249 | ReturnRecorder(req, cachedTx.Response(), res)
250 | }
251 |
252 | // ReturnCompressedRecorder will return the recorder IF the rrequest is asking for compressed
253 | // Content-Encoding using Accept-Encoding: gzip
254 | func ReturnCompressedRecorder(recorder *httptest.ResponseRecorder, writer http.ResponseWriter) {
255 | bodyBytes := recorder.Body.Bytes()
256 |
257 | containsContentType := false
258 |
259 | // write the rest of the headers.
260 | for key, v := range recorder.Header() {
261 | for _, vv := range v {
262 | if strings.ToLower(key) == "content-type" {
263 | containsContentType = true
264 | logrus.Tracef("%s: %s already exist.", key, vv)
265 | }
266 | writer.Header().Set(key, vv)
267 | //logrus.Infof("GZIP Header %s : %s", key, vv)
268 | }
269 | }
270 |
271 | // If its non 2xx we dont compress it.
272 | if recorder.Result().StatusCode < 200 || recorder.Result().StatusCode >= 300 {
273 | // write the result.
274 | writer.WriteHeader(recorder.Result().StatusCode)
275 | // write the body after write header so golang http will not temper to the response code
276 | writer.Write(bodyBytes)
277 | return
278 | }
279 |
280 | if !containsContentType {
281 | ctype := http.DetectContentType(bodyBytes)
282 | logrus.Tracef("Content-Type not exist. Assigning one with Content-Type: %s. ", ctype)
283 | writer.Header().Set("Content-Type", ctype)
284 | }
285 |
286 | // if the body size is above minimum size zip them.
287 | if len(bodyBytes) > 300 {
288 |
289 | // add header for gzip content encoding
290 | writer.Header().Set("Content-Encoding", "gzip")
291 | // write the result.
292 | writer.WriteHeader(recorder.Code)
293 |
294 | // create empty byte buffer.
295 | buff := bytes.NewBuffer(make([]byte, 0))
296 |
297 | // Create new gzip writer to write gzip result into empty buffer.
298 | gw := gzip.NewWriter(buff)
299 |
300 | // Write the original content into gzip writer.
301 | written, err := gw.Write(bodyBytes)
302 | if err != nil {
303 | logrus.Errorf("Error while writing to gzip writer. got %v", err)
304 | }
305 | gw.Close()
306 | logrus.Tracef("Written into gzip writer %d bytes, yielding %d bytes.", written, len(buff.Bytes()))
307 |
308 | // Write the gzip result into response body.
309 | writer.Write(buff.Bytes())
310 |
311 | } else {
312 | // write the result.
313 | writer.WriteHeader(recorder.Code)
314 | // if the body size is bellow minimum size to zip, return them as is.
315 | writer.Write(bodyBytes)
316 | }
317 | }
318 |
319 | // ReturnRecorder will write recorded response into response writer
320 | func ReturnRecorder(request *http.Request, recorder *httptest.ResponseRecorder, writer http.ResponseWriter) {
321 |
322 | if strings.Contains(request.Header.Get("Accept-Encoding"), "gzip") {
323 | ReturnCompressedRecorder(recorder, writer)
324 | }
325 |
326 | // First we write the headers
327 | for k, v := range recorder.Header() {
328 | for _, val := range v {
329 | writer.Header().Add(k, val)
330 | //logrus.Infof("Header %s : %s", k, val)
331 | }
332 | }
333 | // Then we write the status code
334 | writer.WriteHeader(recorder.Result().StatusCode)
335 | // Them we write the body if exist
336 | body, err := ioutil.ReadAll(recorder.Body)
337 | if err != nil {
338 | writer.Write([]byte(err.Error()))
339 | writer.WriteHeader(http.StatusBadGateway)
340 | return
341 | }
342 | writer.Write(body)
343 | }
344 |
345 | // Execute will do the actual HTTP call forwarding to the backend server.
346 | // This function is called behind circuit breaker
347 | func Execute(timeout time.Duration, targetURL string, res http.ResponseWriter, req *http.Request) {
348 | start := time.Now()
349 | var urlToCall string
350 | if len(req.URL.RawQuery) > 0 {
351 | urlToCall = fmt.Sprintf("%s%s?%s", targetURL, req.URL.Path, req.URL.RawQuery)
352 | } else {
353 | urlToCall = fmt.Sprintf("%s%s", targetURL, req.URL.Path)
354 | }
355 | defer func() {
356 | duration := time.Since(start)
357 | serverLog.Tracef("[%s] %s took %d ms", req.Method, urlToCall, duration/time.Millisecond)
358 | }()
359 | request, err := http.NewRequest(req.Method, urlToCall, req.Body)
360 | if err != nil {
361 | res.Write([]byte(err.Error()))
362 | res.WriteHeader(http.StatusInternalServerError)
363 | return
364 | }
365 |
366 | // copy over the header, but exclude the accept-encoding gzip
367 | // as we will handle this separately
368 | for k, v := range req.Header {
369 | for _, hv := range v {
370 | if strings.ToLower(k) != "accept-encoding" && strings.Contains(strings.ToLower(hv), "gzip") {
371 | request.Header.Add(k, hv)
372 | }
373 | }
374 | }
375 |
376 | client := &http.Client{Timeout: timeout}
377 | response, err := client.Do(request)
378 | if err != nil {
379 | if urlErr, yes := err.(*url.Error); yes {
380 | if urlErr.Timeout() {
381 | res.Write([]byte(err.Error()))
382 | res.WriteHeader(RetterStatusBackendTimeout)
383 | return
384 | }
385 | }
386 | res.Write([]byte(err.Error()))
387 | res.WriteHeader(http.StatusBadGateway)
388 | return
389 | }
390 | defer response.Body.Close()
391 |
392 | // First we write the headers
393 | for k, v := range response.Header {
394 | for _, val := range v {
395 | res.Header().Add(k, val)
396 | }
397 | }
398 | // Then we write the status code
399 | res.WriteHeader(response.StatusCode)
400 | // Them we write the body if exist
401 | body, err := ioutil.ReadAll(response.Body)
402 | if err != nil {
403 | res.Write([]byte(err.Error()))
404 | res.WriteHeader(http.StatusBadGateway)
405 | return
406 | }
407 | res.Write(body)
408 | }
409 |
--------------------------------------------------------------------------------
/Server_test.go:
--------------------------------------------------------------------------------
1 | /*-----------------------------------------------------------------------------------
2 | -- RETTER --
3 | -- Copyright (C) 2021 RETTER's Contributors --
4 | -- --
5 | -- This program is free software: you can redistribute it and/or modify --
6 | -- it under the terms of the GNU Affero General Public License as published --
7 | -- by the Free Software Foundation, either version 3 of the License, or --
8 | -- (at your option) any later version. --
9 | -- --
10 | -- This program is distributed in the hope that it will be useful, --
11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of --
12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --
13 | -- GNU Affero General Public License for more details. --
14 | -- --
15 | -- You should have received a copy of the GNU Affero General Public License --
16 | -- along with this program. If not, see . --
17 | -----------------------------------------------------------------------------------*/
18 |
19 | package main
20 |
21 | import (
22 | "github.com/hyperjumptech/retter/cache"
23 | "github.com/hyperjumptech/retter/test"
24 | "go.uber.org/goleak"
25 | "net/http"
26 | "net/http/httptest"
27 | "testing"
28 | "time"
29 | )
30 |
31 | func TestRetterHealthCheck(t *testing.T) {
32 | handler := NewRetterHTTPHandler()
33 | resp := MakeCall("GET", "/health", t, handler)
34 | if resp.Result().StatusCode != http.StatusOK {
35 | t.Fatalf("Health check error")
36 | }
37 | }
38 |
39 | func TestNoCacheNoLastKnown(t *testing.T) {
40 | defer goleak.VerifyNone(t)
41 |
42 | cache.Clear()
43 |
44 | // lets start our dummy server
45 | // lets start our dummy server
46 | test.StartDummyServer("127.0.0.1:34251", false)
47 | t.Logf("Dummy server started")
48 | defer func() {
49 | test.StopDummyServer()
50 | t.Logf("Dummy server stoped")
51 | }()
52 |
53 | t.Logf("Making dummy server always fail")
54 | test.FailProbability(1.0)
55 |
56 | Config[BackendURL] = "http://127.0.0.1:34251"
57 | handler := NewRetterHTTPHandler()
58 |
59 | t.Logf("Making success call")
60 | resp := MakeCall("GET", "/test/newpath", t, handler)
61 |
62 | if resp.Result().StatusCode != http.StatusInternalServerError || resp.Header().Get("X-Retter") != "no-cache" || resp.Header().Get("X-Circuit") != "CLOSED" {
63 | t.Fatalf("Unexpected status code %d - retter header %s - circuit status %s", resp.Result().StatusCode, resp.Header().Get("X-Retter"), resp.Header().Get("X-Circuit"))
64 | }
65 | }
66 |
67 | func BenchmarkRetterHTTPHandler_ServeHTTP(b *testing.B) {
68 |
69 | Config[BackendURL] = "http://127.0.0.1:32415"
70 |
71 | handler := NewRetterHTTPHandler()
72 |
73 | for n := 0; n < b.N; n++ {
74 | r, err := http.NewRequest("GET", "http://localhost/some/path", nil)
75 | if err != nil {
76 | b.Fatalf(err.Error())
77 | }
78 | resp := httptest.NewRecorder()
79 | handler.ServeHTTP(resp, r)
80 | defer resp.Result().Body.Close()
81 |
82 | if resp.Result().StatusCode != http.StatusOK {
83 | b.Fatalf("unexpected response %d", resp.Result().StatusCode)
84 | }
85 | }
86 | }
87 |
88 | func TestRetterHTTPHandler_ServeHTTP(t *testing.T) {
89 | defer goleak.VerifyNone(t)
90 |
91 | cache.Clear()
92 |
93 | // lets start our dummy server
94 | test.StartDummyServer("127.0.0.1:34251", false)
95 | t.Logf("Dummy server started")
96 | defer func() {
97 | test.StopDummyServer()
98 | t.Logf("Dummy server stoped")
99 | }()
100 |
101 | Config[BackendURL] = "http://127.0.0.1:34251"
102 | handler := NewRetterHTTPHandler()
103 |
104 | t.Logf("Making dummy server always success")
105 | test.FailProbability(0.0)
106 |
107 | time.Sleep(100 * time.Millisecond)
108 |
109 | t.Logf("Making success call")
110 | resp := MakeCall("GET", "/test/path", t, handler)
111 | if resp.Result().StatusCode != 200 || resp.Header().Get("X-Retter") != "backend" || resp.Header().Get("X-Circuit") != "CLOSED" {
112 | t.Fatalf("Unexpected status code %d - retter header %s", resp.Result().StatusCode, resp.Header().Get("X-Retter"))
113 | }
114 |
115 | t.Logf("Making dummy server always fail")
116 | time.Sleep(100 * time.Millisecond)
117 | test.FailProbability(1.0)
118 |
119 | for i := 0; i < 3; i++ {
120 | t.Logf("Making fail #%d while breaker still close", i+1)
121 | resp := MakeCall("GET", "/test/path", t, handler)
122 | time.Sleep(100 * time.Millisecond)
123 | if resp.Result().StatusCode != http.StatusOK || resp.Header().Get("X-Retter") != "cache" || resp.Header().Get("X-Circuit") != "CLOSED" {
124 | t.Fatalf("Unexpected status code %d for fail #%d - retter header %s - circuit %s", resp.Result().StatusCode, i+1, resp.Header().Get("X-Retter"), resp.Header().Get("X-Circuit"))
125 | }
126 | }
127 |
128 | // circuit breaker should return with cached success
129 | t.Logf("Making fail call after circuit open")
130 | resp = MakeCall("GET", "/test/path", t, handler)
131 | if resp.Result().StatusCode != http.StatusOK || resp.Header().Get("X-Retter") != "cache" || resp.Header().Get("X-Circuit") != "OPEN" {
132 | t.Fatalf("Unexpected status code %d - retter header %s - circuit %s", resp.Result().StatusCode, resp.Header().Get("X-Retter"), resp.Header().Get("X-Circuit"))
133 | }
134 | }
135 |
136 | func MakeCall(method, path string, t *testing.T, handler http.Handler) *httptest.ResponseRecorder {
137 | r, err := http.NewRequest(method, "http://localhost"+path, nil)
138 | if err != nil {
139 | t.Fatalf(err.Error())
140 | return nil
141 | }
142 | r.Header.Add("Accept-Encoding", "gzip")
143 | resp := httptest.NewRecorder()
144 | handler.ServeHTTP(resp, r)
145 | defer resp.Result().Body.Close()
146 |
147 | t.Logf("----------")
148 | t.Logf("Call result for %s path %s is code %d", method, path, resp.Result().StatusCode)
149 | for k, v := range resp.Result().Header {
150 | for _, vv := range v {
151 | t.Logf(" %s : %s", k, vv)
152 | }
153 | }
154 |
155 | return resp
156 | }
157 |
--------------------------------------------------------------------------------
/Transaction.go:
--------------------------------------------------------------------------------
1 | /*-----------------------------------------------------------------------------------
2 | -- RETTER --
3 | -- Copyright (C) 2021 RETTER's Contributors --
4 | -- --
5 | -- This program is free software: you can redistribute it and/or modify --
6 | -- it under the terms of the GNU Affero General Public License as published --
7 | -- by the Free Software Foundation, either version 3 of the License, or --
8 | -- (at your option) any later version. --
9 | -- --
10 | -- This program is distributed in the hope that it will be useful, --
11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of --
12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --
13 | -- GNU Affero General Public License for more details. --
14 | -- --
15 | -- You should have received a copy of the GNU Affero General Public License --
16 | -- along with this program. If not, see . --
17 | -----------------------------------------------------------------------------------*/
18 |
19 | package main
20 |
21 | import (
22 | "fmt"
23 | "github.com/sirupsen/logrus"
24 | "net/http"
25 | "net/http/httptest"
26 | "regexp"
27 | "time"
28 | )
29 |
30 | var (
31 | cacheLog = logrus.WithFields(logrus.Fields{
32 | "module": "RetterHTTPHandler",
33 | "file": "Server.go",
34 | })
35 |
36 | // ErrNotFound is an error to be returned if a map do not contain specified key.
37 | ErrNotFound = fmt.Errorf("RecordNotFound")
38 | cookieRegex *regexp.Regexp
39 | )
40 |
41 | // HTTPTransaction is an interface to store information about HTTP request-response pair,
42 | // the HTTP transaction time and duration.
43 | type HTTPTransaction interface {
44 | TransactionBeginTime() time.Time
45 | TransactionDuration() time.Duration
46 | Request() *http.Request
47 | Response() *httptest.ResponseRecorder
48 | }
49 |
50 | // DefaultHTTPTransaction is the default implementation of HTTPTransaction
51 | type DefaultHTTPTransaction struct {
52 | TimeStart time.Time
53 | TimeEnd time.Time
54 | Rec *http.Request
55 | Res *httptest.ResponseRecorder
56 | }
57 |
58 | // TransactionBeginTime return the time when the transaction begins.
59 | func (tx *DefaultHTTPTransaction) TransactionBeginTime() time.Time {
60 | return tx.TimeStart
61 | }
62 |
63 | // TransactionDuration return the duration of transaction from request till response is captured.
64 | func (tx *DefaultHTTPTransaction) TransactionDuration() time.Duration {
65 | return tx.TimeEnd.Sub(tx.TimeStart)
66 | }
67 |
68 | // Request of the transaction
69 | func (tx *DefaultHTTPTransaction) Request() *http.Request {
70 | return tx.Rec
71 | }
72 |
73 | // Response of the transaction
74 | func (tx *DefaultHTTPTransaction) Response() *httptest.ResponseRecorder {
75 | return tx.Res
76 | }
77 |
78 | func init() {
79 | regex, err := regexp.Compile(`(ci_session|JSESSIONID|PHPSESSID)\s*=\s*[a-zA-Z0-9.\-]+`)
80 | if err != nil {
81 | panic(err)
82 | }
83 | cookieRegex = regex
84 | }
85 |
86 | func getKey(req *http.Request) string {
87 | completePath := req.URL.Path
88 | if Config.GetBoolean(CacheDetectQuery) && len(req.URL.RawQuery) > 0 {
89 | completePath = fmt.Sprintf("%s?%s", completePath, req.URL.RawQuery)
90 | }
91 | if Config.GetBoolean(CacheDetectSession) {
92 | cookieRow := req.Header.Get("Cookie")
93 | var cookie string
94 | if len(cookieRow) > 0 {
95 | cookie = cookieRegex.FindString(cookieRow)
96 | }
97 | if len(cookie) > 0 {
98 | completePath = fmt.Sprintf("%s:%s", cookie, completePath)
99 | }
100 | }
101 | return completePath
102 | }
103 |
--------------------------------------------------------------------------------
/cache/Caching.go:
--------------------------------------------------------------------------------
1 | /*-----------------------------------------------------------------------------------
2 | -- RETTER --
3 | -- Copyright (C) 2021 RETTER's Contributors --
4 | -- --
5 | -- This program is free software: you can redistribute it and/or modify --
6 | -- it under the terms of the GNU Affero General Public License as published --
7 | -- by the Free Software Foundation, either version 3 of the License, or --
8 | -- (at your option) any later version. --
9 | -- --
10 | -- This program is distributed in the hope that it will be useful, --
11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of --
12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --
13 | -- GNU Affero General Public License for more details. --
14 | -- --
15 | -- You should have received a copy of the GNU Affero General Public License --
16 | -- along with this program. If not, see . --
17 | -----------------------------------------------------------------------------------*/
18 |
19 | package cache
20 |
21 | import (
22 | "github.com/sirupsen/logrus"
23 | "sync"
24 | "time"
25 | )
26 |
27 | var (
28 | log = logrus.WithFields(logrus.Fields{
29 | "module": "Cache",
30 | "file": "cache/Caching.go",
31 | })
32 | cacheData = make(map[string]interface{})
33 | timerData = make(map[string]*time.Timer)
34 | mutext sync.Mutex
35 | )
36 |
37 | // CacheSize return the size of this cache
38 | func CacheSize() int {
39 | return len(cacheData)
40 | }
41 |
42 | // TimerSize return the size of timer
43 | func TimerSize() int {
44 | return len(timerData)
45 | }
46 |
47 | // Clear the cache
48 | func Clear() {
49 | mutext.Lock()
50 | defer mutext.Unlock()
51 |
52 | dataKeys := make([]string, len(cacheData))
53 | index := 0
54 | for k, _ := range cacheData {
55 | dataKeys[index] = k
56 | index++
57 | }
58 | for _, v := range dataKeys {
59 | delete(cacheData, v)
60 | }
61 |
62 | timerKeys := make([]string, len(timerData))
63 | index = 0
64 | for k, _ := range timerData {
65 | timerKeys[index] = k
66 | index++
67 | }
68 | for _, v := range timerKeys {
69 | delete(timerData, v)
70 | }
71 | }
72 |
73 | // Store a value into cache identified by the key. It also specify the TTL duration
74 | func Store(key string, value interface{}, ttl time.Duration) {
75 | mutext.Lock()
76 | defer mutext.Unlock()
77 |
78 | cacheData[key] = value
79 | if timer, ok := timerData[key]; ok {
80 | if !timer.Stop() {
81 | <-timer.C
82 | }
83 | timer.Reset(ttl)
84 | } else {
85 | timerData[key] = time.AfterFunc(ttl, func() {
86 | mutext.Lock()
87 | defer mutext.Unlock()
88 |
89 | delete(cacheData, key)
90 | delete(timerData, key)
91 | })
92 | }
93 | }
94 |
95 | // Get a value from cache identified by the key. It also specify new TTL duration if it need to reset
96 | func Get(key string, reset bool, ttl time.Duration) interface{} {
97 | mutext.Lock()
98 | defer mutext.Unlock()
99 |
100 | if value, ok := cacheData[key]; ok {
101 | if timer, ok := timerData[key]; ok && reset {
102 | if !timer.Stop() {
103 | <-timer.C
104 | }
105 | timer.Reset(ttl)
106 | }
107 | return value
108 | }
109 | return nil
110 | }
111 |
112 | // Remove a cache entry
113 | func Remove(key string) {
114 | mutext.Lock()
115 | defer mutext.Unlock()
116 |
117 | if timer, ok := timerData[key]; ok {
118 | if !timer.Stop() {
119 | <-timer.C
120 | }
121 | delete(timerData, key)
122 | }
123 | if _, ok := cacheData[key]; ok {
124 | delete(cacheData, key)
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/cache/Caching_test.go:
--------------------------------------------------------------------------------
1 | /*-----------------------------------------------------------------------------------
2 | -- RETTER --
3 | -- Copyright (C) 2021 RETTER's Contributors --
4 | -- --
5 | -- This program is free software: you can redistribute it and/or modify --
6 | -- it under the terms of the GNU Affero General Public License as published --
7 | -- by the Free Software Foundation, either version 3 of the License, or --
8 | -- (at your option) any later version. --
9 | -- --
10 | -- This program is distributed in the hope that it will be useful, --
11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of --
12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the --
13 | -- GNU Affero General Public License for more details. --
14 | -- --
15 | -- You should have received a copy of the GNU Affero General Public License --
16 | -- along with this program. If not, see . --
17 | -----------------------------------------------------------------------------------*/
18 |
19 | package cache
20 |
21 | import (
22 | "fmt"
23 | "go.uber.org/goleak"
24 | "testing"
25 | "time"
26 | )
27 |
28 | func TestCacheNoReset(t *testing.T) {
29 | defer goleak.VerifyNone(t)
30 |
31 | Store("akey", "avalue", 2*time.Second)
32 | val := Get("akey", false, 0)
33 | if val.(string) != "avalue" {
34 | t.Errorf("Expect \"avalue\" but \"%s\"", val.(string))
35 | }
36 | time.Sleep(1 * time.Second)
37 | val = Get("akey", false, 0)
38 | if val.(string) != "avalue" {
39 | t.Errorf("Expect \"avalue\" but \"%s\"", val.(string))
40 | }
41 | time.Sleep(2 * time.Second)
42 | val = Get("akey", false, 0)
43 | if val != nil {
44 | t.Errorf("Expect nil but \"%s\"", val.(string))
45 | }
46 | }
47 |
48 | func TestWriteReadRemove(t *testing.T) {
49 | defer goleak.VerifyNone(t)
50 |
51 | Clear()
52 |
53 | if CacheSize() != 0 {
54 | t.Errorf("Excpect cache size = 0 but %d", CacheSize())
55 | }
56 | if TimerSize() != 0 {
57 | t.Errorf("Excpect timer size = 0 but %d", TimerSize())
58 | }
59 |
60 | tmr := time.Now()
61 | for i := 0; i < 5000; i++ {
62 | k := fmt.Sprintf("K%d", i)
63 | v := fmt.Sprintf("V%d", i)
64 | Store(k, v, 2*time.Second)
65 | vget := Get(k, false, 0)
66 | if vget.(string) != v {
67 | t.Errorf("expect equals %s, but %s", v, vget)
68 | }
69 | if i >= 3000 {
70 | Remove(k)
71 | }
72 | }
73 | if (time.Since(tmr) / time.Millisecond) >= (2000 * time.Millisecond) {
74 | t.Fatalf("not enought ime to store get and remove")
75 | }
76 |
77 | time.Sleep(200 * time.Millisecond)
78 |
79 | if CacheSize() != TimerSize() {
80 | t.Fatalf("Cache %d != Timer %d", CacheSize(), TimerSize())
81 | }
82 | if CacheSize() != 3000 {
83 | t.Fatalf("Excpect cache size = 3000 but %d", CacheSize())
84 | }
85 | if TimerSize() != 3000 {
86 | t.Fatalf("Excpect timer size = 3000 but %d", TimerSize())
87 | }
88 |
89 | time.Sleep(2 * time.Second)
90 |
91 | if CacheSize() != TimerSize() {
92 | t.Fatalf("Cache %d != Timer %d", CacheSize(), TimerSize())
93 | }
94 | if CacheSize() != 0 {
95 | t.Fatalf("Excpect cache size = 3000 but %d", CacheSize())
96 | }
97 | if TimerSize() != 0 {
98 | t.Fatalf("Excpect timer size = 3000 but %d", TimerSize())
99 | }
100 | }
101 |
102 | func BenchmarkCache(b *testing.B) {
103 | for i := 0; i < b.N; i++ {
104 | k := fmt.Sprintf("K%d", i)
105 | v := fmt.Sprintf("V%d", i)
106 | Store(k, v, 2*time.Second)
107 | vget := Get(k, false, 0)
108 | if vget.(string) != v {
109 | b.Errorf("expect equals %s, but %s", v, vget)
110 | }
111 | if i >= 3000 {
112 | Remove(k)
113 | }
114 | }
115 | }
116 |
117 | func TestCacheWithReset(t *testing.T) {
118 | defer goleak.VerifyNone(t)
119 |
120 | Clear()
121 |
122 | if CacheSize() != 0 {
123 | t.Errorf("Excpect cache size = 0 but %d", CacheSize())
124 | }
125 | if TimerSize() != 0 {
126 | t.Errorf("Excpect timer size = 0 but %d", TimerSize())
127 | }
128 |
129 | Store("akey", "avalue", 1*time.Second)
130 | val := Get("akey", false, 0)
131 | if val.(string) != "avalue" {
132 | t.Errorf("Expect \"avalue\" but \"%s\"", val.(string))
133 | }
134 | time.Sleep(500 * time.Millisecond)
135 | val = Get("akey", true, 1*time.Second)
136 | if val.(string) != "avalue" {
137 | t.Errorf("Expect \"avalue\" but \"%s\"", val.(string))
138 | }
139 | time.Sleep(500 * time.Millisecond)
140 | val = Get("akey", true, 1*time.Second)
141 | if val.(string) != "avalue" {
142 | t.Errorf("Expect \"avalue\" but \"%s\"", val.(string))
143 | }
144 | if CacheSize() != 1 {
145 | t.Errorf("Excpect cache size = 1 but %d", CacheSize())
146 | }
147 | if TimerSize() != 1 {
148 | t.Errorf("Excpect timer size = 1 but %d", TimerSize())
149 | }
150 | time.Sleep(500 * time.Millisecond)
151 | val = Get("akey", false, 0)
152 | if val.(string) != "avalue" {
153 | t.Errorf("Expect \"avalue\" but \"%s\"", val.(string))
154 | }
155 | time.Sleep(600 * time.Millisecond)
156 | if CacheSize() != 0 {
157 | t.Errorf("Excpect cache size = 0 but %d", CacheSize())
158 | }
159 | if TimerSize() != 0 {
160 | t.Errorf("Excpect timer size = 0 but %d", TimerSize())
161 | }
162 | val = Get("akey", false, 0)
163 | if val != nil {
164 | t.Errorf("Expect nil but \"%s\"", val.(string))
165 | }
166 | }
167 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/hyperjumptech/retter
2 |
3 | go 1.14
4 |
5 | require (
6 | github.com/hyperjumptech/jiffy v1.0.0
7 | github.com/sirupsen/logrus v1.7.0
8 | github.com/sony/gobreaker v0.4.1
9 | github.com/spf13/viper v1.7.1
10 | go.uber.org/goleak v1.1.10
11 | golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 // indirect
12 | golang.org/x/tools v0.1.0 // indirect
13 | )
14 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
2 | cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
3 | cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU=
4 | cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU=
5 | cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY=
6 | cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc=
7 | cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0=
8 | cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
9 | cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE=
10 | cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk=
11 | cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I=
12 | cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw=
13 | dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
14 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
15 | github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
16 | github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
17 | github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
18 | github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
19 | github.com/antlr/antlr4 v0.0.0-20200124162019-2d7f727a00b7 h1:4IkFZAFQ87SeXXF6n+nwLyK2K+tcA5OojhBVf2lhg8g=
20 | github.com/antlr/antlr4 v0.0.0-20200124162019-2d7f727a00b7/go.mod h1:T7PbCXFs94rrTttyxjbyT5+/1V8T2TYDejxUfHJjw1Y=
21 | github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
22 | github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
23 | github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
24 | github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
25 | github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
26 | github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
27 | github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84=
28 | github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
29 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
30 | github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
31 | github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
32 | github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
33 | github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
34 | github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
35 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
36 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
37 | github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
38 | github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
39 | github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
40 | github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
41 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
42 | github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
43 | github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
44 | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
45 | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
46 | github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
47 | github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
48 | github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
49 | github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
50 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
51 | github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
52 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
53 | github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
54 | github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
55 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
56 | github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
57 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
58 | github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
59 | github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
60 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
61 | github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
62 | github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
63 | github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
64 | github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
65 | github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
66 | github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
67 | github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
68 | github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
69 | github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
70 | github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
71 | github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
72 | github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
73 | github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q=
74 | github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8=
75 | github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
76 | github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
77 | github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
78 | github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
79 | github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
80 | github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU=
81 | github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU=
82 | github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4=
83 | github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
84 | github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
85 | github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90=
86 | github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
87 | github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
88 | github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
89 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
90 | github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
91 | github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
92 | github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=
93 | github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
94 | github.com/hyperjumptech/jiffy v1.0.0 h1:hLfjgh4YQPYFanSmh06nfN2Es7BZ1WF2sQwmZIQ5tHQ=
95 | github.com/hyperjumptech/jiffy v1.0.0/go.mod h1:iFHHUap4onOTcvqBBU0iF33snPmqz4DSA/KgnBHG7dU=
96 | github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
97 | github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
98 | github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
99 | github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
100 | github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
101 | github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
102 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
103 | github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
104 | github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
105 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
106 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
107 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
108 | github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4=
109 | github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
110 | github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
111 | github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
112 | github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
113 | github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
114 | github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
115 | github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
116 | github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=
117 | github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=
118 | github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=
119 | github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
120 | github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
121 | github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
122 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
123 | github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
124 | github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
125 | github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
126 | github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
127 | github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
128 | github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
129 | github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
130 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
131 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
132 | github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
133 | github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
134 | github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
135 | github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
136 | github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
137 | github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
138 | github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
139 | github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
140 | github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
141 | github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
142 | github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
143 | github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
144 | github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
145 | github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
146 | github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
147 | github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM=
148 | github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
149 | github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
150 | github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
151 | github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
152 | github.com/sony/gobreaker v0.4.1 h1:oMnRNZXX5j85zso6xCPRNPtmAycat+WcoKbklScLDgQ=
153 | github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY=
154 | github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
155 | github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
156 | github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
157 | github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
158 | github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
159 | github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
160 | github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
161 | github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
162 | github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
163 | github.com/spf13/viper v1.7.1 h1:pM5oEahlgWv/WnHXpgbKz7iLIxRf65tye2Ci+XFK5sk=
164 | github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
165 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
166 | github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
167 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
168 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
169 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
170 | github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
171 | github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
172 | github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
173 | github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
174 | github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
175 | go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
176 | go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
177 | go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
178 | go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
179 | go.uber.org/goleak v1.1.10 h1:z+mqJhf6ss6BSfSM671tgKyZBFPTTJM+HLxnhPC3wu0=
180 | go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A=
181 | go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
182 | go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
183 | golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
184 | golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
185 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
186 | golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
187 | golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
188 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
189 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
190 | golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
191 | golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
192 | golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
193 | golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek=
194 | golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY=
195 | golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
196 | golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
197 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
198 | golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
199 | golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
200 | golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
201 | golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
202 | golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
203 | golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs=
204 | golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
205 | golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 h1:2M3HP5CCK1Si9FQhwnzYhXdG6DXeebvUHFpre8QvbyI=
206 | golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
207 | golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
208 | golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
209 | golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
210 | golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
211 | golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
212 | golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
213 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
214 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
215 | golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
216 | golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
217 | golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
218 | golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
219 | golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
220 | golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
221 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
222 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
223 | golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
224 | golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
225 | golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
226 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
227 | golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
228 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
229 | golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
230 | golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
231 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
232 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
233 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
234 | golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
235 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
236 | golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
237 | golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
238 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
239 | golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
240 | golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
241 | golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
242 | golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
243 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
244 | golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
245 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
246 | golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
247 | golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
248 | golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
249 | golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
250 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
251 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
252 | golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
253 | golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4 h1:myAQVi0cGEoqQVR5POX+8RR2mrocKqNN1hmeMqhX27k=
254 | golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
255 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
256 | golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
257 | golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
258 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
259 | golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
260 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
261 | golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
262 | golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
263 | golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
264 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
265 | golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
266 | golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
267 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
268 | golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
269 | golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
270 | golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
271 | golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
272 | golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
273 | golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
274 | golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
275 | golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
276 | golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
277 | golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
278 | golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
279 | golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
280 | golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc h1:NCy3Ohtk6Iny5V/reW2Ktypo4zIpWBdRJ1uFMjBxdg8=
281 | golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
282 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
283 | golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
284 | golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY=
285 | golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
286 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
287 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
288 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
289 | google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
290 | google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=
291 | google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
292 | google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
293 | google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
294 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
295 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
296 | google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
297 | google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0=
298 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
299 | google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
300 | google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
301 | google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
302 | google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
303 | google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
304 | google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
305 | google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8=
306 | google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
307 | google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
308 | google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
309 | google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
310 | gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
311 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
312 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
313 | gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
314 | gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno=
315 | gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
316 | gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
317 | gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
318 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
319 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
320 | gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I=
321 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
322 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
323 | honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
324 | honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
325 | honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
326 | rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
327 |
--------------------------------------------------------------------------------
/test/DummyHttpServer.go:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | import (
4 | "context"
5 | "fmt"
6 | "log"
7 | "math/rand"
8 | "net/http"
9 | "strconv"
10 | "strings"
11 | "time"
12 | )
13 |
14 | var (
15 | DummyServer *http.Server
16 | DummyServerAlive = false
17 | dummyHttpHandler = &DummyHttpHandler{
18 | fastest: 0,
19 | slowest: 1 * time.Second,
20 | failProbability: 0,
21 | }
22 | RequestCount = 0
23 | LongBody = strings.Repeat("This is a dummy line\n", 300)
24 | )
25 |
26 | func SetFastest(f, s time.Duration) {
27 | dummyHttpHandler.fastest = f
28 | dummyHttpHandler.slowest = s
29 | if dummyHttpHandler.fastest > dummyHttpHandler.slowest {
30 | t := dummyHttpHandler.fastest
31 | dummyHttpHandler.fastest = dummyHttpHandler.slowest
32 | dummyHttpHandler.slowest = t
33 | }
34 | }
35 |
36 | func FailProbability(f float64) {
37 | dummyHttpHandler.failProbability = f
38 | }
39 |
40 | func StartDummyServer(addr string, standalone bool) {
41 | if DummyServerAlive {
42 | return
43 | }
44 |
45 | DummyServer = &http.Server{
46 | Addr: addr,
47 | // Good practice to set timeouts to avoid Slowloris attacks.
48 | WriteTimeout: 1 * time.Minute,
49 | ReadTimeout: 1 * time.Minute,
50 | IdleTimeout: 1 * time.Minute,
51 | Handler: dummyHttpHandler, // Pass our instance of gorilla/mux in.
52 | }
53 |
54 | if standalone {
55 | fmt.Printf("Dummyserver is listening on : %s\n", DummyServer.Addr)
56 | if err := DummyServer.ListenAndServe(); err != nil {
57 | log.Println(err)
58 | }
59 | } else {
60 | go func() {
61 | fmt.Printf("Dummyserver is listening on : %s\n", DummyServer.Addr)
62 | DummyServerAlive = true
63 | if err := DummyServer.ListenAndServe(); err != nil {
64 | log.Println(err)
65 | }
66 | DummyServerAlive = false
67 | }()
68 | }
69 | }
70 |
71 | func StopDummyServer() {
72 | DummyServer.Shutdown(context.Background())
73 | }
74 |
75 | type DummyHttpHandler struct {
76 | fastest time.Duration
77 | slowest time.Duration
78 | failProbability float64
79 | }
80 |
81 | func (dhh *DummyHttpHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
82 | RequestCount++
83 | rc := RequestCount
84 | if req.URL.Path == "/set" {
85 | newFast := req.URL.Query().Get("f")
86 | newSlow := req.URL.Query().Get("s")
87 | newError := req.URL.Query().Get("e")
88 | if len(newFast) > 0 {
89 | nf, err := strconv.Atoi(newFast)
90 | if err == nil {
91 | dhh.fastest = time.Duration(nf) * time.Second
92 | }
93 | }
94 | if len(newSlow) > 0 {
95 | ns, err := strconv.Atoi(newSlow)
96 | if err == nil {
97 | dhh.slowest = time.Duration(ns) * time.Second
98 | }
99 | }
100 | if len(newError) > 0 {
101 | ne, err := strconv.ParseFloat(newError, 64)
102 | if err == nil {
103 | dhh.failProbability = ne
104 | }
105 | }
106 | if dhh.fastest > dhh.slowest {
107 | t := dhh.fastest
108 | dhh.fastest = dhh.slowest
109 | dhh.slowest = t
110 | }
111 | ToReturn := []byte(fmt.Sprintf("DONE %d \n %s", rc, LongBody))
112 | res.Header().Set("Content-Type", "text/plain")
113 | res.Header().Set("Content-Length", strconv.Itoa(len(ToReturn)))
114 | res.WriteHeader(http.StatusOK)
115 | res.Write(ToReturn)
116 | } else {
117 | dur := dhh.slowest - dhh.fastest
118 | sleep := dhh.fastest + time.Duration(rand.Int63n(int64(dur)))
119 | time.Sleep(sleep)
120 | res.Header().Set("Content-Type", "text/plain")
121 | failRandom := rand.Float64()
122 | if failRandom < dhh.failProbability {
123 | ToReturn := []byte(fmt.Sprintf("ERROR %d", rc))
124 | res.Header().Set("Content-Length", strconv.Itoa(len(ToReturn)))
125 | res.WriteHeader(http.StatusInternalServerError)
126 | res.Write(ToReturn)
127 | } else {
128 | ToReturn := []byte(fmt.Sprintf("DONE %d \n %s", rc, LongBody))
129 | res.Header().Set("Content-Length", strconv.Itoa(len(ToReturn)))
130 | res.WriteHeader(http.StatusOK)
131 | res.Write(ToReturn)
132 | }
133 | }
134 | }
135 |
--------------------------------------------------------------------------------