migrate from govendor to dep

This commit is contained in:
bergquist
2018-01-19 09:48:15 +01:00
parent 5bb22b836d
commit e023f79c5a
7349 changed files with 3153302 additions and 64302 deletions
+11
View File
@@ -0,0 +1,11 @@
*.out
*.test
*.xml
*.swp
.idea/
.tmp/
*.iml
*.cov
*.html
*.log
vendor/
+37
View File
@@ -0,0 +1,37 @@
Changes by Version
==================
1.3.1 (2018-01-12)
-------------------
- Add Gopkg.toml to allow using the lib with `dep`
1.3.0 (2018-01-08)
------------------
- Move rate limiter from client to jaeger-lib [#35](https://github.com/jaegertracing/jaeger-lib/pull/35)
1.2.1 (2017-11-14)
------------------
- *breaking* Change prometheus.New() to accept options instead of fixed arguments
1.2.0 (2017-11-12)
------------------
- Support Prometheus metrics directly [#29](https://github.com/jaegertracing/jaeger-lib/pull/29).
1.1.0 (2017-09-10)
------------------
- Re-releasing the project under Apache 2.0 license.
1.0.0 (2017-08-22)
------------------
- First semver release.
+163
View File
@@ -0,0 +1,163 @@
# How to Contribute to `jaeger-lib`
We'd love your help!
Jaeger is [Apache 2.0 licensed](LICENSE) and accepts contributions via GitHub
pull requests. This document outlines some of the conventions on development
workflow, commit message formatting, contact points and other resources to make
it easier to get your contribution accepted.
We gratefully welcome improvements to documentation as well as to code.
# Certificate of Origin
By contributing to this project you agree to the [Developer Certificate of
Origin](https://developercertificate.org/) (DCO). This document was created
by the Linux Kernel community and is a simple statement that you, as a
contributor, have the legal right to make the contribution. See the [DCO](DCO)
file for details.
## Getting Started
This library uses [glide](https://github.com/Masterminds/glide) to manage dependencies.
To get started, make sure you clone the Git repository into the correct location
`github.com/uber/jaeger-lib` relative to `$GOPATH`:
```
mkdir -p $GOPATH/src/github.com/uber
cd $GOPATH/src/github.com/uber
git clone git@github.com:jaegertracing/jaeger-lib.git jaeger-lib
cd jaeger-lib
```
Then install dependencies and run the tests:
```
git submodule update --init --recursive
glide install
make test
```
## Imports grouping
This projects follows the following pattern for grouping imports in Go files:
* imports from standard library
* imports from other projects
* imports from this `jaeger-lib` project
For example:
```go
import (
"fmt"
"go.uber.org/zap"
"github.com/uber/jaeger-lib/metrics"
)
```
## Making A Change
*Before making any significant changes, please [open an
issue](https://github.com/uber/jaeger-lib/issues).* Discussing your proposed
changes ahead of time will make the contribution process smooth for everyone.
Once we've discussed your changes and you've got your code ready, make sure
that tests are passing (`make test` or `make cover`) and open your PR. Your
pull request is most likely to be accepted if it:
* Includes tests for new functionality.
* Follows the guidelines in [Effective
Go](https://golang.org/doc/effective_go.html) and the [Go team's common code
review comments](https://github.com/golang/go/wiki/CodeReviewComments).
* Has a [good commit
message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html).
* Each commit must be signed by the author ([see below](#sign-your-work)).
## License
By contributing your code, you agree to license your contribution under the terms
of the [Apache License](LICENSE).
If you are adding a new file it should have a header like below. The easiest
way to add such header is to run `make fmt`.
```
// Copyright (c) 2017 The Jaeger Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
```
## Sign your work
The sign-off is a simple line at the end of the explanation for the
patch, which certifies that you wrote it or otherwise have the right to
pass it on as an open-source patch. The rules are pretty simple: if you
can certify the below (from
[developercertificate.org](http://developercertificate.org/)):
```
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
then you just add a line to every git commit message:
Signed-off-by: Joe Smith <joe@gmail.com>
using your real name (sorry, no pseudonyms or anonymous contributions.)
You can add the sign off when creating the git commit via `git commit -s`.
If you want this to be automatic you can set up some aliases:
```
git config --add alias.amend "commit -s --amend"
git config --add alias.c "commit -s"
```
+37
View File
@@ -0,0 +1,37 @@
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
+114
View File
@@ -0,0 +1,114 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
name = "github.com/VividCortex/gohistogram"
packages = ["."]
revision = "51564d9861991fb0ad0f531c99ef602d0f9866e6"
version = "v1.0.0"
[[projects]]
branch = "master"
name = "github.com/beorn7/perks"
packages = ["quantile"]
revision = "4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9"
[[projects]]
name = "github.com/codahale/hdrhistogram"
packages = ["."]
revision = "f8ad88b59a584afeee9d334eff879b104439117b"
[[projects]]
name = "github.com/davecgh/go-spew"
packages = ["spew"]
revision = "04cdfd42973bb9c8589fd6a731800cf222fde1a9"
[[projects]]
branch = "master"
name = "github.com/facebookgo/clock"
packages = ["."]
revision = "600d898af40aa09a7a93ecb9265d87b0504b6f03"
[[projects]]
name = "github.com/go-kit/kit"
packages = ["log","log/level","metrics","metrics/expvar","metrics/generic","metrics/influx","metrics/internal/lv","metrics/prometheus"]
revision = "a9ca6725cbbea455e61c6bc8a1ed28e81eb3493b"
version = "v0.5.0"
[[projects]]
name = "github.com/go-logfmt/logfmt"
packages = ["."]
revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5"
version = "v0.3.0"
[[projects]]
name = "github.com/go-stack/stack"
packages = ["."]
revision = "817915b46b97fd7bb80e8ab6b69f01a53ac3eebf"
version = "v1.6.0"
[[projects]]
name = "github.com/golang/protobuf"
packages = ["proto"]
revision = "7cc19b78d562895b13596ddce7aafb59dd789318"
[[projects]]
name = "github.com/influxdata/influxdb"
packages = ["client/v2","models","pkg/escape"]
revision = "f3f30726d822c4be8cd00137ba66b6e4fd68cca1"
[[projects]]
branch = "master"
name = "github.com/kr/logfmt"
packages = ["."]
revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0"
[[projects]]
branch = "master"
name = "github.com/matttproud/golang_protobuf_extensions"
packages = ["pbutil"]
revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c"
[[projects]]
name = "github.com/pmezard/go-difflib"
packages = ["difflib"]
revision = "d8ed2627bdf02c080bf22230dbb337003b7aba2d"
[[projects]]
name = "github.com/prometheus/client_golang"
packages = ["prometheus"]
revision = "c5b7fccd204277076155f10851dad72b76a49317"
version = "v0.8.0"
[[projects]]
name = "github.com/prometheus/client_model"
packages = ["go"]
revision = "6f3806018612930941127f2a7c6c453ba2c527d2"
[[projects]]
name = "github.com/prometheus/common"
packages = ["expfmt","internal/bitbucket.org/ww/goautoneg","model"]
revision = "49fee292b27bfff7f354ee0f64e1bc4850462edf"
[[projects]]
name = "github.com/prometheus/procfs"
packages = [".","xfs"]
revision = "a1dba9ce8baed984a2495b658c82687f8157b98f"
[[projects]]
name = "github.com/stretchr/testify"
packages = ["assert","require"]
revision = "05e8a0eda380579888eb53c394909df027f06991"
[[projects]]
name = "github.com/uber-go/tally"
packages = ["."]
revision = "be9e53c77349ae2dd4b8c03a6dc20ed9a88b9927"
version = "v3.2.0"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "6a38cb6e727212ac18ae744a1a3f17dcd79235e1947fac5f63b41d3162328e1f"
solver-name = "gps-cdcl"
solver-version = 1
+23
View File
@@ -0,0 +1,23 @@
[[constraint]]
name = "github.com/codahale/hdrhistogram"
[[constraint]]
name = "github.com/go-kit/kit"
version = "0.5.0"
[[constraint]]
name = "github.com/influxdata/influxdb"
[[constraint]]
name = "github.com/prometheus/client_golang"
version = "0.8.0"
[[constraint]]
name = "github.com/prometheus/client_model"
[[constraint]]
name = "github.com/stretchr/testify"
[[constraint]]
name = "github.com/uber-go/tally"
version = ">=2.1.0, <4.0.0"
+197 -17
View File
@@ -1,21 +1,201 @@
The MIT License (MIT)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) 2016 Uber Technologies, Inc.
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. Definitions.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+98
View File
@@ -0,0 +1,98 @@
PROJECT_ROOT=github.com/uber/jaeger-lib
PACKAGES := $(shell glide novendor | grep -v ./thrift-gen/...)
# all .go files that don't exist in hidden directories
ALL_SRC := $(shell find . -name "*.go" | grep -v -e vendor -e thrift-gen \
-e ".*/\..*" \
-e ".*/_.*" \
-e ".*/mocks.*")
export GO15VENDOREXPERIMENT=1
GOTEST=go test -v $(RACE)
GOLINT=golint
GOVET=go vet
GOFMT=gofmt
FMT_LOG=fmt.log
LINT_LOG=lint.log
THRIFT_VER=0.9.3
THRIFT_IMG=thrift:$(THRIFT_VER)
THRIFT=docker run -v "${PWD}:/data" $(THRIFT_IMG) thrift
THRIFT_GO_ARGS=thrift_import="github.com/apache/thrift/lib/go/thrift"
THRIFT_GEN_DIR=thrift-gen
PASS=$(shell printf "\033[32mPASS\033[0m")
FAIL=$(shell printf "\033[31mFAIL\033[0m")
COLORIZE=sed ''/PASS/s//$(PASS)/'' | sed ''/FAIL/s//$(FAIL)/''
.DEFAULT_GOAL := test-and-lint
.PHONY: test-and-lint
test-and-lint: test fmt lint
.PHONY: test
test:
$(GOTEST) $(PACKAGES) | $(COLORIZE)
.PHONY: fmt
fmt:
$(GOFMT) -e -s -l -w $(ALL_SRC)
./scripts/updateLicenses.sh
.PHONY: lint
lint:
$(GOVET) $(PACKAGES)
@cat /dev/null > $(LINT_LOG)
@$(foreach pkg, $(PACKAGES), $(GOLINT) $(pkg) | grep -v crossdock/thrift >> $(LINT_LOG) || true;)
@[ ! -s "$(LINT_LOG)" ] || (echo "Lint Failures" | cat - $(LINT_LOG) && false)
@$(GOFMT) -e -s -l $(ALL_SRC) > $(FMT_LOG)
@./scripts/updateLicenses.sh >> $(FMT_LOG)
@[ ! -s "$(FMT_LOG)" ] || (echo "go fmt or license check failures, run 'make fmt'" | cat - $(FMT_LOG) && false)
.PHONY: install
install:
glide --version || go get github.com/Masterminds/glide
ifeq ($(USE_DEP),true)
dep ensure
dep status
else
glide install
endif
.PHONY: cover
cover:
./scripts/cover.sh $(shell go list $(PACKAGES))
go tool cover -html=cover.out -o cover.html
idl-submodule:
git submodule init
git submodule update
thrift-image:
$(THRIFT) -version
.PHONY: install-dep-ci
install-dep-ci:
- curl -L -s https://github.com/golang/dep/releases/download/v0.3.2/dep-linux-amd64 -o $$GOPATH/bin/dep
- chmod +x $$GOPATH/bin/dep
.PHONY: install-ci
install-ci: install
go get github.com/wadey/gocovmerge
go get github.com/mattn/goveralls
go get golang.org/x/tools/cmd/cover
go get github.com/golang/lint/golint
.PHONY: test-ci
test-ci:
./scripts/cover.sh $(shell go list $(PACKAGES))
make lint
.PHONY: test-only-ci
test-only-ci:
go test -cover $(PACKAGES)
make lint
+22
View File
@@ -0,0 +1,22 @@
[![GoDoc][doc-img]][doc] [![Build Status][ci-img]][ci] [![Coverage Status][cov-img]][cov]
# jaeger-lib
A collection of shared infrastructure libraries used by different
components of [Jaeger](https://github.com/uber/jaeger) backend and [jaeger-client-go](https://github.com/uber/jaeger-client-go).
This library is *not intended to be used standalone*, and provides *no guarantees of backwards compatibility*.
The library's import path is `github.com/uber/jaeger-lib`.
## How to Contribute
Please see [CONTRIBUTING.md](CONTRIBUTING.md).
[doc-img]: https://godoc.org/github.com/uber/jaeger-lib?status.svg
[doc]: https://godoc.org/github.com/uber/jaeger-lib
[ci-img]: https://travis-ci.org/jaegertracing/jaeger-lib.svg?branch=master
[ci]: https://travis-ci.org/jaegertracing/jaeger-lib
[cov-img]: https://coveralls.io/repos/jaegertracing/jaeger-lib/badge.svg?branch=master&service=github
[cov]: https://coveralls.io/github/jaegertracing/jaeger-lib?branch=master
+64
View File
@@ -0,0 +1,64 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package xkit
import (
"fmt"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
)
// LoggerOption sets a parameter for the Logger.
type LoggerOption func(*Logger)
// MessageKey sets the key for the actual log message. By default, it's "msg".
func MessageKey(key string) LoggerOption {
return func(l *Logger) { l.messageKey = key }
}
// Logger wraps a go-kit logger instance in a Jaeger client compatible one.
type Logger struct {
infoLogger log.Logger
errorLogger log.Logger
messageKey string
}
// NewLogger creates a new Jaeger client logger from a go-kit one.
func NewLogger(kitlogger log.Logger, options ...LoggerOption) *Logger {
logger := &Logger{
infoLogger: level.Info(kitlogger),
errorLogger: level.Error(kitlogger),
messageKey: "msg",
}
for _, option := range options {
option(logger)
}
return logger
}
// Error implements the github.com/uber/jaeger-client-go/log.Logger interface.
func (l *Logger) Error(msg string) {
l.errorLogger.Log(l.messageKey, msg)
}
// Infof implements the github.com/uber/jaeger-client-go/log.Logger interface.
func (l *Logger) Infof(msg string, args ...interface{}) {
l.infoLogger.Log(l.messageKey, fmt.Sprintf(msg, args...))
}
+78
View File
@@ -0,0 +1,78 @@
hash: 8ca2ebd4305a4aaead18ee8cc5a84da42e95c202d53c1bd78d11436aeb8be8e4
updated: 2017-09-20T01:48:48.588894144+02:00
imports:
- name: github.com/beorn7/perks
version: 4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9
subpackages:
- quantile
- name: github.com/codahale/hdrhistogram
version: f8ad88b59a584afeee9d334eff879b104439117b
- name: github.com/davecgh/go-spew
version: 04cdfd42973bb9c8589fd6a731800cf222fde1a9
subpackages:
- spew
- name: github.com/facebookgo/clock
version: 600d898af40aa09a7a93ecb9265d87b0504b6f03
- name: github.com/go-kit/kit
version: a9ca6725cbbea455e61c6bc8a1ed28e81eb3493b
subpackages:
- log
- log/level
- metrics
- metrics/expvar
- metrics/generic
- metrics/influx
- metrics/internal/lv
- metrics/prometheus
- name: github.com/go-logfmt/logfmt
version: 390ab7935ee28ec6b286364bba9b4dd6410cb3d5
- name: github.com/go-stack/stack
version: 817915b46b97fd7bb80e8ab6b69f01a53ac3eebf
- name: github.com/golang/protobuf
version: 7cc19b78d562895b13596ddce7aafb59dd789318
subpackages:
- proto
- name: github.com/influxdata/influxdb
version: f3f30726d822c4be8cd00137ba66b6e4fd68cca1
subpackages:
- client/v2
- models
- pkg/escape
- name: github.com/kr/logfmt
version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0
- name: github.com/matttproud/golang_protobuf_extensions
version: c12348ce28de40eed0136aa2b644d0ee0650e56c
subpackages:
- pbutil
- name: github.com/pmezard/go-difflib
version: d8ed2627bdf02c080bf22230dbb337003b7aba2d
subpackages:
- difflib
- name: github.com/prometheus/client_golang
version: c5b7fccd204277076155f10851dad72b76a49317
subpackages:
- prometheus
- name: github.com/prometheus/client_model
version: 6f3806018612930941127f2a7c6c453ba2c527d2
subpackages:
- go
- name: github.com/prometheus/common
version: 49fee292b27bfff7f354ee0f64e1bc4850462edf
subpackages:
- expfmt
- internal/bitbucket.org/ww/goautoneg
- model
- name: github.com/prometheus/procfs
version: a1dba9ce8baed984a2495b658c82687f8157b98f
subpackages:
- xfs
- name: github.com/stretchr/testify
version: 05e8a0eda380579888eb53c394909df027f06991
subpackages:
- assert
- require
- name: github.com/uber-go/tally
version: be9e53c77349ae2dd4b8c03a6dc20ed9a88b9927
- name: github.com/VividCortex/gohistogram
version: 51564d9861991fb0ad0f531c99ef602d0f9866e6
testImports: []
+13
View File
@@ -0,0 +1,13 @@
package: github.com/uber/jaeger-lib
import:
- package: github.com/codahale/hdrhistogram
- package: github.com/go-kit/kit
version: v0.5.0
subpackages:
- metrics/influx
- package: github.com/uber-go/tally
version: '>= 2.1.0, < 4'
- package: github.com/prometheus/client_golang
version: v0.8.0
testImport:
- package: github.com/stretchr/testify
+9 -15
View File
@@ -1,22 +1,16 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// http://www.apache.org/licenses/LICENSE-2.0
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metrics
+9 -15
View File
@@ -1,22 +1,16 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// http://www.apache.org/licenses/LICENSE-2.0
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metrics
+9 -15
View File
@@ -1,22 +1,16 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// http://www.apache.org/licenses/LICENSE-2.0
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metrics
+50
View File
@@ -0,0 +1,50 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package expvar
import (
"github.com/go-kit/kit/metrics"
"github.com/go-kit/kit/metrics/expvar"
"github.com/uber/jaeger-lib/metrics/go-kit"
)
// NewFactory creates a new metrics factory using go-kit expvar package.
// buckets is the number of buckets to be used in histograms.
func NewFactory(buckets int) xkit.Factory {
return factory{
buckets: buckets,
}
}
type factory struct {
buckets int
}
func (f factory) Counter(name string) metrics.Counter {
return expvar.NewCounter(name)
}
func (f factory) Histogram(name string) metrics.Histogram {
return expvar.NewHistogram(name, f.buckets)
}
func (f factory) Gauge(name string) metrics.Gauge {
return expvar.NewGauge(name)
}
func (f factory) Capabilities() xkit.Capabilities {
return xkit.Capabilities{Tagging: false}
}
+161
View File
@@ -0,0 +1,161 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package xkit
import (
kit "github.com/go-kit/kit/metrics"
"github.com/uber/jaeger-lib/metrics"
)
// Factory provides a unified interface for creating named metrics
// from various go-kit metrics implementations.
type Factory interface {
Counter(name string) kit.Counter
Gauge(name string) kit.Gauge
Histogram(name string) kit.Histogram
Capabilities() Capabilities
}
// Capabilities describes capabilities of a specific metrics factory.
type Capabilities struct {
// Tagging indicates whether the factory has the capability for tagged metrics
Tagging bool
}
// FactoryOption is a function that adjusts some parameters of the factory.
type FactoryOption func(*factory)
// Wrap is used to create an adapter from xkit.Factory to metrics.Factory.
func Wrap(namespace string, f Factory, options ...FactoryOption) metrics.Factory {
factory := &factory{
scope: namespace,
factory: f,
scopeSep: ".",
tagsSep: ".",
tagKVSep: "_",
}
for i := range options {
options[i](factory)
}
return factory
}
// ScopeSeparator returns an option that overrides default scope separator.
func ScopeSeparator(scopeSep string) FactoryOption {
return func(f *factory) {
f.scopeSep = scopeSep
}
}
// TagsSeparator returns an option that overrides default tags separator.
func TagsSeparator(tagsSep string) FactoryOption {
return func(f *factory) {
f.tagsSep = tagsSep
}
}
type factory struct {
scope string
tags map[string]string
factory Factory
scopeSep string
tagsSep string
tagKVSep string
}
func (f *factory) subScope(name string) string {
if f.scope == "" {
return name
}
if name == "" {
return f.scope
}
return f.scope + f.scopeSep + name
}
// nameAndTagsList returns a name and tags list for the new metrics.
// The name is a concatenation of nom and the current factory scope.
// The tags list is a flattened list of passed tags merged with factory tags.
// If the underlying factory does not support tags, then the tags are
// transformed into a string and appended to the name.
func (f *factory) nameAndTagsList(nom string, tags map[string]string) (name string, tagsList []string) {
mergedTags := f.mergeTags(tags)
name = f.subScope(nom)
tagsList = f.tagsList(mergedTags)
if len(tagsList) == 0 || f.factory.Capabilities().Tagging {
return
}
name = metrics.GetKey(name, mergedTags, f.tagsSep, f.tagKVSep)
tagsList = nil
return
}
func (f *factory) Counter(name string, tags map[string]string) metrics.Counter {
name, tagsList := f.nameAndTagsList(name, tags)
counter := f.factory.Counter(name)
if len(tagsList) > 0 {
counter = counter.With(tagsList...)
}
return NewCounter(counter)
}
func (f *factory) Timer(name string, tags map[string]string) metrics.Timer {
name, tagsList := f.nameAndTagsList(name, tags)
hist := f.factory.Histogram(name)
if len(tagsList) > 0 {
hist = hist.With(tagsList...)
}
return NewTimer(hist)
}
func (f *factory) Gauge(name string, tags map[string]string) metrics.Gauge {
name, tagsList := f.nameAndTagsList(name, tags)
gauge := f.factory.Gauge(name)
if len(tagsList) > 0 {
gauge = gauge.With(tagsList...)
}
return NewGauge(gauge)
}
func (f *factory) Namespace(name string, tags map[string]string) metrics.Factory {
return &factory{
scope: f.subScope(name),
tags: f.mergeTags(tags),
factory: f.factory,
scopeSep: f.scopeSep,
tagsSep: f.tagsSep,
tagKVSep: f.tagKVSep,
}
}
func (f *factory) tagsList(a map[string]string) []string {
ret := make([]string, 0, 2*len(a))
for k, v := range a {
ret = append(ret, k, v)
}
return ret
}
func (f *factory) mergeTags(tags map[string]string) map[string]string {
ret := make(map[string]string, len(f.tags)+len(tags))
for k, v := range f.tags {
ret[k] = v
}
for k, v := range tags {
ret[k] = v
}
return ret
}
+49
View File
@@ -0,0 +1,49 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package influx
import (
"github.com/go-kit/kit/metrics"
"github.com/go-kit/kit/metrics/influx"
"github.com/uber/jaeger-lib/metrics/go-kit"
)
// NewFactory creates a new metrics factory using go-kit influx package.
func NewFactory(client *influx.Influx) xkit.Factory {
return factory{
client: client,
}
}
type factory struct {
client *influx.Influx
}
func (f factory) Counter(name string) metrics.Counter {
return f.client.NewCounter(name)
}
func (f factory) Histogram(name string) metrics.Histogram {
return f.client.NewHistogram(name)
}
func (f factory) Gauge(name string) metrics.Gauge {
return f.client.NewGauge(name)
}
func (f factory) Capabilities() xkit.Capabilities {
return xkit.Capabilities{Tagging: true}
}
+66
View File
@@ -0,0 +1,66 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package xkit
import (
"time"
kit "github.com/go-kit/kit/metrics"
)
// Counter is an adapter from go-kit Counter to jaeger-lib Counter
type Counter struct {
counter kit.Counter
}
// NewCounter creates a new Counter
func NewCounter(counter kit.Counter) *Counter {
return &Counter{counter: counter}
}
// Inc adds the given value to the counter.
func (c *Counter) Inc(delta int64) {
c.counter.Add(float64(delta))
}
// Gauge is an adapter from go-kit Gauge to jaeger-lib Gauge
type Gauge struct {
gauge kit.Gauge
}
// NewGauge creates a new Gauge
func NewGauge(gauge kit.Gauge) *Gauge {
return &Gauge{gauge: gauge}
}
// Update the gauge to the value passed in.
func (g *Gauge) Update(value int64) {
g.gauge.Set(float64(value))
}
// Timer is an adapter from go-kit Histogram to jaeger-lib Timer
type Timer struct {
hist kit.Histogram
}
// NewTimer creates a new Timer
func NewTimer(hist kit.Histogram) *Timer {
return &Timer{hist: hist}
}
// Record saves the time passed in.
func (t *Timer) Record(delta time.Duration) {
t.hist.Observe(delta.Seconds())
}
+82
View File
@@ -0,0 +1,82 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package prometheus
import (
"strings"
"github.com/go-kit/kit/metrics"
kitprom "github.com/go-kit/kit/metrics/prometheus"
"github.com/prometheus/client_golang/prometheus"
"github.com/uber/jaeger-lib/metrics/go-kit"
)
var normalizer = strings.NewReplacer(
".", "_",
"-", "_",
)
// NewFactory creates a new metrics factory using go-kit prometheus package.
// buckets define the buckets into which histogram observations are counted.
// If buckets == nil, the default value prometheus.DefBuckets is used.
func NewFactory(namespace, subsystem string, buckets []float64) xkit.Factory {
return &factory{
namespace: namespace,
subsystem: subsystem,
buckets: buckets,
}
}
type factory struct {
namespace string
subsystem string
buckets []float64
}
func (f *factory) Counter(name string) metrics.Counter {
opts := prometheus.CounterOpts{
Namespace: f.namespace,
Subsystem: f.subsystem,
Name: normalizer.Replace(name),
Help: name,
}
return kitprom.NewCounterFrom(opts, nil)
}
func (f *factory) Histogram(name string) metrics.Histogram {
opts := prometheus.HistogramOpts{
Namespace: f.namespace,
Subsystem: f.subsystem,
Name: normalizer.Replace(name),
Help: name,
Buckets: f.buckets,
}
return kitprom.NewHistogramFrom(opts, nil)
}
func (f *factory) Gauge(name string) metrics.Gauge {
opts := prometheus.GaugeOpts{
Namespace: f.namespace,
Subsystem: f.subsystem,
Name: normalizer.Replace(name),
Help: name,
}
return kitprom.NewGaugeFrom(opts, nil)
}
func (f *factory) Capabilities() xkit.Capabilities {
return xkit.Capabilities{Tagging: true}
}
+9 -15
View File
@@ -1,22 +1,16 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// http://www.apache.org/licenses/LICENSE-2.0
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metrics
+9 -15
View File
@@ -1,22 +1,16 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// http://www.apache.org/licenses/LICENSE-2.0
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metrics
+107
View File
@@ -0,0 +1,107 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package multi
import (
"time"
"github.com/uber/jaeger-lib/metrics"
)
// Factory is a metrics factory that dispatches to multiple metrics backends.
type Factory struct {
factories []metrics.Factory
}
// New creates a new multi.Factory that will dispatch to multiple metrics backends.
func New(factories ...metrics.Factory) *Factory {
return &Factory{
factories: factories,
}
}
type counter struct {
counters []metrics.Counter
}
func (c *counter) Inc(delta int64) {
for _, counter := range c.counters {
counter.Inc(delta)
}
}
// Counter implements metrics.Factory interface
func (f *Factory) Counter(name string, tags map[string]string) metrics.Counter {
counter := &counter{
counters: make([]metrics.Counter, len(f.factories)),
}
for i, factory := range f.factories {
counter.counters[i] = factory.Counter(name, tags)
}
return counter
}
type timer struct {
timers []metrics.Timer
}
func (t *timer) Record(delta time.Duration) {
for _, timer := range t.timers {
timer.Record(delta)
}
}
// Timer implements metrics.Factory interface
func (f *Factory) Timer(name string, tags map[string]string) metrics.Timer {
timer := &timer{
timers: make([]metrics.Timer, len(f.factories)),
}
for i, factory := range f.factories {
timer.timers[i] = factory.Timer(name, tags)
}
return timer
}
type gauge struct {
gauges []metrics.Gauge
}
func (t *gauge) Update(value int64) {
for _, gauge := range t.gauges {
gauge.Update(value)
}
}
// Gauge implements metrics.Factory interface
func (f *Factory) Gauge(name string, tags map[string]string) metrics.Gauge {
gauge := &gauge{
gauges: make([]metrics.Gauge, len(f.factories)),
}
for i, factory := range f.factories {
gauge.gauges[i] = factory.Gauge(name, tags)
}
return gauge
}
// Namespace implements metrics.Factory interface
func (f *Factory) Namespace(name string, tags map[string]string) metrics.Factory {
newFactory := &Factory{
factories: make([]metrics.Factory, len(f.factories)),
}
for i, factory := range f.factories {
newFactory.factories[i] = factory.Namespace(name, tags)
}
return newFactory
}
+85
View File
@@ -0,0 +1,85 @@
// Copyright (c) 2017 The Jaeger Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package prometheus
import (
"strings"
"sync"
"github.com/prometheus/client_golang/prometheus"
)
type vectorCache struct {
registerer prometheus.Registerer
lock sync.Mutex
cVecs map[string]*prometheus.CounterVec
gVecs map[string]*prometheus.GaugeVec
hVecs map[string]*prometheus.HistogramVec
}
func newVectorCache(registerer prometheus.Registerer) *vectorCache {
return &vectorCache{
registerer: registerer,
cVecs: make(map[string]*prometheus.CounterVec),
gVecs: make(map[string]*prometheus.GaugeVec),
hVecs: make(map[string]*prometheus.HistogramVec),
}
}
func (c *vectorCache) getOrMakeCounterVec(opts prometheus.CounterOpts, labelNames []string) *prometheus.CounterVec {
c.lock.Lock()
defer c.lock.Unlock()
cacheKey := c.getCacheKey(opts.Name, labelNames)
cv, cvExists := c.cVecs[cacheKey]
if !cvExists {
cv = prometheus.NewCounterVec(opts, labelNames)
c.registerer.MustRegister(cv)
c.cVecs[cacheKey] = cv
}
return cv
}
func (c *vectorCache) getOrMakeGaugeVec(opts prometheus.GaugeOpts, labelNames []string) *prometheus.GaugeVec {
c.lock.Lock()
defer c.lock.Unlock()
cacheKey := c.getCacheKey(opts.Name, labelNames)
gv, gvExists := c.gVecs[cacheKey]
if !gvExists {
gv = prometheus.NewGaugeVec(opts, labelNames)
c.registerer.MustRegister(gv)
c.gVecs[cacheKey] = gv
}
return gv
}
func (c *vectorCache) getOrMakeHistogramVec(opts prometheus.HistogramOpts, labelNames []string) *prometheus.HistogramVec {
c.lock.Lock()
defer c.lock.Unlock()
cacheKey := c.getCacheKey(opts.Name, labelNames)
hv, hvExists := c.hVecs[cacheKey]
if !hvExists {
hv = prometheus.NewHistogramVec(opts, labelNames)
c.registerer.MustRegister(hv)
c.hVecs[cacheKey] = hv
}
return hv
}
func (c *vectorCache) getCacheKey(name string, labels []string) string {
return strings.Join(append([]string{name}, labels...), "||")
}
+216
View File
@@ -0,0 +1,216 @@
// Copyright (c) 2017 The Jaeger Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package prometheus
import (
"sort"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/uber/jaeger-lib/metrics"
)
// Factory implements metrics.Factory backed by Prometheus registry.
type Factory struct {
scope string
tags map[string]string
cache *vectorCache
buckets []float64
normalizer *strings.Replacer
}
type options struct {
registerer prometheus.Registerer
buckets []float64
}
// Option is a function that sets some option for the Factory constructor.
type Option func(*options)
// WithRegisterer returns an option that sets the registerer.
// If not used we fallback to prometheus.DefaultRegisterer.
func WithRegisterer(registerer prometheus.Registerer) Option {
return func(opts *options) {
opts.registerer = registerer
}
}
// WithBuckets returns an option that sets the default buckets for histogram.
// If not used, we fallback to default Prometheus buckets.
func WithBuckets(buckets []float64) Option {
return func(opts *options) {
opts.buckets = buckets
}
}
func applyOptions(opts []Option) *options {
options := new(options)
for _, o := range opts {
o(options)
}
if options.registerer == nil {
options.registerer = prometheus.DefaultRegisterer
}
return options
}
// New creates a Factory backed by Prometheus registry.
// Typically the first argument should be prometheus.DefaultRegisterer.
//
// Parameter buckets defines the buckets into which Timer observations are counted.
// Each element in the slice is the upper inclusive bound of a bucket. The
// values must be sorted in strictly increasing order. There is no need
// to add a highest bucket with +Inf bound, it will be added
// implicitly. The default value is prometheus.DefBuckets.
func New(opts ...Option) *Factory {
options := applyOptions(opts)
return newFactory(
&Factory{ // dummy struct to be discarded
cache: newVectorCache(options.registerer),
buckets: options.buckets,
normalizer: strings.NewReplacer(".", "_", "-", "_"),
},
"", // scope
nil) // tags
}
func newFactory(parent *Factory, scope string, tags map[string]string) *Factory {
return &Factory{
cache: parent.cache,
buckets: parent.buckets,
normalizer: parent.normalizer,
scope: scope,
tags: tags,
}
}
// Counter implements Counter of metrics.Factory.
func (f *Factory) Counter(name string, tags map[string]string) metrics.Counter {
name = f.subScope(name)
tags = f.mergeTags(tags)
labelNames := f.tagNames(tags)
opts := prometheus.CounterOpts{
Name: name,
Help: name,
}
cv := f.cache.getOrMakeCounterVec(opts, labelNames)
return &counter{
counter: cv.WithLabelValues(f.tagsAsLabelValues(labelNames, tags)...),
}
}
// Gauge implements Gauge of metrics.Factory.
func (f *Factory) Gauge(name string, tags map[string]string) metrics.Gauge {
name = f.subScope(name)
tags = f.mergeTags(tags)
labelNames := f.tagNames(tags)
opts := prometheus.GaugeOpts{
Name: name,
Help: name,
}
gv := f.cache.getOrMakeGaugeVec(opts, labelNames)
return &gauge{
gauge: gv.WithLabelValues(f.tagsAsLabelValues(labelNames, tags)...),
}
}
// Timer implements Timer of metrics.Factory.
func (f *Factory) Timer(name string, tags map[string]string) metrics.Timer {
name = f.subScope(name)
tags = f.mergeTags(tags)
labelNames := f.tagNames(tags)
opts := prometheus.HistogramOpts{
Name: name,
Help: name,
Buckets: f.buckets,
}
hv := f.cache.getOrMakeHistogramVec(opts, labelNames)
return &timer{
histogram: hv.WithLabelValues(f.tagsAsLabelValues(labelNames, tags)...),
}
}
// Namespace implements Namespace of metrics.Factory.
func (f *Factory) Namespace(name string, tags map[string]string) metrics.Factory {
return newFactory(f, f.subScope(name), f.mergeTags(tags))
}
type counter struct {
counter prometheus.Counter
}
func (c *counter) Inc(v int64) {
c.counter.Add(float64(v))
}
type gauge struct {
gauge prometheus.Gauge
}
func (g *gauge) Update(v int64) {
g.gauge.Set(float64(v))
}
type timer struct {
histogram prometheus.Histogram
}
func (t *timer) Record(v time.Duration) {
t.histogram.Observe(float64(v.Nanoseconds()) / float64(time.Second/time.Nanosecond))
}
func (f *Factory) subScope(name string) string {
if f.scope == "" {
return f.normalize(name)
}
if name == "" {
return f.normalize(f.scope)
}
return f.normalize(f.scope + ":" + name)
}
func (f *Factory) normalize(v string) string {
return f.normalizer.Replace(v)
}
func (f *Factory) mergeTags(tags map[string]string) map[string]string {
ret := make(map[string]string, len(f.tags)+len(tags))
for k, v := range f.tags {
ret[k] = v
}
for k, v := range tags {
ret[k] = v
}
return ret
}
func (f *Factory) tagNames(tags map[string]string) []string {
ret := make([]string, 0, len(tags))
for k := range tags {
ret = append(ret, k)
}
sort.Strings(ret)
return ret
}
func (f *Factory) tagsAsLabelValues(labels []string, tags map[string]string) []string {
ret := make([]string, 0, len(tags))
for _, l := range labels {
ret = append(ret, tags[l])
}
return ret
}
+9 -15
View File
@@ -1,22 +1,16 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// http://www.apache.org/licenses/LICENSE-2.0
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metrics
+63
View File
@@ -0,0 +1,63 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tally
import (
"github.com/uber-go/tally"
"github.com/uber/jaeger-lib/metrics"
)
// Wrap takes a tally Scope and returns jaeger-lib metrics.Factory.
func Wrap(scope tally.Scope) metrics.Factory {
return &factory{
tally: scope,
}
}
// TODO implement support for tags if tally.Scope does not support them
type factory struct {
tally tally.Scope
}
func (f *factory) Counter(name string, tags map[string]string) metrics.Counter {
scope := f.tally
if len(tags) > 0 {
scope = scope.Tagged(tags)
}
return NewCounter(scope.Counter(name))
}
func (f *factory) Gauge(name string, tags map[string]string) metrics.Gauge {
scope := f.tally
if len(tags) > 0 {
scope = scope.Tagged(tags)
}
return NewGauge(scope.Gauge(name))
}
func (f *factory) Timer(name string, tags map[string]string) metrics.Timer {
scope := f.tally
if len(tags) > 0 {
scope = scope.Tagged(tags)
}
return NewTimer(scope.Timer(name))
}
func (f *factory) Namespace(name string, tags map[string]string) metrics.Factory {
return &factory{
tally: f.tally.SubScope(name).Tagged(tags),
}
}
+66
View File
@@ -0,0 +1,66 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tally
import (
"time"
"github.com/uber-go/tally"
)
// Counter is an adapter from go-tally Counter to jaeger-lib Counter
type Counter struct {
counter tally.Counter
}
// NewCounter creates a new Counter
func NewCounter(counter tally.Counter) *Counter {
return &Counter{counter: counter}
}
// Inc adds the given value to the counter.
func (c *Counter) Inc(delta int64) {
c.counter.Inc(delta)
}
// Gauge is an adapter from go-tally Gauge to jaeger-lib Gauge
type Gauge struct {
gauge tally.Gauge
}
// NewGauge creates a new Gauge
func NewGauge(gauge tally.Gauge) *Gauge {
return &Gauge{gauge: gauge}
}
// Update the gauge to the value passed in.
func (g *Gauge) Update(value int64) {
g.gauge.Update(float64(value))
}
// Timer is an adapter from go-tally Histogram to jaeger-lib Timer
type Timer struct {
timer tally.Timer
}
// NewTimer creates a new Timer
func NewTimer(timer tally.Timer) *Timer {
return &Timer{timer: timer}
}
// Record saves the time passed in.
func (t *Timer) Record(delta time.Duration) {
t.timer.Record(delta)
}
+55
View File
@@ -0,0 +1,55 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package testutils
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/uber/jaeger-lib/metrics"
)
// ExpectedMetric contains metrics under test.
type ExpectedMetric struct {
Name string
Tags map[string]string
Value int
}
// TODO do something similar for Timers
// AssertCounterMetrics checks if counter metrics exist.
func AssertCounterMetrics(t *testing.T, f *metrics.LocalFactory, expectedMetrics ...ExpectedMetric) {
counters, _ := f.Snapshot()
assertMetrics(t, counters, expectedMetrics...)
}
// AssertGaugeMetrics checks if gauge metrics exist.
func AssertGaugeMetrics(t *testing.T, f *metrics.LocalFactory, expectedMetrics ...ExpectedMetric) {
_, gauges := f.Snapshot()
assertMetrics(t, gauges, expectedMetrics...)
}
func assertMetrics(t *testing.T, actualMetrics map[string]int64, expectedMetrics ...ExpectedMetric) {
for _, expected := range expectedMetrics {
key := metrics.GetKey(expected.Name, expected.Tags, "|", "=")
assert.EqualValues(t,
expected.Value,
actualMetrics[key],
"expected metric name: %s, tags: %+v", expected.Name, expected.Tags,
)
}
}
+9 -15
View File
@@ -1,22 +1,16 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// http://www.apache.org/licenses/LICENSE-2.0
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metrics
+24
View File
@@ -0,0 +1,24 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sample
import (
"fmt"
)
// SayHello is a sample function
func SayHello() {
fmt.Println("Hello, playground")
}
+64
View File
@@ -0,0 +1,64 @@
#!/bin/bash
set -e
COVER=.cover
ROOT_PKG=github.com/uber/jaeger-lib/
if [[ -d "$COVER" ]]; then
rm -rf "$COVER"
fi
mkdir -p "$COVER"
# If a package directory has a .nocover file, don't count it when calculating
# coverage.
filter=""
for pkg in "$@"; do
if [[ -f "$GOPATH/src/$pkg/.nocover" ]]; then
if [[ -n "$filter" ]]; then
filter="$filter, "
fi
filter="\"$pkg\": true"
fi
done
if [[ "$filter" = "" ]]; then
# make up some name to avoid breaking jq's select(in({}))
filter='"no-filter": true'
fi
i=0
for pkg in "$@"; do
i=$((i + 1))
extracoverpkg=""
if [[ -f "$GOPATH/src/$pkg/.extra-coverpkg" ]]; then
extracoverpkg=$( \
sed -e "s|^|$pkg/|g" < "$GOPATH/src/$pkg/.extra-coverpkg" \
| tr '\n' ',')
fi
coverpkg=$(go list -json "$pkg" | jq -r '
.Deps
| . + ["'"$pkg"'"]
| map
( select(startswith("'"$ROOT_PKG"'"))
| select(contains("/vendor/") | not)
| select(in({'"$filter"'}) | not)
)
| join(",")
')
if [[ -n "$extracoverpkg" ]]; then
coverpkg="$extracoverpkg$coverpkg"
fi
args=""
if [[ -n "$coverpkg" ]]; then
args="-coverprofile $COVER/cover.${i}.out" # -coverpkg $coverpkg"
fi
echo go test -v -race "$pkg"
go test $args -v -race "$pkg"
done
gocovmerge "$COVER"/*.out > cover.out
+6
View File
@@ -0,0 +1,6 @@
#!/bin/bash
set -e
set -x
python scripts/updateLicense.py $(go list -json $(glide nv) | jq -r '.Dir + "/" + (.GoFiles | .[])')
+77
View File
@@ -0,0 +1,77 @@
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"sync"
"time"
)
// RateLimiter is a filter used to check if a message that is worth itemCost units is within the rate limits.
type RateLimiter interface {
CheckCredit(itemCost float64) bool
}
type rateLimiter struct {
sync.Mutex
creditsPerSecond float64
balance float64
maxBalance float64
lastTick time.Time
timeNow func() time.Time
}
// NewRateLimiter creates a new rate limiter based on leaky bucket algorithm, formulated in terms of a
// credits balance that is replenished every time CheckCredit() method is called (tick) by the amount proportional
// to the time elapsed since the last tick, up to max of creditsPerSecond. A call to CheckCredit() takes a cost
// of an item we want to pay with the balance. If the balance exceeds the cost of the item, the item is "purchased"
// and the balance reduced, indicated by returned value of true. Otherwise the balance is unchanged and return false.
//
// This can be used to limit a rate of messages emitted by a service by instantiating the Rate Limiter with the
// max number of messages a service is allowed to emit per second, and calling CheckCredit(1.0) for each message
// to determine if the message is within the rate limit.
//
// It can also be used to limit the rate of traffic in bytes, by setting creditsPerSecond to desired throughput
// as bytes/second, and calling CheckCredit() with the actual message size.
func NewRateLimiter(creditsPerSecond, maxBalance float64) RateLimiter {
return &rateLimiter{
creditsPerSecond: creditsPerSecond,
balance: maxBalance,
maxBalance: maxBalance,
lastTick: time.Now(),
timeNow: time.Now}
}
func (b *rateLimiter) CheckCredit(itemCost float64) bool {
b.Lock()
defer b.Unlock()
// calculate how much time passed since the last tick, and update current tick
currentTime := b.timeNow()
elapsedTime := currentTime.Sub(b.lastTick)
b.lastTick = currentTime
// calculate how much credit have we accumulated since the last tick
b.balance += elapsedTime.Seconds() * b.creditsPerSecond
if b.balance > b.maxBalance {
b.balance = b.maxBalance
}
// if we have enough credits to pay for current item, then reduce balance and allow
if b.balance >= itemCost {
b.balance -= itemCost
return true
}
return false
}