Compare commits
20 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
948d223b82 | ||
7a656210f7 | |||
|
cf310138cb | ||
05740fa208 | |||
b7f2d44c6f | |||
734bf3cb75 | |||
5dba791473 | |||
ffa3e0753f | |||
434c2e31a3 | |||
09528896b1 | |||
c798df52a1 | |||
|
118517eb72 | ||
3d0ec5c6ea | |||
1862ee5380 | |||
4cd610a474 | |||
b64ea019ed | |||
4cdca6cd83 | |||
bd8eca5f5e | |||
04d67b540c | |||
44b2cb9572 |
8
.github/ISSUE_TEMPLATE/bug_report.md
vendored
8
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: For reporting bugs in go-micro
|
||||
about: For reporting bugs in micro
|
||||
title: "[BUG]"
|
||||
labels: ''
|
||||
assignees: ''
|
||||
@@ -16,9 +16,3 @@ assignees: ''
|
||||
**How to reproduce the bug:**
|
||||
|
||||
If possible, please include a minimal code snippet here.
|
||||
|
||||
**Environment:**
|
||||
Go Version: please paste `go version` output here
|
||||
```
|
||||
please paste `go env` output here
|
||||
```
|
||||
|
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: Feature request / Enhancement
|
||||
about: If you have a need not served by go-micro
|
||||
about: If you have a need not served by micro
|
||||
title: "[FEATURE]"
|
||||
labels: ''
|
||||
assignees: ''
|
||||
@@ -14,4 +14,4 @@ A clear and concise description of what the problem is. Ex. I'm always frustrate
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
Add any other context or screenshots about the feature request here.
|
10
.github/ISSUE_TEMPLATE/question.md
vendored
10
.github/ISSUE_TEMPLATE/question.md
vendored
@@ -1,14 +1,8 @@
|
||||
---
|
||||
name: Question
|
||||
about: Ask a question about go-micro
|
||||
about: Ask a question about micro
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
Before asking, please check if your question has already been answered:
|
||||
|
||||
1. Check the documentation - https://micro.mu/docs/
|
||||
2. Check the examples and plugins - https://github.com/micro/examples & https://github.com/micro/go-plugins
|
||||
3. Search existing issues
|
||||
---
|
28
.github/autoapprove.yml
vendored
Normal file
28
.github/autoapprove.yml
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
name: "autoapprove"
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [assigned, opened, synchronize, reopened]
|
||||
workflow_run:
|
||||
workflows: ["prbuild"]
|
||||
types:
|
||||
- completed
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
autoapprove:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: approve
|
||||
run: [ "curl -o tea https://dl.gitea.com/tea/main/tea-main-linux-amd64",
|
||||
"chmod +x ./tea",
|
||||
"./tea login add --name unistack --token ${{ secrets.GITHUB_TOKEN }} --url https://git.unistack.org",
|
||||
"./tea pr --repo ${{ github.event.repository.name }}"
|
||||
]
|
||||
if: github.actor == 'vtolstov'
|
||||
id: approve
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
19
.github/dependabot.yml
vendored
19
.github/dependabot.yml
vendored
@@ -1,19 +0,0 @@
|
||||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
|
||||
# Maintain dependencies for GitHub Actions
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
|
||||
# Maintain dependencies for Golang
|
||||
- package-ecosystem: "gomod"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
20
.github/workflows/autoapprove.yml
vendored
20
.github/workflows/autoapprove.yml
vendored
@@ -1,20 +0,0 @@
|
||||
name: "autoapprove"
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [assigned, opened, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
autoapprove:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: approve
|
||||
uses: hmarr/auto-approve-action@v3
|
||||
if: github.actor == 'vtolstov' || github.actor == 'dependabot[bot]'
|
||||
id: approve
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
21
.github/workflows/automerge.yml
vendored
21
.github/workflows/automerge.yml
vendored
@@ -1,21 +0,0 @@
|
||||
name: "automerge"
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [assigned, opened, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
automerge:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.actor == 'vtolstov'
|
||||
steps:
|
||||
- name: merge
|
||||
id: merge
|
||||
run: gh pr merge --auto --merge "$PR_URL"
|
||||
env:
|
||||
PR_URL: ${{github.event.pull_request.html_url}}
|
||||
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
47
.github/workflows/build.yml
vendored
47
.github/workflows/build.yml
vendored
@@ -1,47 +0,0 @@
|
||||
name: build
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- v3
|
||||
jobs:
|
||||
test:
|
||||
name: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: setup
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: 1.17
|
||||
- name: checkout
|
||||
uses: actions/checkout@v3
|
||||
- name: cache
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: ${{ runner.os }}-go-
|
||||
- name: deps
|
||||
run: go get -v -t -d ./...
|
||||
- name: test
|
||||
env:
|
||||
INTEGRATION_TESTS: yes
|
||||
run: go test -mod readonly -v ./...
|
||||
lint:
|
||||
name: lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v3
|
||||
- name: lint
|
||||
uses: golangci/golangci-lint-action@v3.4.0
|
||||
continue-on-error: true
|
||||
with:
|
||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||
version: v1.30
|
||||
# Optional: working directory, useful for monorepos
|
||||
# working-directory: somedir
|
||||
# Optional: golangci-lint command line arguments.
|
||||
# args: --issues-exit-code=0
|
||||
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
||||
# only-new-issues: true
|
78
.github/workflows/codeql-analysis.yml
vendored
78
.github/workflows/codeql-analysis.yml
vendored
@@ -1,78 +0,0 @@
|
||||
# For most projects, this workflow file will not need changing; you simply need
|
||||
# to commit it to your repository.
|
||||
#
|
||||
# You may wish to alter this file to override the set of languages analyzed,
|
||||
# or to provide custom queries or build logic.
|
||||
#
|
||||
# ******** NOTE ********
|
||||
# We have attempted to detect the languages in your repository. Please check
|
||||
# the `language` matrix defined below to confirm you have the correct set of
|
||||
# supported CodeQL languages.
|
||||
#
|
||||
name: "codeql"
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["prbuild"]
|
||||
types:
|
||||
- completed
|
||||
push:
|
||||
branches: [ master, v3 ]
|
||||
pull_request:
|
||||
# The branches below must be a subset of the branches above
|
||||
branches: [ master, v3 ]
|
||||
schedule:
|
||||
- cron: '34 1 * * 0'
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: analyze
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
security-events: write
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: [ 'go' ]
|
||||
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
|
||||
# Learn more:
|
||||
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
|
||||
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v3
|
||||
- name: setup
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: 1.17
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: init
|
||||
uses: github/codeql-action/init@v2
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
# By default, queries listed here will override any specified in a config file.
|
||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||
# queries: ./path/to/local/query, your-org/your-repo/queries@main
|
||||
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: autobuild
|
||||
uses: github/codeql-action/autobuild@v2
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 https://git.io/JvXDl
|
||||
|
||||
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
|
||||
# and modify them (or add more) to build your code if your project
|
||||
# uses a compiled language
|
||||
|
||||
#- run: |
|
||||
# make bootstrap
|
||||
# make release
|
||||
|
||||
- name: analyze
|
||||
uses: github/codeql-action/analyze@v2
|
27
.github/workflows/dependabot-automerge.yml
vendored
27
.github/workflows/dependabot-automerge.yml
vendored
@@ -1,27 +0,0 @@
|
||||
name: "dependabot-automerge"
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [assigned, opened, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
automerge:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.actor == 'dependabot[bot]'
|
||||
steps:
|
||||
- name: metadata
|
||||
id: metadata
|
||||
uses: dependabot/fetch-metadata@v1.3.6
|
||||
with:
|
||||
github-token: "${{ secrets.TOKEN }}"
|
||||
- name: merge
|
||||
id: merge
|
||||
if: ${{contains(steps.metadata.outputs.dependency-names, 'go.unistack.org')}}
|
||||
run: gh pr merge --auto --merge "$PR_URL"
|
||||
env:
|
||||
PR_URL: ${{github.event.pull_request.html_url}}
|
||||
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
53
.github/workflows/job_coverage.yml
vendored
Normal file
53
.github/workflows/job_coverage.yml
vendored
Normal file
@@ -0,0 +1,53 @@
|
||||
name: coverage
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, v3, v4 ]
|
||||
paths-ignore:
|
||||
- '.github/**'
|
||||
- '.gitea/**'
|
||||
pull_request:
|
||||
branches: [ main, v3, v4 ]
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
if: github.server_url != 'https://github.com'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
filter: 'blob:none'
|
||||
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
cache-dependency-path: "**/*.sum"
|
||||
go-version: 'stable'
|
||||
|
||||
- name: test coverage
|
||||
run: |
|
||||
go test -v -cover ./... -covermode=count -coverprofile coverage.out -coverpkg ./...
|
||||
go tool cover -func coverage.out -o coverage.out
|
||||
|
||||
- name: coverage badge
|
||||
uses: tj-actions/coverage-badge-go@v2
|
||||
with:
|
||||
green: 80
|
||||
filename: coverage.out
|
||||
|
||||
- uses: stefanzweifel/git-auto-commit-action@v4
|
||||
name: autocommit
|
||||
with:
|
||||
commit_message: Apply Code Coverage Badge
|
||||
skip_fetch: false
|
||||
skip_checkout: false
|
||||
file_pattern: ./README.md
|
||||
|
||||
- name: push
|
||||
if: steps.auto-commit-action.outputs.changes_detected == 'true'
|
||||
uses: ad-m/github-push-action@master
|
||||
with:
|
||||
github_token: ${{ github.token }}
|
||||
branch: ${{ github.ref }}
|
29
.github/workflows/job_lint.yml
vendored
Normal file
29
.github/workflows/job_lint.yml
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
name: lint
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
branches: [ master, v3, v4 ]
|
||||
paths-ignore:
|
||||
- '.github/**'
|
||||
- '.gitea/**'
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
filter: 'blob:none'
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
cache-dependency-path: "**/*.sum"
|
||||
go-version: 'stable'
|
||||
- name: setup deps
|
||||
run: go get -v ./...
|
||||
- name: run lint
|
||||
uses: golangci/golangci-lint-action@v6
|
||||
with:
|
||||
version: 'latest'
|
94
.github/workflows/job_sync.yml
vendored
Normal file
94
.github/workflows/job_sync.yml
vendored
Normal file
@@ -0,0 +1,94 @@
|
||||
name: sync
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '*/5 * * * *'
|
||||
# Allows you to run this workflow manually from the Actions tab
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
if: github.server_url != 'https://github.com'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: init
|
||||
run: |
|
||||
git config --global user.email "vtolstov <vtolstov@users.noreply.github.com>"
|
||||
git config --global user.name "github-actions[bot]"
|
||||
echo "machine git.unistack.org login vtolstov password ${{ secrets.TOKEN_GITEA }}" >> /root/.netrc
|
||||
echo "machine github.com login vtolstov password ${{ secrets.TOKEN_GITHUB }}" >> /root/.netrc
|
||||
|
||||
- name: check master
|
||||
id: check_master
|
||||
run: |
|
||||
src_hash=$(git ls-remote https://github.com/${GITHUB_REPOSITORY} refs/heads/master | cut -f1)
|
||||
dst_hash=$(git ls-remote ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} refs/heads/master | cut -f1)
|
||||
echo "src_hash=$src_hash"
|
||||
echo "dst_hash=$dst_hash"
|
||||
if [ "$src_hash" != "$dst_hash" ]; then
|
||||
echo "sync_needed=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "sync_needed=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: sync master
|
||||
if: steps.check_master.outputs.sync_needed == 'true'
|
||||
run: |
|
||||
git clone --filter=blob:none --filter=tree:0 --branch master --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
|
||||
cd repo
|
||||
git remote add --no-tags --fetch --track master upstream https://github.com/${GITHUB_REPOSITORY}
|
||||
git pull --rebase upstream master
|
||||
git push upstream master --progress
|
||||
git push origin master --progress
|
||||
cd ../
|
||||
rm -rf repo
|
||||
|
||||
- name: check v3
|
||||
id: check_v3
|
||||
run: |
|
||||
src_hash=$(git ls-remote https://github.com/${GITHUB_REPOSITORY} refs/heads/v3 | cut -f1)
|
||||
dst_hash=$(git ls-remote ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} refs/heads/v3 | cut -f1)
|
||||
echo "src_hash=$src_hash"
|
||||
echo "dst_hash=$dst_hash"
|
||||
if [ "$src_hash" != "$dst_hash" ]; then
|
||||
echo "sync_needed=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "sync_needed=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: sync v3
|
||||
if: steps.check_v3.outputs.sync_needed == 'true'
|
||||
run: |
|
||||
git clone --filter=blob:none --filter=tree:0 --branch v3 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
|
||||
cd repo
|
||||
git remote add --no-tags --fetch --track v3 upstream https://github.com/${GITHUB_REPOSITORY}
|
||||
git pull --rebase upstream v3
|
||||
git push upstream v3 --progress
|
||||
git push origin v3 --progress
|
||||
cd ../
|
||||
rm -rf repo
|
||||
|
||||
- name: check v4
|
||||
id: check_v4
|
||||
run: |
|
||||
src_hash=$(git ls-remote https://github.com/${GITHUB_REPOSITORY} refs/heads/v4 | cut -f1)
|
||||
dst_hash=$(git ls-remote ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} refs/heads/v4 | cut -f1)
|
||||
echo "src_hash=$src_hash"
|
||||
echo "dst_hash=$dst_hash"
|
||||
if [ "$src_hash" != "$dst_hash" ]; then
|
||||
echo "sync_needed=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "sync_needed=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: sync v4
|
||||
if: steps.check_v4.outputs.sync_needed == 'true'
|
||||
run: |
|
||||
git clone --filter=blob:none --filter=tree:0 --branch v4 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
|
||||
cd repo
|
||||
git remote add --no-tags --fetch --track v4 upstream https://github.com/${GITHUB_REPOSITORY}
|
||||
git pull --rebase upstream v4
|
||||
git push upstream v4 --progress
|
||||
git push origin v4 --progress
|
||||
cd ../
|
||||
rm -rf repo
|
31
.github/workflows/job_test.yml
vendored
Normal file
31
.github/workflows/job_test.yml
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
name: test
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
branches: [ master, v3, v4 ]
|
||||
push:
|
||||
branches: [ master, v3, v4 ]
|
||||
paths-ignore:
|
||||
- '.github/**'
|
||||
- '.gitea/**'
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
filter: 'blob:none'
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
cache-dependency-path: "**/*.sum"
|
||||
go-version: 'stable'
|
||||
- name: setup deps
|
||||
run: go get -v ./...
|
||||
- name: run test
|
||||
env:
|
||||
INTEGRATION_TESTS: yes
|
||||
run: go test -mod readonly -v ./...
|
50
.github/workflows/job_tests.yml
vendored
Normal file
50
.github/workflows/job_tests.yml
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
name: test
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, reopened, synchronize]
|
||||
branches: [ master, v3, v4 ]
|
||||
push:
|
||||
branches: [ master, v3, v4 ]
|
||||
paths-ignore:
|
||||
- '.github/**'
|
||||
- '.gitea/**'
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
filter: 'blob:none'
|
||||
- name: checkout tests
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: master
|
||||
filter: 'blob:none'
|
||||
repository: unistack-org/micro-tests
|
||||
path: micro-tests
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
cache-dependency-path: "**/*.sum"
|
||||
go-version: 'stable'
|
||||
- name: setup go work
|
||||
env:
|
||||
GOWORK: ${{ github.workspace }}/go.work
|
||||
run: |
|
||||
go work init
|
||||
go work use .
|
||||
go work use micro-tests
|
||||
- name: setup deps
|
||||
env:
|
||||
GOWORK: ${{ github.workspace }}/go.work
|
||||
run: go get -v ./...
|
||||
- name: run tests
|
||||
env:
|
||||
INTEGRATION_TESTS: yes
|
||||
GOWORK: ${{ github.workspace }}/go.work
|
||||
run: |
|
||||
cd micro-tests
|
||||
go test -mod readonly -v ./... || true
|
47
.github/workflows/pr.yml
vendored
47
.github/workflows/pr.yml
vendored
@@ -1,47 +0,0 @@
|
||||
name: prbuild
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
- v3
|
||||
jobs:
|
||||
test:
|
||||
name: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: setup
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: 1.17
|
||||
- name: checkout
|
||||
uses: actions/checkout@v3
|
||||
- name: cache
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/go/pkg/mod
|
||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||
restore-keys: ${{ runner.os }}-go-
|
||||
- name: deps
|
||||
run: go get -v -t -d ./...
|
||||
- name: test
|
||||
env:
|
||||
INTEGRATION_TESTS: yes
|
||||
run: go test -mod readonly -v ./...
|
||||
lint:
|
||||
name: lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v3
|
||||
- name: lint
|
||||
uses: golangci/golangci-lint-action@v3.4.0
|
||||
continue-on-error: true
|
||||
with:
|
||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||
version: v1.30
|
||||
# Optional: working directory, useful for monorepos
|
||||
# working-directory: somedir
|
||||
# Optional: golangci-lint command line arguments.
|
||||
# args: --issues-exit-code=0
|
||||
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
||||
# only-new-issues: true
|
5
.golangci.yml
Normal file
5
.golangci.yml
Normal file
@@ -0,0 +1,5 @@
|
||||
run:
|
||||
concurrency: 8
|
||||
timeout: 5m
|
||||
issues-exit-code: 1
|
||||
tests: true
|
2
README.md
Normal file
2
README.md
Normal file
@@ -0,0 +1,2 @@
|
||||
# micro-meter-prometheus
|
||||

|
91
counter.go
91
counter.go
@@ -1,91 +0,0 @@
|
||||
package prometheus
|
||||
|
||||
import (
|
||||
"math"
|
||||
"sync/atomic"
|
||||
"unsafe"
|
||||
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
)
|
||||
|
||||
type prometheusCounter struct {
|
||||
name string
|
||||
c *dto.Metric
|
||||
}
|
||||
|
||||
func (c *prometheusCounter) Add(n int) {
|
||||
addFloat64(c.c.Gauge.Value, float64(n))
|
||||
}
|
||||
|
||||
func (c *prometheusCounter) Dec() {
|
||||
addFloat64(c.c.Gauge.Value, float64(-1))
|
||||
}
|
||||
|
||||
func (c *prometheusCounter) Inc() {
|
||||
addFloat64(c.c.Gauge.Value, float64(1))
|
||||
}
|
||||
|
||||
func (c *prometheusCounter) Get() uint64 {
|
||||
return uint64(getFloat64(c.c.Gauge.Value))
|
||||
}
|
||||
|
||||
func (c *prometheusCounter) Set(n uint64) {
|
||||
setFloat64(c.c.Gauge.Value, math.Float64frombits(n))
|
||||
}
|
||||
|
||||
type prometheusFloatCounter struct {
|
||||
name string
|
||||
c *dto.Metric
|
||||
}
|
||||
|
||||
func (c *prometheusFloatCounter) Add(n float64) {
|
||||
addFloat64(c.c.Gauge.Value, n)
|
||||
}
|
||||
|
||||
func (c *prometheusFloatCounter) Dec() {
|
||||
addFloat64(c.c.Gauge.Value, float64(-1))
|
||||
}
|
||||
|
||||
func (c *prometheusFloatCounter) Inc() {
|
||||
addFloat64(c.c.Gauge.Value, float64(1))
|
||||
}
|
||||
|
||||
func (c *prometheusFloatCounter) Get() float64 {
|
||||
return getFloat64(c.c.Gauge.Value)
|
||||
}
|
||||
|
||||
func (c *prometheusFloatCounter) Set(n float64) {
|
||||
setFloat64(c.c.Gauge.Value, n)
|
||||
}
|
||||
|
||||
func (c *prometheusFloatCounter) Sub(n float64) {
|
||||
addFloat64(c.c.Gauge.Value, -n)
|
||||
}
|
||||
|
||||
func setFloat64(_addr *float64, value float64) float64 {
|
||||
addr := (*uint64)(unsafe.Pointer(_addr))
|
||||
for {
|
||||
x := atomic.LoadUint64(addr)
|
||||
if atomic.CompareAndSwapUint64(addr, x, math.Float64bits(value)) {
|
||||
return value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func addFloat64(_addr *float64, delta float64) float64 {
|
||||
addr := (*uint64)(unsafe.Pointer(_addr))
|
||||
for {
|
||||
x := atomic.LoadUint64(addr)
|
||||
y := math.Float64frombits(x) + delta
|
||||
if atomic.CompareAndSwapUint64(addr, x, math.Float64bits(y)) {
|
||||
return y
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getFloat64(_addr *float64) float64 {
|
||||
addr := (*uint64)(unsafe.Pointer(_addr))
|
||||
x := atomic.LoadUint64(addr)
|
||||
y := math.Float64frombits(x)
|
||||
return y
|
||||
}
|
12
gauge.go
12
gauge.go
@@ -1,12 +0,0 @@
|
||||
package prometheus
|
||||
|
||||
import dto "github.com/prometheus/client_model/go"
|
||||
|
||||
type prometheusGauge struct {
|
||||
name string
|
||||
c *dto.Metric
|
||||
}
|
||||
|
||||
func (c prometheusGauge) Get() float64 {
|
||||
return getFloat64(c.c.Gauge.Value)
|
||||
}
|
18
go.mod
18
go.mod
@@ -1,23 +1,21 @@
|
||||
module go.unistack.org/micro-meter-prometheus/v3
|
||||
module go.unistack.org/micro-meter-prometheus/v4
|
||||
|
||||
go 1.22.0
|
||||
|
||||
toolchain go1.24.0
|
||||
|
||||
require (
|
||||
github.com/prometheus/client_golang v1.20.4
|
||||
github.com/prometheus/client_golang v1.21.0
|
||||
github.com/prometheus/client_model v0.6.1
|
||||
github.com/prometheus/common v0.59.1
|
||||
go.unistack.org/micro/v3 v3.10.91
|
||||
google.golang.org/protobuf v1.34.2
|
||||
github.com/prometheus/common v0.62.0
|
||||
go.unistack.org/micro/v4 v4.1.2
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/golang/protobuf v1.5.4 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/prometheus/procfs v0.15.1 // indirect
|
||||
go.unistack.org/micro-proto/v3 v3.4.1 // indirect
|
||||
golang.org/x/sys v0.25.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d // indirect
|
||||
google.golang.org/grpc v1.58.2 // indirect
|
||||
golang.org/x/sys v0.30.0 // indirect
|
||||
google.golang.org/protobuf v1.36.5 // indirect
|
||||
)
|
||||
|
48
go.sum
48
go.sum
@@ -2,43 +2,31 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
|
||||
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
|
||||
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.20.4 h1:Tgh3Yr67PaOv/uTqloMsCEdeuFTatm5zIq5+qNN23vI=
|
||||
github.com/prometheus/client_golang v1.20.4/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.21.0 h1:DIsaGmiaBkSangBgMtWdNfxbMNdku5IK6iNhrEqWvdA=
|
||||
github.com/prometheus/client_golang v1.21.0/go.mod h1:U9NM32ykUErtVBxdvD3zfi+EuFkkaBvMb09mIfe0Zgg=
|
||||
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
|
||||
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
|
||||
github.com/prometheus/common v0.59.1 h1:LXb1quJHWm1P6wq/U824uxYi4Sg0oGvNeUm1z5dJoX0=
|
||||
github.com/prometheus/common v0.59.1/go.mod h1:GpWM7dewqmVYcd7SmRaiWVe9SSqjf0UrwnYnpEZNuT0=
|
||||
github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io=
|
||||
github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I=
|
||||
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
|
||||
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
go.unistack.org/micro-proto/v3 v3.4.1 h1:UTjLSRz2YZuaHk9iSlVqqsA50JQNAEK2ZFboGqtEa9Q=
|
||||
go.unistack.org/micro-proto/v3 v3.4.1/go.mod h1:okx/cnOhzuCX0ggl/vToatbCupi0O44diiiLLsZ93Zo=
|
||||
go.unistack.org/micro/v3 v3.10.91 h1:vuJY4tXwpqimwIkEJ3TozMYNVQQs+C5QMlQWPgSY/YM=
|
||||
go.unistack.org/micro/v3 v3.10.91/go.mod h1:erMgt3Bl7vQQ0e9UpQyR5NlLiZ9pKeEJ9+1tfYFaqUg=
|
||||
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
|
||||
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
|
||||
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
|
||||
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
|
||||
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d h1:uvYuEyMHKNt+lT4K3bN6fGswmK8qSvcreM3BwjDh+y4=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20230822172742-b8732ec3820d/go.mod h1:+Bk1OCOj40wS2hwAMA+aCW9ypzm63QTBBHp6lQ3p+9M=
|
||||
google.golang.org/grpc v1.58.2 h1:SXUpjxeVF3FKrTYQI4f4KvbGD5u2xccdYdurwowix5I=
|
||||
google.golang.org/grpc v1.58.2/go.mod h1:tgX3ZQDlNJGU96V6yHh1T/JeoBQ2TXdr43YbYSsCJk0=
|
||||
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
|
||||
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
go.unistack.org/micro/v4 v4.1.2 h1:9SOlPYyPNNFpg1A7BsvhDyQm3gysLH1AhWbDCp1hyoY=
|
||||
go.unistack.org/micro/v4 v4.1.2/go.mod h1:lr3oYED8Ay1vjK68QqRw30QOtdk/ffpZqMFDasOUhKw=
|
||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=
|
||||
google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
39
histogram.go
39
histogram.go
@@ -1,39 +0,0 @@
|
||||
package prometheus
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
)
|
||||
|
||||
type prometheusHistogram struct {
|
||||
name string
|
||||
c *dto.Metric
|
||||
}
|
||||
|
||||
func (c prometheusHistogram) Reset() {
|
||||
}
|
||||
|
||||
func (c prometheusHistogram) Update(n float64) {
|
||||
atomic.AddUint64(c.c.Histogram.SampleCount, 1)
|
||||
addFloat64(c.c.Histogram.SampleSum, n)
|
||||
for _, b := range c.c.Histogram.Bucket {
|
||||
if n > *b.UpperBound {
|
||||
continue
|
||||
}
|
||||
atomic.AddUint64(b.CumulativeCount, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func (c prometheusHistogram) UpdateDuration(n time.Time) {
|
||||
x := time.Since(n).Seconds()
|
||||
atomic.AddUint64(c.c.Histogram.SampleCount, 1)
|
||||
addFloat64(c.c.Histogram.SampleSum, x)
|
||||
for _, b := range c.c.Histogram.Bucket {
|
||||
if x > *b.UpperBound {
|
||||
continue
|
||||
}
|
||||
atomic.AddUint64(b.CumulativeCount, 1)
|
||||
}
|
||||
}
|
555
prometheus.go
555
prometheus.go
@@ -2,8 +2,10 @@ package prometheus
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -11,210 +13,243 @@ import (
|
||||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
"github.com/prometheus/common/expfmt"
|
||||
"go.unistack.org/micro/v3/meter"
|
||||
xpool "go.unistack.org/micro/v3/util/xpool"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
"go.unistack.org/micro/v4/meter"
|
||||
)
|
||||
|
||||
var _ meter.Meter = (*prometheusMeter)(nil)
|
||||
var _ meter.Meter = &prometheusMeter{}
|
||||
|
||||
type prometheusMeter struct {
|
||||
opts meter.Options
|
||||
set prometheus.Registerer
|
||||
counter map[uint64]*prometheusCounter
|
||||
floatCounter map[uint64]*prometheusFloatCounter
|
||||
gauge map[uint64]*prometheusGauge
|
||||
histogram map[uint64]*prometheusHistogram
|
||||
summary map[uint64]*prometheusSummary
|
||||
mfPool xpool.Pool[*dto.MetricFamily]
|
||||
mu sync.Mutex
|
||||
counter map[string]*counters
|
||||
floatCounter map[string]*floatCounters
|
||||
gauge map[string]*gauges
|
||||
histogram map[string]*histograms
|
||||
summary map[string]*summaries
|
||||
mu *sync.Mutex
|
||||
}
|
||||
|
||||
type counters struct {
|
||||
cs map[uint64]*prometheusCounter
|
||||
}
|
||||
|
||||
type gauges struct {
|
||||
cs map[uint64]*prometheusGauge
|
||||
}
|
||||
|
||||
type histograms struct {
|
||||
cs map[uint64]*prometheusHistogram
|
||||
}
|
||||
|
||||
type summaries struct {
|
||||
cs map[uint64]*prometheusSummary
|
||||
}
|
||||
|
||||
type floatCounters struct {
|
||||
cs map[uint64]*prometheusFloatCounter
|
||||
}
|
||||
|
||||
/*
|
||||
func newFloat64(v float64) *float64 {
|
||||
nv := v
|
||||
return &nv
|
||||
}
|
||||
*/
|
||||
|
||||
func newString(v string) *string {
|
||||
nv := v
|
||||
return &nv
|
||||
}
|
||||
|
||||
func newName(name string) *string {
|
||||
idx := strings.Index(name, "{")
|
||||
if idx <= 0 {
|
||||
return newString(name)
|
||||
}
|
||||
|
||||
return newString(name[:idx])
|
||||
}
|
||||
|
||||
func NewMeter(opts ...meter.Option) *prometheusMeter {
|
||||
return &prometheusMeter{
|
||||
set: prometheus.NewRegistry(), // prometheus.DefaultRegisterer,
|
||||
opts: meter.NewOptions(opts...),
|
||||
counter: make(map[uint64]*prometheusCounter),
|
||||
floatCounter: make(map[uint64]*prometheusFloatCounter),
|
||||
gauge: make(map[uint64]*prometheusGauge),
|
||||
histogram: make(map[uint64]*prometheusHistogram),
|
||||
summary: make(map[uint64]*prometheusSummary),
|
||||
mfPool: xpool.NewPool[*dto.MetricFamily](func() *dto.MetricFamily {
|
||||
return &dto.MetricFamily{}
|
||||
}),
|
||||
counter: make(map[string]*counters),
|
||||
floatCounter: make(map[string]*floatCounters),
|
||||
gauge: make(map[string]*gauges),
|
||||
histogram: make(map[string]*histograms),
|
||||
summary: make(map[string]*summaries),
|
||||
mu: &sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
func (m *prometheusMeter) buildMetric(name string, labels ...string) string {
|
||||
nl := len(m.opts.Labels) + len(labels)
|
||||
if nl == 0 {
|
||||
return name
|
||||
}
|
||||
|
||||
nlabels := make([]string, 0, nl)
|
||||
nlabels = append(nlabels, m.opts.Labels...)
|
||||
nlabels = append(nlabels, labels...)
|
||||
|
||||
return meter.BuildName(name, nlabels...)
|
||||
}
|
||||
|
||||
func (m *prometheusMeter) Name() string {
|
||||
return m.opts.Name
|
||||
}
|
||||
|
||||
func (m *prometheusMeter) Counter(name string, labels ...string) meter.Counter {
|
||||
clabels := meter.BuildLabels(append(m.opts.Labels, labels...)...)
|
||||
h := newHash(name, clabels)
|
||||
m.mu.Lock()
|
||||
mc, ok := m.counter[h]
|
||||
m.mu.Unlock()
|
||||
defer m.mu.Unlock()
|
||||
nm := m.buildMetric(name)
|
||||
labels = append(m.opts.Labels, labels...)
|
||||
cd, ok := m.counter[nm]
|
||||
h := newHash(labels)
|
||||
if !ok {
|
||||
var v float64
|
||||
mc = &prometheusCounter{
|
||||
name: name,
|
||||
c: &dto.Metric{
|
||||
Gauge: &dto.Gauge{Value: &v},
|
||||
Label: labelMetric(clabels),
|
||||
},
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.counter[h] = mc
|
||||
m.mu.Unlock()
|
||||
cd = &counters{cs: make(map[uint64]*prometheusCounter)}
|
||||
c := &prometheusCounter{c: prometheus.NewGauge(prometheus.GaugeOpts{Name: nm}), labels: labels}
|
||||
cd.cs[h] = c
|
||||
m.counter[nm] = cd
|
||||
return c
|
||||
}
|
||||
return mc
|
||||
c, ok := cd.cs[h]
|
||||
if !ok {
|
||||
c = &prometheusCounter{c: prometheus.NewGauge(prometheus.GaugeOpts{Name: nm}), labels: labels}
|
||||
cd.cs[h] = c
|
||||
m.counter[nm] = cd
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (m *prometheusMeter) FloatCounter(name string, labels ...string) meter.FloatCounter {
|
||||
clabels := meter.BuildLabels(append(m.opts.Labels, labels...)...)
|
||||
h := newHash(name, clabels)
|
||||
m.mu.Lock()
|
||||
mc, ok := m.floatCounter[h]
|
||||
m.mu.Unlock()
|
||||
defer m.mu.Unlock()
|
||||
nm := m.buildMetric(name)
|
||||
labels = append(m.opts.Labels, labels...)
|
||||
cd, ok := m.floatCounter[nm]
|
||||
h := newHash(labels)
|
||||
if !ok {
|
||||
var v float64
|
||||
mc = &prometheusFloatCounter{
|
||||
name: name,
|
||||
c: &dto.Metric{
|
||||
Gauge: &dto.Gauge{Value: &v},
|
||||
Label: labelMetric(clabels),
|
||||
},
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.floatCounter[h] = mc
|
||||
m.mu.Unlock()
|
||||
cd = &floatCounters{cs: make(map[uint64]*prometheusFloatCounter)}
|
||||
c := &prometheusFloatCounter{c: prometheus.NewGauge(prometheus.GaugeOpts{Name: nm}), labels: labels}
|
||||
cd.cs[h] = c
|
||||
m.floatCounter[nm] = cd
|
||||
return c
|
||||
}
|
||||
return mc
|
||||
c, ok := cd.cs[h]
|
||||
if !ok {
|
||||
c = &prometheusFloatCounter{c: prometheus.NewGauge(prometheus.GaugeOpts{Name: nm}), labels: labels}
|
||||
cd.cs[h] = c
|
||||
m.floatCounter[nm] = cd
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (m *prometheusMeter) Gauge(name string, fn func() float64, labels ...string) meter.Gauge {
|
||||
clabels := meter.BuildLabels(append(m.opts.Labels, labels...)...)
|
||||
h := newHash(name, clabels)
|
||||
m.mu.Lock()
|
||||
mc, ok := m.gauge[h]
|
||||
m.mu.Unlock()
|
||||
defer m.mu.Unlock()
|
||||
nm := m.buildMetric(name)
|
||||
labels = append(m.opts.Labels, labels...)
|
||||
cd, ok := m.gauge[nm]
|
||||
h := newHash(labels)
|
||||
if !ok {
|
||||
var v float64
|
||||
mc = &prometheusGauge{
|
||||
name: name,
|
||||
c: &dto.Metric{
|
||||
Gauge: &dto.Gauge{Value: &v},
|
||||
Label: labelMetric(clabels),
|
||||
},
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.gauge[h] = mc
|
||||
m.mu.Unlock()
|
||||
cd = &gauges{cs: make(map[uint64]*prometheusGauge)}
|
||||
c := &prometheusGauge{c: prometheus.NewGauge(prometheus.GaugeOpts{Name: nm}), labels: labels}
|
||||
cd.cs[h] = c
|
||||
m.gauge[nm] = cd
|
||||
return c
|
||||
}
|
||||
return mc
|
||||
c, ok := cd.cs[h]
|
||||
if !ok {
|
||||
c = &prometheusGauge{c: prometheus.NewGauge(prometheus.GaugeOpts{Name: nm}), labels: labels}
|
||||
cd.cs[h] = c
|
||||
m.gauge[nm] = cd
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (m *prometheusMeter) Histogram(name string, labels ...string) meter.Histogram {
|
||||
clabels := meter.BuildLabels(append(m.opts.Labels, labels...)...)
|
||||
h := newHash(name, clabels)
|
||||
m.mu.Lock()
|
||||
mc, ok := m.histogram[h]
|
||||
m.mu.Unlock()
|
||||
defer m.mu.Unlock()
|
||||
nm := m.buildMetric(name)
|
||||
labels = append(m.opts.Labels, labels...)
|
||||
cd, ok := m.histogram[nm]
|
||||
h := newHash(labels)
|
||||
if !ok {
|
||||
var c uint64
|
||||
var s float64
|
||||
buckets := make([]float64, len(prometheus.DefBuckets))
|
||||
copy(buckets, prometheus.DefBuckets)
|
||||
mdto := &dto.Metric{
|
||||
Histogram: &dto.Histogram{
|
||||
SampleCount: &c,
|
||||
SampleSum: &s,
|
||||
CreatedTimestamp: timestamppb.Now(),
|
||||
Bucket: make([]*dto.Bucket, len(buckets)),
|
||||
},
|
||||
Label: labelMetric(clabels),
|
||||
}
|
||||
for idx, b := range buckets {
|
||||
var cc uint64
|
||||
mdto.Histogram.Bucket[idx] = &dto.Bucket{CumulativeCount: &cc, UpperBound: &b}
|
||||
}
|
||||
mc = &prometheusHistogram{
|
||||
name: name,
|
||||
c: mdto,
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.histogram[h] = mc
|
||||
m.mu.Unlock()
|
||||
cd = &histograms{cs: make(map[uint64]*prometheusHistogram)}
|
||||
c := &prometheusHistogram{c: prometheus.NewHistogram(prometheus.HistogramOpts{Name: nm}), labels: labels}
|
||||
cd.cs[h] = c
|
||||
m.histogram[nm] = cd
|
||||
return c
|
||||
}
|
||||
return mc
|
||||
c, ok := cd.cs[h]
|
||||
if !ok {
|
||||
c = &prometheusHistogram{c: prometheus.NewHistogram(prometheus.HistogramOpts{Name: nm}), labels: labels}
|
||||
cd.cs[h] = c
|
||||
m.histogram[nm] = cd
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (m *prometheusMeter) Summary(name string, labels ...string) meter.Summary {
|
||||
clabels := meter.BuildLabels(append(m.opts.Labels, labels...)...)
|
||||
h := newHash(name, clabels)
|
||||
m.mu.Lock()
|
||||
mc, ok := m.summary[h]
|
||||
m.mu.Unlock()
|
||||
defer m.mu.Unlock()
|
||||
nm := m.buildMetric(name)
|
||||
labels = append(m.opts.Labels, labels...)
|
||||
cd, ok := m.summary[nm]
|
||||
h := newHash(labels)
|
||||
if !ok {
|
||||
var c uint64
|
||||
var s float64
|
||||
mc = &prometheusSummary{
|
||||
name: name,
|
||||
c: &dto.Metric{
|
||||
Summary: &dto.Summary{
|
||||
SampleCount: &c,
|
||||
SampleSum: &s,
|
||||
CreatedTimestamp: timestamppb.Now(),
|
||||
},
|
||||
Label: labelMetric(clabels),
|
||||
},
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.summary[h] = mc
|
||||
m.mu.Unlock()
|
||||
cd = &summaries{cs: make(map[uint64]*prometheusSummary)}
|
||||
c := &prometheusSummary{c: prometheus.NewSummary(prometheus.SummaryOpts{Name: nm}), labels: labels}
|
||||
cd.cs[h] = c
|
||||
m.summary[nm] = cd
|
||||
return c
|
||||
}
|
||||
return mc
|
||||
c, ok := cd.cs[h]
|
||||
if !ok {
|
||||
c = &prometheusSummary{c: prometheus.NewSummary(prometheus.SummaryOpts{Name: nm}), labels: labels}
|
||||
cd.cs[h] = c
|
||||
m.summary[nm] = cd
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (m *prometheusMeter) SummaryExt(name string, window time.Duration, quantiles []float64, labels ...string) meter.Summary {
|
||||
clabels := meter.BuildLabels(append(m.opts.Labels, labels...)...)
|
||||
h := newHash(name, clabels)
|
||||
m.mu.Lock()
|
||||
mc, ok := m.summary[h]
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
nm := m.buildMetric(name)
|
||||
labels = append(m.opts.Labels, labels...)
|
||||
cd, ok := m.summary[nm]
|
||||
h := newHash(labels)
|
||||
if !ok {
|
||||
var c uint64
|
||||
var s float64
|
||||
mc = &prometheusSummary{
|
||||
name: name,
|
||||
c: &dto.Metric{
|
||||
Summary: &dto.Summary{
|
||||
SampleCount: &c,
|
||||
SampleSum: &s,
|
||||
},
|
||||
Label: labelMetric(clabels),
|
||||
},
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.summary[h] = mc
|
||||
m.mu.Unlock()
|
||||
cd = &summaries{cs: make(map[uint64]*prometheusSummary)}
|
||||
c := &prometheusSummary{c: prometheus.NewSummary(prometheus.SummaryOpts{
|
||||
Name: nm,
|
||||
MaxAge: window,
|
||||
Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
|
||||
}), labels: labels}
|
||||
cd.cs[h] = c
|
||||
m.summary[nm] = cd
|
||||
return c
|
||||
}
|
||||
return mc
|
||||
c, ok := cd.cs[h]
|
||||
if !ok {
|
||||
c = &prometheusSummary{c: prometheus.NewSummary(prometheus.SummaryOpts{
|
||||
Name: nm,
|
||||
MaxAge: window,
|
||||
Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
|
||||
}), labels: labels}
|
||||
cd.cs[h] = c
|
||||
m.summary[nm] = cd
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (m *prometheusMeter) Init(opts ...meter.Option) error {
|
||||
for _, o := range opts {
|
||||
o(&m.opts)
|
||||
}
|
||||
|
||||
if m.opts.WriteProcessMetrics || m.opts.WriteFDMetrics {
|
||||
pc := collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})
|
||||
_ = m.set.Register(pc)
|
||||
gc := collectors.NewGoCollector(collectors.WithGoCollectorRuntimeMetrics(collectors.GoRuntimeMetricsRule{Matcher: regexp.MustCompile("/.*")}))
|
||||
_ = m.set.Register(gc)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -224,6 +259,13 @@ func (m *prometheusMeter) Write(w io.Writer, opts ...meter.Option) error {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
if options.WriteProcessMetrics || options.WriteFDMetrics {
|
||||
pc := collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})
|
||||
_ = m.set.Register(pc)
|
||||
gc := collectors.NewGoCollector(collectors.WithGoCollectorRuntimeMetrics(collectors.GoRuntimeMetricsRule{Matcher: regexp.MustCompile("/.*")}))
|
||||
_ = m.set.Register(gc)
|
||||
}
|
||||
|
||||
g, ok := m.set.(prometheus.Gatherer)
|
||||
if !ok {
|
||||
return fmt.Errorf("set type %T not prometheus.Gatherer", m.set)
|
||||
@@ -238,43 +280,78 @@ func (m *prometheusMeter) Write(w io.Writer, opts ...meter.Option) error {
|
||||
|
||||
m.mu.Lock()
|
||||
|
||||
for _, c := range m.counter {
|
||||
mf := m.mfPool.Get()
|
||||
mf.Name = &c.name
|
||||
mf.Type = dto.MetricType_GAUGE.Enum()
|
||||
mf.Metric = append(mf.Metric, c.c)
|
||||
for name, metrics := range m.counter {
|
||||
mf := &dto.MetricFamily{
|
||||
Name: newName(name),
|
||||
Type: dto.MetricType_GAUGE.Enum(),
|
||||
Metric: make([]*dto.Metric, 0, len(metrics.cs)),
|
||||
}
|
||||
for _, c := range metrics.cs {
|
||||
m := &dto.Metric{}
|
||||
_ = c.c.Write(m)
|
||||
fillMetric(m, c.labels)
|
||||
mf.Metric = append(mf.Metric, m)
|
||||
}
|
||||
mfs = append(mfs, mf)
|
||||
}
|
||||
|
||||
for _, c := range m.floatCounter {
|
||||
mf := m.mfPool.Get()
|
||||
mf.Name = &c.name
|
||||
mf.Type = dto.MetricType_GAUGE.Enum()
|
||||
mf.Metric = append(mf.Metric, c.c)
|
||||
for name, metrics := range m.gauge {
|
||||
mf := &dto.MetricFamily{
|
||||
Name: newName(name),
|
||||
Type: dto.MetricType_GAUGE.Enum(),
|
||||
Metric: make([]*dto.Metric, 0, len(metrics.cs)),
|
||||
}
|
||||
for _, c := range metrics.cs {
|
||||
m := &dto.Metric{}
|
||||
_ = c.c.Write(m)
|
||||
fillMetric(m, c.labels)
|
||||
mf.Metric = append(mf.Metric, m)
|
||||
}
|
||||
mfs = append(mfs, mf)
|
||||
}
|
||||
|
||||
for _, c := range m.gauge {
|
||||
mf := m.mfPool.Get()
|
||||
mf.Name = &c.name
|
||||
mf.Type = dto.MetricType_GAUGE.Enum()
|
||||
mf.Metric = append(mf.Metric, c.c)
|
||||
for name, metrics := range m.floatCounter {
|
||||
mf := &dto.MetricFamily{
|
||||
Name: newName(name),
|
||||
Type: dto.MetricType_GAUGE.Enum(),
|
||||
Metric: make([]*dto.Metric, 0, len(metrics.cs)),
|
||||
}
|
||||
for _, c := range metrics.cs {
|
||||
m := &dto.Metric{}
|
||||
_ = c.c.Write(m)
|
||||
fillMetric(m, c.labels)
|
||||
mf.Metric = append(mf.Metric, m)
|
||||
}
|
||||
mfs = append(mfs, mf)
|
||||
}
|
||||
|
||||
for _, c := range m.histogram {
|
||||
mf := m.mfPool.Get()
|
||||
mf.Name = &c.name
|
||||
mf.Type = dto.MetricType_HISTOGRAM.Enum()
|
||||
mf.Metric = append(mf.Metric, c.c)
|
||||
for name, metrics := range m.histogram {
|
||||
mf := &dto.MetricFamily{
|
||||
Name: newName(name),
|
||||
Type: dto.MetricType_HISTOGRAM.Enum(),
|
||||
Metric: make([]*dto.Metric, 0, len(metrics.cs)),
|
||||
}
|
||||
for _, c := range metrics.cs {
|
||||
m := &dto.Metric{}
|
||||
_ = c.c.Write(m)
|
||||
fillMetric(m, c.labels)
|
||||
mf.Metric = append(mf.Metric, m)
|
||||
}
|
||||
mfs = append(mfs, mf)
|
||||
}
|
||||
|
||||
for _, c := range m.summary {
|
||||
mf := m.mfPool.Get()
|
||||
mf.Name = &c.name
|
||||
mf.Type = dto.MetricType_SUMMARY.Enum()
|
||||
mf.Metric = append(mf.Metric, c.c)
|
||||
for name, metrics := range m.summary {
|
||||
mf := &dto.MetricFamily{
|
||||
Name: newName(name),
|
||||
Type: dto.MetricType_SUMMARY.Enum(),
|
||||
Metric: make([]*dto.Metric, 0, len(metrics.cs)),
|
||||
}
|
||||
for _, c := range metrics.cs {
|
||||
m := &dto.Metric{}
|
||||
_ = c.c.Write(m)
|
||||
fillMetric(m, c.labels)
|
||||
mf.Metric = append(mf.Metric, m)
|
||||
}
|
||||
mfs = append(mfs, mf)
|
||||
}
|
||||
|
||||
@@ -282,8 +359,6 @@ func (m *prometheusMeter) Write(w io.Writer, opts ...meter.Option) error {
|
||||
|
||||
for _, mf := range mfs {
|
||||
_ = enc.Encode(mf)
|
||||
mf.Reset()
|
||||
m.mfPool.Put(mf)
|
||||
}
|
||||
|
||||
if closer, ok := enc.(io.Closer); ok {
|
||||
@@ -300,6 +375,7 @@ func (m *prometheusMeter) Clone(opts ...meter.Option) meter.Meter {
|
||||
}
|
||||
|
||||
return &prometheusMeter{
|
||||
mu: m.mu,
|
||||
set: m.set,
|
||||
opts: options,
|
||||
floatCounter: m.floatCounter,
|
||||
@@ -327,30 +403,117 @@ func (m *prometheusMeter) Set(opts ...meter.Option) meter.Meter {
|
||||
return nm
|
||||
}
|
||||
|
||||
func labelMetric(labels []string) []*dto.LabelPair {
|
||||
nl := make([]string, len(labels))
|
||||
copy(nl, labels)
|
||||
dtoLabels := make([]*dto.LabelPair, 0, len(nl)/2)
|
||||
for idx := 0; idx < len(nl); idx += 2 {
|
||||
dtoLabels = append(dtoLabels, &dto.LabelPair{
|
||||
Name: &(nl[idx]),
|
||||
Value: &(nl[idx+1]),
|
||||
})
|
||||
}
|
||||
return dtoLabels
|
||||
type prometheusCounter struct {
|
||||
c prometheus.Gauge
|
||||
labels []string
|
||||
}
|
||||
|
||||
func newHash(n string, l []string) uint64 {
|
||||
h := uint64(14695981039346656037)
|
||||
for i := 0; i < len(n); i++ {
|
||||
h ^= uint64(n[i])
|
||||
h *= 1099511628211
|
||||
}
|
||||
for _, s := range l {
|
||||
for i := 0; i < len(s); i++ {
|
||||
h ^= uint64(s[i])
|
||||
h *= 1099511628211
|
||||
}
|
||||
}
|
||||
return h
|
||||
func (c *prometheusCounter) Add(n int) {
|
||||
c.c.Add(float64(n))
|
||||
}
|
||||
|
||||
func (c *prometheusCounter) Dec() {
|
||||
c.c.Dec()
|
||||
}
|
||||
|
||||
func (c *prometheusCounter) Inc() {
|
||||
c.c.Inc()
|
||||
}
|
||||
|
||||
func (c *prometheusCounter) Get() uint64 {
|
||||
m := &dto.Metric{}
|
||||
if err := c.c.Write(m); err != nil {
|
||||
return 0
|
||||
}
|
||||
return uint64(m.GetGauge().GetValue())
|
||||
}
|
||||
|
||||
func (c *prometheusCounter) Set(n uint64) {
|
||||
c.c.Set(float64(n))
|
||||
}
|
||||
|
||||
type prometheusFloatCounter struct {
|
||||
c prometheus.Gauge
|
||||
labels []string
|
||||
}
|
||||
|
||||
func (c prometheusFloatCounter) Add(n float64) {
|
||||
c.c.Add(n)
|
||||
}
|
||||
|
||||
func (c prometheusFloatCounter) Get() float64 {
|
||||
m := &dto.Metric{}
|
||||
if err := c.c.Write(m); err != nil {
|
||||
return 0
|
||||
}
|
||||
return m.GetGauge().GetValue()
|
||||
}
|
||||
|
||||
func (c prometheusFloatCounter) Set(n float64) {
|
||||
c.c.Set(n)
|
||||
}
|
||||
|
||||
func (c prometheusFloatCounter) Sub(n float64) {
|
||||
c.c.Add(-n)
|
||||
}
|
||||
|
||||
type prometheusGauge struct {
|
||||
c prometheus.Gauge
|
||||
labels []string
|
||||
}
|
||||
|
||||
func (c prometheusGauge) Get() float64 {
|
||||
m := &dto.Metric{}
|
||||
if err := c.c.Write(m); err != nil {
|
||||
return 0
|
||||
}
|
||||
return float64(m.GetGauge().GetValue())
|
||||
}
|
||||
|
||||
type prometheusHistogram struct {
|
||||
c prometheus.Histogram
|
||||
labels []string
|
||||
}
|
||||
|
||||
func (c prometheusHistogram) Reset() {
|
||||
}
|
||||
|
||||
func (c prometheusHistogram) Update(n float64) {
|
||||
c.c.Observe(n)
|
||||
}
|
||||
|
||||
func (c prometheusHistogram) UpdateDuration(n time.Time) {
|
||||
c.c.Observe(time.Since(n).Seconds())
|
||||
}
|
||||
|
||||
type prometheusSummary struct {
|
||||
c prometheus.Summary
|
||||
labels []string
|
||||
}
|
||||
|
||||
func (c prometheusSummary) Update(n float64) {
|
||||
c.c.Observe(n)
|
||||
}
|
||||
|
||||
func (c prometheusSummary) UpdateDuration(n time.Time) {
|
||||
c.c.Observe(time.Since(n).Seconds())
|
||||
}
|
||||
|
||||
func newHash(labels []string) uint64 {
|
||||
h := fnv.New64a()
|
||||
for _, l := range labels {
|
||||
h.Write([]byte(l))
|
||||
}
|
||||
return h.Sum64()
|
||||
}
|
||||
|
||||
func fillMetric(m *dto.Metric, labels []string) *dto.Metric {
|
||||
m.Label = make([]*dto.LabelPair, 0, len(labels)/2)
|
||||
for idx := 0; idx < len(labels); idx += 2 {
|
||||
m.Label = append(m.Label, &dto.LabelPair{
|
||||
Name: newString(labels[idx]),
|
||||
Value: newString(labels[idx+1]),
|
||||
})
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
@@ -2,112 +2,12 @@ package prometheus
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
"github.com/prometheus/common/expfmt"
|
||||
"go.unistack.org/micro/v3/client"
|
||||
"go.unistack.org/micro/v3/codec"
|
||||
"go.unistack.org/micro/v3/meter"
|
||||
"go.unistack.org/micro/v4/meter"
|
||||
)
|
||||
|
||||
func TestHash(t *testing.T) {
|
||||
t.Skip()
|
||||
h1 := newHash("micro_server_request_total", []string{"code", "16", "endpoint", "/clientprofile.ClientProfileService/GetClientProfile", "status", "failure"})
|
||||
h2 := newHash("micro_server_request_total", []string{"code", "16", "endpoint", "/clientproduct.ClientProductService/GetDepositProducts", "status", "failure"})
|
||||
h3 := newHash("micro_server_request_total", []string{"code", "16", "endpoint", "/operationsinfo.OperationsInfoService/GetOperations", "status", "failure"})
|
||||
t.Logf("h1: %v\nh2: %v\nh3: %v\n", h1, h2, h3)
|
||||
}
|
||||
|
||||
func TestHistogram(t *testing.T) {
|
||||
m := NewMeter()
|
||||
name := "test"
|
||||
m.Histogram(name, "endpoint").Update(1)
|
||||
m.Histogram(name, "endpoint").Update(1)
|
||||
m.Histogram(name, "endpoint").Update(5)
|
||||
m.Histogram(name, "endpoint").Update(10)
|
||||
m.Histogram(name, "endpoint").Update(10)
|
||||
m.Histogram(name, "endpoint").Update(30)
|
||||
mbuf := bytes.NewBuffer(nil)
|
||||
_ = m.Write(mbuf, meter.WriteProcessMetrics(false), meter.WriteFDMetrics(false))
|
||||
|
||||
/*
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`micro_server_sum{endpoint="ep1",path="/path1"} 20`)) {
|
||||
t.Fatalf("invalid metrics output: %s", buf.Bytes())
|
||||
}
|
||||
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`micro_server_count{endpoint="ep1",path="/path1"} 2`)) {
|
||||
t.Fatalf("invalid metrics output: %s", buf.Bytes())
|
||||
}
|
||||
*/
|
||||
p := prometheus.NewHistogram(prometheus.HistogramOpts{Name: name})
|
||||
p.Observe(1)
|
||||
p.Observe(1)
|
||||
p.Observe(5)
|
||||
p.Observe(10)
|
||||
p.Observe(10)
|
||||
p.Observe(30)
|
||||
mdto := &dto.Metric{}
|
||||
p.Write(mdto)
|
||||
pbuf := bytes.NewBuffer(nil)
|
||||
enc := expfmt.NewEncoder(pbuf, expfmt.NewFormat(expfmt.TypeTextPlain))
|
||||
mf := &dto.MetricFamily{Name: &name, Type: dto.MetricType_HISTOGRAM.Enum(), Metric: []*dto.Metric{mdto}}
|
||||
_ = enc.Encode(mf)
|
||||
|
||||
if !bytes.Equal(mbuf.Bytes(), pbuf.Bytes()) {
|
||||
fmt.Printf("m\n%s\n", mbuf.Bytes())
|
||||
fmt.Printf("m\n%s\n", pbuf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummary(t *testing.T) {
|
||||
t.Skip()
|
||||
name := "micro_server"
|
||||
m := NewMeter()
|
||||
m.Summary("micro_server").Update(1)
|
||||
m.Summary("micro_server").Update(1)
|
||||
m.Summary("micro_server").Update(5)
|
||||
m.Summary("micro_server").Update(10)
|
||||
m.Summary("micro_server").Update(10)
|
||||
m.Summary("micro_server").Update(30)
|
||||
mbuf := bytes.NewBuffer(nil)
|
||||
_ = m.Write(mbuf, meter.WriteProcessMetrics(false), meter.WriteFDMetrics(false))
|
||||
|
||||
if !bytes.Contains(mbuf.Bytes(), []byte(`micro_server_sum 57`)) {
|
||||
t.Fatalf("invalid metrics output: %s", mbuf.Bytes())
|
||||
}
|
||||
|
||||
if !bytes.Contains(mbuf.Bytes(), []byte(`micro_server_count 6`)) {
|
||||
t.Fatalf("invalid metrics output: %s", mbuf.Bytes())
|
||||
}
|
||||
|
||||
objectives := make(map[float64]float64)
|
||||
for _, c := range meter.DefaultSummaryQuantiles {
|
||||
objectives[c] = c
|
||||
}
|
||||
p := prometheus.NewSummary(prometheus.SummaryOpts{Name: name, Objectives: objectives, MaxAge: meter.DefaultSummaryWindow})
|
||||
p.Observe(1)
|
||||
p.Observe(1)
|
||||
p.Observe(5)
|
||||
p.Observe(10)
|
||||
p.Observe(10)
|
||||
p.Observe(30)
|
||||
mdto := &dto.Metric{}
|
||||
_ = p.Write(mdto)
|
||||
pbuf := bytes.NewBuffer(nil)
|
||||
enc := expfmt.NewEncoder(pbuf, expfmt.NewFormat(expfmt.TypeTextPlain))
|
||||
mf := &dto.MetricFamily{Name: &name, Type: dto.MetricType_SUMMARY.Enum(), Metric: []*dto.Metric{mdto}}
|
||||
_ = enc.Encode(mf)
|
||||
|
||||
if !bytes.Equal(mbuf.Bytes(), pbuf.Bytes()) {
|
||||
fmt.Printf("m\n%s\n", mbuf.Bytes())
|
||||
fmt.Printf("m\n%s\n", pbuf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStd(t *testing.T) {
|
||||
m := NewMeter(meter.WriteProcessMetrics(true), meter.WriteFDMetrics(true))
|
||||
if err := m.Init(); err != nil {
|
||||
@@ -120,24 +20,16 @@ func TestStd(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapper(t *testing.T) {
|
||||
m := NewMeter() // meter.Labels("test_key", "test_val"))
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
c := client.NewClient(client.Meter(m))
|
||||
if err := c.Init(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rsp := &codec.Frame{}
|
||||
req := &codec.Frame{}
|
||||
err := c.Call(ctx, c.NewRequest("svc2", "Service.Method", req), rsp)
|
||||
_, _ = rsp, err
|
||||
buf := bytes.NewBuffer(nil)
|
||||
_ = m.Write(buf, meter.WriteProcessMetrics(false), meter.WriteFDMetrics(false))
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`micro_client_request_inflight{endpoint="Service.Method"} 0`)) {
|
||||
t.Fatalf("invalid metrics output: %s", buf.Bytes())
|
||||
func TestBuildName(t *testing.T) {
|
||||
m := NewMeter()
|
||||
check := `micro_foo{aaa="b",bar="baz",ccc="d"}`
|
||||
name := m.buildMetric("micro_foo", "bar", "baz", "aaa", "b", "ccc", "d")
|
||||
if name != check {
|
||||
t.Fatalf("metric name error: %s != %s", name, check)
|
||||
}
|
||||
|
||||
cnt := m.Counter("counter", "key", "val")
|
||||
cnt.Inc()
|
||||
}
|
||||
|
||||
func TestMultiple(t *testing.T) {
|
||||
@@ -154,9 +46,31 @@ func TestMultiple(t *testing.T) {
|
||||
buf := bytes.NewBuffer(nil)
|
||||
_ = m.Write(buf, meter.WriteProcessMetrics(false), meter.WriteFDMetrics(false))
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`micro_server{endpoint="ep1",path="/path1"} 2`)) {
|
||||
t.Fatalf("invalid metrics output: %s", buf.Bytes())
|
||||
}
|
||||
if !bytes.Contains(buf.Bytes(), []byte(`micro_server{endpoint="ep3",path="/path3",status="success"} 1`)) {
|
||||
// t.Fatal("XXXX")
|
||||
t.Fatalf("invalid metrics output: %s", buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCounterSet(t *testing.T) {
|
||||
m := NewMeter()
|
||||
|
||||
value := uint64(42)
|
||||
|
||||
m.Counter("forte_accounts_total", "channel_code", "crm").Set(value)
|
||||
|
||||
fmt.Println(uint64(float64(value)))
|
||||
|
||||
buf := bytes.NewBuffer(nil)
|
||||
|
||||
_ = m.Write(buf)
|
||||
|
||||
output := buf.String()
|
||||
|
||||
fmt.Println(output)
|
||||
|
||||
expectedOutput := fmt.Sprintf(`%s{channel_code="crm"} %d`, "forte_accounts_total", value)
|
||||
|
||||
if !bytes.Contains(buf.Bytes(), []byte(expectedOutput)) {
|
||||
t.Fatalf("invalid metrics output: expected %q, got %q", expectedOutput, output)
|
||||
}
|
||||
}
|
||||
|
24
summary.go
24
summary.go
@@ -1,24 +0,0 @@
|
||||
package prometheus
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
dto "github.com/prometheus/client_model/go"
|
||||
)
|
||||
|
||||
type prometheusSummary struct {
|
||||
name string
|
||||
c *dto.Metric
|
||||
}
|
||||
|
||||
func (c prometheusSummary) Update(n float64) {
|
||||
atomic.AddUint64(c.c.Summary.SampleCount, 1)
|
||||
addFloat64(c.c.Summary.SampleSum, n)
|
||||
}
|
||||
|
||||
func (c prometheusSummary) UpdateDuration(n time.Time) {
|
||||
x := time.Since(n).Seconds()
|
||||
atomic.AddUint64(c.c.Summary.SampleCount, 1)
|
||||
addFloat64(c.c.Summary.SampleSum, x)
|
||||
}
|
Reference in New Issue
Block a user