From e6595c07915d28bc970ca5f2438ae7f9f75f5255 Mon Sep 17 00:00:00 2001 From: Yihang Wang Date: Tue, 7 May 2024 16:18:03 +0800 Subject: [PATCH] feat: add city in instance name --- pkg/utils/string.go | 25 +++++++++++++++++++++++++ pkg/utils/string_test.go | 31 +++++++++++++++++++++++++++++++ prometheus.go | 8 +++++--- 3 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 pkg/utils/string.go create mode 100644 pkg/utils/string_test.go diff --git a/pkg/utils/string.go b/pkg/utils/string.go new file mode 100644 index 0000000..f37e070 --- /dev/null +++ b/pkg/utils/string.go @@ -0,0 +1,25 @@ +package utils + +import "strings" + +func Sanitize(s string) string { + builder := strings.Builder{} + for _, c := range s { + if 'a' <= c && c <= 'z' { + builder.WriteRune(c) + continue + } + if 'A' <= c && c <= 'Z' { + builder.WriteRune(c - 'A' + 'a') + continue + } + if '0' <= c && c <= '9' { + builder.WriteRune(c) + continue + } + if c == ' ' || c == '-' { + builder.WriteString("-") + } + } + return builder.String() +} diff --git a/pkg/utils/string_test.go b/pkg/utils/string_test.go new file mode 100644 index 0000000..1b3eff8 --- /dev/null +++ b/pkg/utils/string_test.go @@ -0,0 +1,31 @@ +package utils_test + +import ( + "fmt" + "testing" + + "github.com/WangYihang/gojob/pkg/utils" +) + +func ExampleSanitize() { + sanitized := utils.Sanitize("New York") + fmt.Println(sanitized) + // Output: new-york +} + +func TestSanitize(t *testing.T) { + testcases := []struct { + s string + want string + }{ + {s: "New York", want: "new-york"}, + {s: "New-York", want: "new-york"}, + {s: "NewYork", want: "newyork"}, + } + for _, testcase := range testcases { + got := utils.Sanitize(testcase.s) + if got != testcase.want { + t.Errorf("Sanitize(%#v), want: %#v, expected: %#v", testcase.s, testcase.want, got) + } + } +} diff --git a/prometheus.go b/prometheus.go index 761abb0..fdfcc70 100644 --- a/prometheus.go +++ b/prometheus.go @@ -3,10 +3,10 @@ package gojob import ( "fmt" "log/slog" - "strings" "sync" "github.com/WangYihang/gojob/pkg/runner" + "github.com/WangYihang/gojob/pkg/utils" "github.com/WangYihang/gojob/pkg/version" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/collectors" @@ -71,11 +71,13 @@ func (g *customMetricsRegistry) Gather() ([]*io_prometheus_client.MetricFamily, return metricFamilies, err } + func prometheusPusher(url, job string, statusChan <-chan Status, wg *sync.WaitGroup) { instance := fmt.Sprintf( - "gojob-%s-%s-%s", + "gojob-%s-%s-%s-%s", version.Version, - strings.ToLower(runner.Runner.Country), + utils.Sanitize(runner.Runner.Country), + utils.Sanitize(runner.Runner.City), runner.Runner.IP, ) registry := NewRegistryWithLabels(map[string]string{