From 7bb219222a6fdc26954f5a1f05991730f377a718 Mon Sep 17 00:00:00 2001 From: Kevin Conaway Date: Tue, 9 Oct 2018 16:45:07 -0400 Subject: [PATCH] Add internal function for telegraf version (#4828) --- cmd/telegraf/telegraf.go | 10 ++++++++++ internal/internal.go | 19 +++++++++++++++++++ internal/internal_test.go | 12 ++++++++++++ 3 files changed, 41 insertions(+) diff --git a/cmd/telegraf/telegraf.go b/cmd/telegraf/telegraf.go index 93336ffb4..02f22353b 100644 --- a/cmd/telegraf/telegraf.go +++ b/cmd/telegraf/telegraf.go @@ -326,6 +326,16 @@ func main() { return } + shortVersion := version + if shortVersion == "" { + shortVersion = "unknown" + } + + // Configure version + if err := internal.SetVersion(shortVersion); err != nil { + log.Println("Telegraf version already configured to: " + internal.Version()) + } + if runtime.GOOS == "windows" && !(*fRunAsConsole) { svcConfig := &service.Config{ Name: *fServiceName, diff --git a/internal/internal.go b/internal/internal.go index 6d087cceb..f6b85de84 100644 --- a/internal/internal.go +++ b/internal/internal.go @@ -24,13 +24,32 @@ var ( TimeoutErr = errors.New("Command timed out.") NotImplementedError = errors.New("not implemented yet") + + VersionAlreadySetError = errors.New("version has already been set") ) +// Set via the main module +var version string + // Duration just wraps time.Duration type Duration struct { Duration time.Duration } +// SetVersion sets the telegraf agent version +func SetVersion(v string) error { + if version != "" { + return VersionAlreadySetError + } + version = v + return nil +} + +// Version returns the telegraf agent version +func Version() string { + return version +} + // UnmarshalTOML parses the duration from the TOML config file func (d *Duration) UnmarshalTOML(b []byte) error { var err error diff --git a/internal/internal_test.go b/internal/internal_test.go index 3b4ec5dda..486c3d744 100644 --- a/internal/internal_test.go +++ b/internal/internal_test.go @@ -182,3 +182,15 @@ func TestCompressWithGzip(t *testing.T) { assert.Equal(t, testData, string(output)) } + +func TestVersionAlreadySet(t *testing.T) { + err := SetVersion("foo") + assert.Nil(t, err) + + err = SetVersion("bar") + + assert.NotNil(t, err) + assert.IsType(t, VersionAlreadySetError, err) + + assert.Equal(t, "foo", Version()) +}