7 Commits

Author SHA1 Message Date
1dbf610d02 reuse sync.Map
All checks were successful
test / test (push) Successful in 2m52s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-01-20 12:43:22 +03:00
0f9ff3fe38 Merge pull request 'Update workflows' (#109) from atolstikhin/micro-meter-prometheus:v3 into v3
All checks were successful
test / test (push) Successful in 4m56s
Reviewed-on: #109
2024-12-19 19:53:21 +03:00
3dcb589de9 Merge branch 'v3' into v3
Some checks failed
automerge / automerge (pull_request) Failing after 20s
autoapprove / autoapprove (pull_request) Failing after 1m38s
lint / lint (pull_request) Successful in 3m59s
dependabot-automerge / automerge (pull_request) Failing after 13m39s
test / test (pull_request) Successful in 15m58s
2024-12-15 17:51:38 +03:00
3c23fa1343 fixup lint
Some checks failed
codeql / analyze (go) (push) Failing after 5m32s
build / lint (push) Successful in 1m5s
build / test (push) Failing after 1m58s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-12-15 17:51:29 +03:00
Aleksandr Tolstikhin
8aecd80e99 Update workflows
Some checks failed
automerge / automerge (pull_request) Has been skipped
dependabot-automerge / automerge (pull_request) Has been skipped
autoapprove / autoapprove (pull_request) Successful in 6s
test / test (pull_request) Successful in 1m23s
lint / lint (pull_request) Failing after 27s
2024-12-14 01:35:16 +07:00
d4472e1ab2 partially fix race cond
Some checks failed
codeql / analyze (go) (push) Failing after 49s
build / test (push) Failing after 4m54s
build / lint (push) Successful in 9m28s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-11-08 15:27:05 +03:00
6f6d362c20 experimental race free labels
Some checks failed
codeql / analyze (go) (push) Failing after 44s
build / test (push) Failing after 4m52s
build / lint (push) Successful in 9m27s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-11-07 16:49:16 +03:00
22 changed files with 276 additions and 382 deletions

View File

@@ -0,0 +1,29 @@
name: lint
on:
pull_request:
types: [opened, reopened, synchronize]
branches:
- master
- v3
- v4
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: https://github.com/golangci/golangci-lint-action@v6
with:
version: 'latest'

View File

@@ -0,0 +1,34 @@
name: test
on:
pull_request:
types: [opened, reopened, synchronize]
branches:
- master
- v3
- v4
push:
branches:
- master
- v3
- v4
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 ./...

View File

@@ -0,0 +1,53 @@
name: test
on:
pull_request:
types: [opened, reopened, synchronize]
branches:
- master
- v3
- v4
push:
branches:
- master
- v3
- v4
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: /workspace/${{ github.repository_owner }}/go.work
run: |
go work init
go work use .
go work use micro-tests
- name: setup deps
env:
GOWORK: /workspace/${{ github.repository_owner }}/go.work
run: go get -v ./...
- name: run tests
env:
INTEGRATION_TESTS: yes
GOWORK: /workspace/${{ github.repository_owner }}/go.work
run: |
cd micro-tests
go test -mod readonly -v ./... || true

View File

@@ -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"

View File

@@ -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 }}

View File

@@ -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}}

View File

@@ -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

View File

@@ -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

View File

@@ -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}}

View File

@@ -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
View File

@@ -0,0 +1,5 @@
run:
concurrency: 8
deadline: 5m
issues-exit-code: 1
tests: true

View File

