fix: refactor telegraf version (#11656)

This commit is contained in:
Povilas Versockas 2022-08-17 22:08:31 +03:00 committed by GitHub
parent 0481a78ec6
commit 447e8a385e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 44 additions and 77 deletions

View File

@ -45,12 +45,12 @@ MAKEFLAGS += --no-print-directory
GOOS ?= $(shell go env GOOS) GOOS ?= $(shell go env GOOS)
GOARCH ?= $(shell go env GOARCH) GOARCH ?= $(shell go env GOARCH)
HOSTGO := env -u GOOS -u GOARCH -u GOARM -- go HOSTGO := env -u GOOS -u GOARCH -u GOARM -- go
INTERNAL_PKG=github.com/influxdata/telegraf/internal
LDFLAGS := $(LDFLAGS) -X main.commit=$(commit) -X main.branch=$(branch) -X main.goos=$(GOOS) -X main.goarch=$(GOARCH) LDFLAGS := $(LDFLAGS) -X $(INTERNAL_PKG).commit=$(commit) -X $(INTERNAL_PKG).branch=$(branch)
ifneq ($(tag),) ifneq ($(tag),)
LDFLAGS += -X main.version=$(version) LDFLAGS += -X $(INTERNAL_PKG).version=$(version)
else else
LDFLAGS += -X main.version=$(version)-$(commit) LDFLAGS += -X $(INTERNAL_PKG).version=$(version)-$(commit)
endif endif
# Go built-in race detector works only for 64 bits architectures. # Go built-in race detector works only for 64 bits architectures.

View File

@ -126,12 +126,6 @@ var fPlugins = flag.String("plugin-directory", "",
"path to directory containing external plugins") "path to directory containing external plugins")
var fRunOnce = flag.Bool("once", false, "run one gather and exit") var fRunOnce = flag.Bool("once", false, "run one gather and exit")
var (
version string
commit string
branch string
)
var stop chan struct{} var stop chan struct{}
func reloadLoop( func reloadLoop(
@ -277,7 +271,7 @@ func runAgent(ctx context.Context,
logger.SetupLogging(logConfig) logger.SetupLogging(logConfig)
log.Printf("I! Starting Telegraf %s", version) log.Printf("I! Starting Telegraf %s", internal.Version())
log.Printf("I! Loaded inputs: %s", strings.Join(c.InputNames(), " ")) log.Printf("I! Loaded inputs: %s", strings.Join(c.InputNames(), " "))
log.Printf("I! Loaded aggregators: %s", strings.Join(c.AggregatorNames(), " ")) log.Printf("I! Loaded aggregators: %s", strings.Join(c.AggregatorNames(), " "))
log.Printf("I! Loaded processors: %s", strings.Join(c.ProcessorNames(), " ")) log.Printf("I! Loaded processors: %s", strings.Join(c.ProcessorNames(), " "))
@ -348,29 +342,6 @@ func usageExit(rc int) {
os.Exit(rc) os.Exit(rc)
} }
func formatFullVersion() string {
var parts = []string{"Telegraf"}
if version != "" {
parts = append(parts, version)
} else {
parts = append(parts, "unknown")
}
if branch != "" || commit != "" {
if branch == "" {
branch = "unknown"
}
if commit == "" {
commit = "unknown"
}
git := fmt.Sprintf("(git: %s %s)", branch, commit)
parts = append(parts, git)
}
return strings.Join(parts, " ")
}
func deleteEmpty(s []string) []string { func deleteEmpty(s []string) []string {
var r []string var r []string
for _, str := range s { for _, str := range s {
@ -410,11 +381,6 @@ func main() {
logger.SetupLogging(logger.LogConfig{}) logger.SetupLogging(logger.LogConfig{})
// Configure version
if err := internal.SetVersion(version); err != nil {
log.Println("Telegraf version already configured to: " + internal.Version())
}
// Load external plugins, if requested. // Load external plugins, if requested.
if *fPlugins != "" { if *fPlugins != "" {
log.Printf("I! Loading external plugins from: %s", *fPlugins) log.Printf("I! Loading external plugins from: %s", *fPlugins)
@ -443,7 +409,7 @@ func main() {
if len(args) > 0 { if len(args) > 0 {
switch args[0] { switch args[0] {
case "version": case "version":
fmt.Println(formatFullVersion()) fmt.Println(internal.FormatFullVersion())
return return
case "config": case "config":
err := configCmd.Parse(args[1:]) err := configCmd.Parse(args[1:])
@ -534,7 +500,7 @@ func main() {
} }
return return
case *fVersion: case *fVersion:
fmt.Println(formatFullVersion()) fmt.Println(internal.FormatFullVersion())
return return
case *fSampleConfig: case *fSampleConfig:
printer.PrintSampleConfig( printer.PrintSampleConfig(

View File

@ -25,35 +25,48 @@ const alphanum string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrs
var ( var (
ErrTimeout = errors.New("command timed out") ErrTimeout = errors.New("command timed out")
ErrorNotImplemented = errors.New("not implemented yet") ErrorNotImplemented = errors.New("not implemented yet")
ErrorVersionAlreadySet = errors.New("version has already been set")
) )
// Set via the main module // Set via LDFLAGS -X
var version string var (
version = "unknown"
branch = ""
commit = ""
)
type ReadWaitCloser struct { type ReadWaitCloser struct {
pipeReader *io.PipeReader pipeReader *io.PipeReader
wg sync.WaitGroup wg sync.WaitGroup
} }
// SetVersion sets the telegraf agent version
func SetVersion(v string) error {
if version != "" {
return ErrorVersionAlreadySet
}
version = v
if version == "" {
version = "unknown"
}
return nil
}
// Version returns the telegraf agent version // Version returns the telegraf agent version
func Version() string { func Version() string {
return version return version
} }
func FormatFullVersion() string {
var parts = []string{"Telegraf"}
if version != "" {
parts = append(parts, version)
} else {
parts = append(parts, "unknown")
}
if branch != "" || commit != "" {
if branch == "" {
branch = "unknown"
}
if commit == "" {
commit = "unknown"
}
git := fmt.Sprintf("(git: %s@%s)", branch, commit)
parts = append(parts, git)
}
return strings.Join(parts, " ")
}
// ProductToken returns a tag for Telegraf that can be used in user agents. // ProductToken returns a tag for Telegraf that can be used in user agents.
func ProductToken() string { func ProductToken() string {
return fmt.Sprintf("Telegraf/%s Go/%s", return fmt.Sprintf("Telegraf/%s Go/%s",

View File

@ -219,18 +219,6 @@ func TestCompressWithGzipEarlyClose(t *testing.T) {
assert.Equal(t, r1, r2) assert.Equal(t, r1, r2)
} }
func TestVersionAlreadySet(t *testing.T) {
err := SetVersion("foo")
assert.NoError(t, err)
err = SetVersion("bar")
assert.Error(t, err)
assert.IsType(t, ErrorVersionAlreadySet, err)
assert.Equal(t, "foo", Version())
}
func TestAlignDuration(t *testing.T) { func TestAlignDuration(t *testing.T) {
tests := []struct { tests := []struct {
name string name string

View File

@ -21,13 +21,14 @@ func TestSelfPlugin(t *testing.T) {
stat.Incr(1) stat.Incr(1)
stat.Incr(2) stat.Incr(2)
require.NoError(t, s.Gather(acc)) require.NoError(t, s.Gather(acc))
acc.AssertContainsTaggedFields(t, "internal_mytest", acc.AssertContainsTaggedFields(t, "internal_mytest",
map[string]interface{}{ map[string]interface{}{
"test": int64(3), "test": int64(3),
}, },
map[string]string{ map[string]string{
"test": "foo", "test": "foo",
"version": "", "version": "unknown",
}, },
) )
acc.ClearMetrics() acc.ClearMetrics()
@ -41,7 +42,7 @@ func TestSelfPlugin(t *testing.T) {
}, },
map[string]string{ map[string]string{
"test": "foo", "test": "foo",
"version": "", "version": "unknown",
}, },
) )
acc.ClearMetrics() acc.ClearMetrics()
@ -59,7 +60,7 @@ func TestSelfPlugin(t *testing.T) {
}, },
map[string]string{ map[string]string{
"test": "foo", "test": "foo",
"version": "", "version": "unknown",
}, },
) )
} }

View File

@ -4,8 +4,6 @@ package opentelemetry
import ( import (
"context" "context"
_ "embed" _ "embed"
"fmt"
"runtime"
"time" "time"
ntls "crypto/tls" ntls "crypto/tls"
@ -23,11 +21,12 @@ import (
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/common/tls" "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/outputs" "github.com/influxdata/telegraf/plugins/outputs"
) )
var userAgent = fmt.Sprintf("telegraf (%s/%s)", runtime.GOOS, runtime.GOARCH) var userAgent = internal.ProductToken()
// DO NOT REMOVE THE NEXT TWO LINES! This is required to embed the sampleConfig data. // DO NOT REMOVE THE NEXT TWO LINES! This is required to embed the sampleConfig data.
//go:embed sample.conf //go:embed sample.conf