@@ -11,55 +11,57 @@ import (
type prometheusCounter struct {
name string
c *dto.Metric
n float64
}
func (c *prometheusCounter) Add(n int) {
addFloat64(c.c.Gauge.Value, float64(n))
addFloat64(&(c.n), float64(n))
}
func (c *prometheusCounter) Dec() {
addFloat64(c.c.Gauge.Value, float64(-1))
addFloat64(&(c.n), float64(-1))
}
func (c *prometheusCounter) Inc() {
addFloat64(c.c.Gauge.Value, float64(1))
addFloat64(&(c.n), float64(1))
}
func (c *prometheusCounter) Get() uint64 {
return uint64(getFloat64(c.c.Gauge.Value))
return uint64(getFloat64(&(c.n)))
}
func (c *prometheusCounter) Set(n uint64) {
setFloat64(c.c.Gauge.Value, math.Float64frombits(n))
setFloat64(&(c.n), math.Float64frombits(n))
}
type prometheusFloatCounter struct {
name string
c *dto.Metric
n float64
}
func (c *prometheusFloatCounter) Add(n float64) {
addFloat64(c.c.Gauge.Value, n)
addFloat64(&(c.n), n)
}
func (c *prometheusFloatCounter) Dec() {
addFloat64(c.c.Gauge.Value, float64(-1))
addFloat64(&(c.n), float64(-1))
}
func (c *prometheusFloatCounter) Inc() {
addFloat64(c.c.Gauge.Value, float64(1))
addFloat64(&(c.n), float64(1))
}
func (c *prometheusFloatCounter) Get() float64 {
return getFloat64(c.c.Gauge.Value)
return getFloat64(&(c.n))
}
func (c *prometheusFloatCounter) Set(n float64) {
setFloat64(c.c.Gauge.Value, n)
setFloat64(&(c.n), n)
}
func (c *prometheusFloatCounter) Sub(n float64) {
addFloat64(c.c.Gauge.Value, -n)
addFloat64(&(c.n), -n)
}
func setFloat64(_addr *float64, value float64) float64 {

View File

@@ -5,8 +5,9 @@ import dto "github.com/prometheus/client_model/go"
type prometheusGauge struct {
name string
c *dto.Metric
n float64
}
func (c prometheusGauge) Get() float64 {
return getFloat64(c.c.Gauge.Value)
func (c *prometheusGauge) Get() float64 {
return getFloat64(&(c.n))
}

14
go.mod
View File

@@ -7,17 +7,21 @@ require (
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
google.golang.org/protobuf v1.35.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/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/klauspost/compress v1.17.11 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/stretchr/testify v1.10.0 // 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/net v0.32.0 // indirect
golang.org/x/sys v0.28.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20241209162323-e6fa225c2576 // indirect
google.golang.org/grpc v1.68.1 // indirect
)

30
go.sum
View File

@@ -2,18 +2,15 @@ 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/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
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/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/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
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/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
@@ -22,23 +19,16 @@ github.com/prometheus/common v0.59.1 h1:LXb1quJHWm1P6wq/U824uxYi4Sg0oGvNeUm1z5dJ
github.com/prometheus/common v0.59.1/go.mod h1:GpWM7dewqmVYcd7SmRaiWVe9SSqjf0UrwnYnpEZNuT0=
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=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
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=
golang.org/x/net v0.32.0 h1:ZqPmj8Kzc+Y6e0+skZsuACbx+wzMgo5MQsJh9Qd6aYI=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
google.golang.org/genproto/googleapis/rpc v0.0.0-20241209162323-e6fa225c2576 h1:8ZmaLZE4XWrtU3MyClkYqqtl6Oegr3235h7jxsDyqCY=
google.golang.org/grpc v1.68.1 h1:oI5oTa11+ng8r8XMMN7jAOmWfPZWbYpCFaMUTACxkM0=
google.golang.org/protobuf v1.35.2 h1:8Ar7bF+apOIoThw1EdZl0p1oWvMqTHmpA2fRTyZO8io=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -5,6 +5,7 @@ import (
"io"
"regexp"
"sync"
"sync/atomic"
"time"
"github.com/prometheus/client_golang/prometheus"
@@ -21,11 +22,11 @@ var _ meter.Meter = (*prometheusMeter)(nil)
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
counter sync.Map
floatCounter sync.Map
gauge sync.Map
histogram sync.Map
summary sync.Map
mfPool xpool.Pool[*dto.MetricFamily]
mu sync.Mutex
}
@@ -34,11 +35,6 @@ 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{}
}),
@@ -53,82 +49,83 @@ 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]
c, ok := m.counter.Load(h)
// fmt.Printf("counter name %s hash %v labels %v\n", name, h, labels)
m.mu.Unlock()
if !ok {
var v float64
mc = &prometheusCounter{
var n float64
c = &prometheusCounter{
name: name,
c: &dto.Metric{
Gauge: &dto.Gauge{Value: &v},
Gauge: &dto.Gauge{Value: &n},
Label: labelMetric(clabels),
},
}
m.mu.Lock()
m.counter[h] = mc
m.counter.Store(h, c)
m.mu.Unlock()
}
return mc
return c.(*prometheusCounter)
}
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]
c, ok := m.counter.Load(h)
m.mu.Unlock()
if !ok {
var v float64
mc = &prometheusFloatCounter{
var n float64
c = &prometheusFloatCounter{
name: name,
c: &dto.Metric{
Gauge: &dto.Gauge{Value: &v},
Gauge: &dto.Gauge{Value: &n},
Label: labelMetric(clabels),
},
}
m.mu.Lock()
m.floatCounter[h] = mc
m.counter.Store(h, c)
m.mu.Unlock()
}
return mc
return c.(*prometheusFloatCounter)
}
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]
c, ok := m.gauge.Load(h)
m.mu.Unlock()
if !ok {
var v float64
mc = &prometheusGauge{
var n float64
c = &prometheusGauge{
name: name,
c: &dto.Metric{
Gauge: &dto.Gauge{Value: &v},
Gauge: &dto.Gauge{Value: &n},
Label: labelMetric(clabels),
},
}
m.mu.Lock()
m.gauge[h] = mc
m.gauge.Store(h, c)
m.mu.Unlock()
}
return mc
return c.(*prometheusGauge)
}
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]
c, ok := m.histogram.Load(h)
m.mu.Unlock()
if !ok {
var c uint64
var n uint64
var s float64
buckets := make([]float64, len(prometheus.DefBuckets))
copy(buckets, prometheus.DefBuckets)
mdto := &dto.Metric{
Histogram: &dto.Histogram{
SampleCount: &c,
SampleCount: &n,
SampleSum: &s,
CreatedTimestamp: timestamppb.Now(),
Bucket: make([]*dto.Bucket, len(buckets)),
@@ -139,31 +136,31 @@ func (m *prometheusMeter) Histogram(name string, labels ...string) meter.Histogr
var cc uint64
mdto.Histogram.Bucket[idx] = &dto.Bucket{CumulativeCount: &cc, UpperBound: &b}
}
mc = &prometheusHistogram{
c = &prometheusHistogram{
name: name,
c: mdto,
}
m.mu.Lock()
m.histogram[h] = mc
m.histogram.Store(h, c)
m.mu.Unlock()
}
return mc
return c.(*prometheusHistogram)
}
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]
c, ok := m.summary.Load(h)
m.mu.Unlock()
if !ok {
var c uint64
var n uint64
var s float64
mc = &prometheusSummary{
c = &prometheusSummary{
name: name,
c: &dto.Metric{
Summary: &dto.Summary{
SampleCount: &c,
SampleCount: &n,
SampleSum: &s,
CreatedTimestamp: timestamppb.Now(),
},
@@ -171,36 +168,36 @@ func (m *prometheusMeter) Summary(name string, labels ...string) meter.Summary {
},
}
m.mu.Lock()
m.summary[h] = mc
m.summary.Store(h, c)
m.mu.Unlock()
}
return mc
return c.(*prometheusSummary)
}
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]
c, ok := m.summary.Load(h)
m.mu.Lock()
if !ok {
var c uint64
var n uint64
var s float64
mc = &prometheusSummary{
c = &prometheusSummary{
name: name,
c: &dto.Metric{
Summary: &dto.Summary{
SampleCount: &c,
SampleCount: &n,
SampleSum: &s,
},
Label: labelMetric(clabels),
},
}
m.mu.Lock()
m.summary[h] = mc
m.summary.Store(h, c)
m.mu.Unlock()
}
return mc
return c.(*prometheusSummary)
}
func (m *prometheusMeter) Init(opts ...meter.Option) error {
@@ -238,45 +235,65 @@ func (m *prometheusMeter) Write(w io.Writer, opts ...meter.Option) error {
m.mu.Lock()
for _, c := range m.counter {
m.counter.Range(func(_ any, v any) bool {
mc := v.(*prometheusCounter)
mf := m.mfPool.Get()
mf.Name = &c.name
mf.Name = &mc.name
mf.Type = dto.MetricType_GAUGE.Enum()
mf.Metric = append(mf.Metric, c.c)
n := getFloat64(&(mc.n))
mc.c.Gauge.Value = &n
mf.Metric = append(mf.Metric, mc.c)
mfs = append(mfs, mf)
}
return true
})
for _, c := range m.floatCounter {
m.floatCounter.Range(func(_ any, v any) bool {
mc := v.(*prometheusFloatCounter)
mf := m.mfPool.Get()
mf.Name = &c.name
mf.Name = &mc.name
mf.Type = dto.MetricType_GAUGE.Enum()
mf.Metric = append(mf.Metric, c.c)
n := getFloat64(&(mc.n))
mc.c.Gauge.Value = &n
mf.Metric = append(mf.Metric, mc.c)
mfs = append(mfs, mf)
}
return true
})
for _, c := range m.gauge {
m.gauge.Range(func(_ any, v any) bool {
mc := v.(*prometheusGauge)
mf := m.mfPool.Get()
mf.Name = &c.name
mf.Name = &mc.name
mf.Type = dto.MetricType_GAUGE.Enum()
mf.Metric = append(mf.Metric, c.c)
n := getFloat64(&(mc.n))
mc.c.Gauge.Value = &n
mf.Metric = append(mf.Metric, mc.c)
mfs = append(mfs, mf)
}
return true
})
for _, c := range m.histogram {
m.histogram.Range(func(_ any, v any) bool {
c := v.(*prometheusHistogram)
mf := m.mfPool.Get()
mf.Name = &c.name
mf.Type = dto.MetricType_HISTOGRAM.Enum()
mf.Metric = append(mf.Metric, c.c)
mfs = append(mfs, mf)
}
return true
})
for _, c := range m.summary {
m.summary.Range(func(_ any, v any) bool {
mc := v.(*prometheusSummary)
mf := m.mfPool.Get()
mf.Name = &c.name
mf.Name = &mc.name
mf.Type = dto.MetricType_SUMMARY.Enum()
mf.Metric = append(mf.Metric, c.c)
sc := atomic.LoadUint64(&(mc.sampleCount))
mc.c.Summary.SampleCount = &sc
ss := getFloat64(&(mc.SampleSum))
mc.c.Summary.SampleSum = &ss
mf.Metric = append(mf.Metric, mc.c)
mfs = append(mfs, mf)
}
return true
})
m.mu.Unlock()
@@ -328,11 +345,13 @@ func (m *prometheusMeter) Set(opts ...meter.Option) meter.Meter {
}
func labelMetric(labels []string) []*dto.LabelPair {
dtoLabels := make([]*dto.LabelPair, 0, len(labels)/2)
for idx := 0; idx < len(labels); idx += 2 {
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: &(labels[idx]),
Value: &(labels[idx+1]),
Name: &(nl[idx]),
Value: &(nl[idx+1]),
})
}
return dtoLabels

View File

@@ -15,11 +15,25 @@ import (
)
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)
m := NewMeter() // meter.Labels("test_key", "test_val"))
buf := bytes.NewBuffer(nil)
for i := 0; i < 100000; i++ {
go func() {
m.Counter("micro_server_request_total", "code", "16",
"endpoint", "/clientprofile.ClientProfileService/GetClientProfile",
"status", "failure").Inc()
m.Counter("micro_server_request_total", "code", "16",
"endpoint", "/clientproduct.ClientProductService/GetDepositProducts",
"status", "failure").Inc()
m.Counter("micro_server_request_total", "code", "16",
"endpoint", "/operationsinfo.OperationsInfoService/GetOperations",
"status", "failure").Inc()
}()
}
_ = m.Write(buf)
t.Logf("h1: %s\n", buf.Bytes())
}
func TestHistogram(t *testing.T) {
@@ -51,7 +65,7 @@ func TestHistogram(t *testing.T) {
p.Observe(10)
p.Observe(30)
mdto := &dto.Metric{}
p.Write(mdto)
_ = 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}}

View File

@@ -10,15 +10,17 @@ import (
type prometheusSummary struct {
name string
c *dto.Metric
sampleCount uint64
SampleSum float64
}
func (c prometheusSummary) Update(n float64) {
atomic.AddUint64(c.c.Summary.SampleCount, 1)
addFloat64(c.c.Summary.SampleSum, n)
func (c *prometheusSummary) Update(n float64) {
atomic.AddUint64(&(c.sampleCount), 1)
addFloat64(&(c.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)
func (c *prometheusSummary) UpdateDuration(t time.Time) {
n := time.Since(t).Seconds()
atomic.AddUint64(&(c.sampleCount), 1)
addFloat64(&(c.SampleSum), n)
}