Linter fixes for plugins/inputs/[fg]* (#9387)

This commit is contained in:
Paweł Żak 2021-07-27 23:28:26 +02:00 committed by GitHub
parent 1a42c7d289
commit 87c94e4ac3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 172 additions and 157 deletions

View File

@ -103,29 +103,35 @@ func TestHelperProcess(_ *testing.T) {
if !strings.HasSuffix(cmd, "fail2ban-client") { if !strings.HasSuffix(cmd, "fail2ban-client") {
//nolint:errcheck,revive // Test will fail anyway //nolint:errcheck,revive // Test will fail anyway
fmt.Fprint(os.Stdout, "command not found") fmt.Fprint(os.Stdout, "command not found")
//nolint:revive // os.Exit called intentionally
os.Exit(1) os.Exit(1)
} }
if len(args) == 1 && args[0] == "status" { if len(args) == 1 && args[0] == "status" {
//nolint:errcheck,revive // Test will fail anyway //nolint:errcheck,revive // Test will fail anyway
fmt.Fprint(os.Stdout, execStatusOutput) fmt.Fprint(os.Stdout, execStatusOutput)
//nolint:revive // os.Exit called intentionally
os.Exit(0) os.Exit(0)
} else if len(args) == 2 && args[0] == "status" { } else if len(args) == 2 && args[0] == "status" {
if args[1] == "sshd" { if args[1] == "sshd" {
//nolint:errcheck,revive // Test will fail anyway //nolint:errcheck,revive // Test will fail anyway
fmt.Fprint(os.Stdout, execStatusSshdOutput) fmt.Fprint(os.Stdout, execStatusSshdOutput)
//nolint:revive // os.Exit called intentionally
os.Exit(0) os.Exit(0)
} else if args[1] == "postfix" { } else if args[1] == "postfix" {
//nolint:errcheck,revive // Test will fail anyway //nolint:errcheck,revive // Test will fail anyway
fmt.Fprint(os.Stdout, execStatusPostfixOutput) fmt.Fprint(os.Stdout, execStatusPostfixOutput)
//nolint:revive // os.Exit called intentionally
os.Exit(0) os.Exit(0)
} else if args[1] == "dovecot" { } else if args[1] == "dovecot" {
//nolint:errcheck,revive // Test will fail anyway //nolint:errcheck,revive // Test will fail anyway
fmt.Fprint(os.Stdout, execStatusDovecotOutput) fmt.Fprint(os.Stdout, execStatusDovecotOutput)
//nolint:revive // os.Exit called intentionally
os.Exit(0) os.Exit(0)
} }
} }
//nolint:errcheck,revive // Test will fail anyway //nolint:errcheck,revive // Test will fail anyway
fmt.Fprint(os.Stdout, "invalid argument") fmt.Fprint(os.Stdout, "invalid argument")
//nolint:revive // os.Exit called intentionally
os.Exit(1) os.Exit(1)
} }

View File

@ -11,15 +11,18 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/parsers" "github.com/influxdata/telegraf/plugins/parsers"
"github.com/influxdata/telegraf/plugins/parsers/csv" "github.com/influxdata/telegraf/plugins/parsers/csv"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
func TestRefreshFilePaths(t *testing.T) { func TestRefreshFilePaths(t *testing.T) {
wd, err := os.Getwd() wd, err := os.Getwd()
require.NoError(t, err)
r := File{ r := File{
Files: []string{filepath.Join(wd, "dev/testfiles/**.log")}, Files: []string{filepath.Join(wd, "dev/testfiles/**.log")},
} }
@ -100,7 +103,8 @@ func TestGrokParser(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
err = r.Gather(&acc) err = r.Gather(&acc)
require.Equal(t, len(acc.Metrics), 2) require.NoError(t, err)
require.Len(t, acc.Metrics, 2)
} }
func TestCharacterEncoding(t *testing.T) { func TestCharacterEncoding(t *testing.T) {

View File

@ -53,11 +53,12 @@ func TestRealFS(t *testing.T) {
fs = getTestFileSystem() fs = getTestFileSystem()
// now, the same test as above will return an error as the file doesn't exist in our fake fs // now, the same test as above will return an error as the file doesn't exist in our fake fs
expectedError := "Stat " + getTestdataDir() + "/qux: No such file or directory" expectedError := "Stat " + getTestdataDir() + "/qux: No such file or directory"
fileInfo, err = fs.Stat(getTestdataDir() + "/qux") _, err = fs.Stat(getTestdataDir() + "/qux")
require.Equal(t, expectedError, err.Error()) require.Error(t, err, expectedError)
// and verify that what we DO expect to find, we do // and verify that what we DO expect to find, we do
fileInfo, err = fs.Stat("/testdata/foo") fileInfo, err = fs.Stat("/testdata/foo")
require.NoError(t, err) require.NoError(t, err)
require.NotNil(t, fileInfo)
} }
func getTestFileSystem() fakeFileSystem { func getTestFileSystem() fakeFileSystem {

View File

@ -114,11 +114,11 @@ func (f *FileStat) Gather(acc telegraf.Accumulator) error {
} }
if f.Md5 { if f.Md5 {
md5, err := getMd5(fileName) md5Hash, err := getMd5(fileName)
if err != nil { if err != nil {
acc.AddError(err) acc.AddError(err)
} else { } else {
fields["md5_sum"] = md5 fields["md5_sum"] = md5Hash
} }
} }

View File

@ -198,7 +198,7 @@ func TestGetMd5(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, "5a7e9b77fa25e7bb411dbd17cf403c1f", md5) require.Equal(t, "5a7e9b77fa25e7bb411dbd17cf403c1f", md5)
md5, err = getMd5("/tmp/foo/bar/fooooo") _, err = getMd5("/tmp/foo/bar/fooooo")
require.Error(t, err) require.Error(t, err)
} }

View File

@ -63,11 +63,11 @@ func parse(data []byte) (datapointArray []pluginData, err error) {
if err = json.Unmarshal(data, &endpointData); err != nil { if err = json.Unmarshal(data, &endpointData); err != nil {
err = fmt.Errorf("processing JSON structure") err = fmt.Errorf("processing JSON structure")
return return nil, err
} }
datapointArray = append(datapointArray, endpointData.Payload...) datapointArray = append(datapointArray, endpointData.Payload...)
return return datapointArray, err
} }
// Description - display description // Description - display description

View File

@ -8,8 +8,9 @@ import (
"net/url" "net/url"
"testing" "testing"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/testutil"
) )
// sampleJSON from fluentd version '0.14.9' // sampleJSON from fluentd version '0.14.9'
@ -127,6 +128,8 @@ func Test_Gather(t *testing.T) {
})) }))
requestURL, err := url.Parse(fluentdTest.Endpoint) requestURL, err := url.Parse(fluentdTest.Endpoint)
require.NoError(t, err)
require.NotNil(t, requestURL)
ts.Listener, _ = net.Listen("tcp", fmt.Sprintf("%s:%s", requestURL.Hostname(), requestURL.Port())) ts.Listener, _ = net.Listen("tcp", fmt.Sprintf("%s:%s", requestURL.Hostname(), requestURL.Port()))

View File

@ -8,12 +8,13 @@ import (
"sync" "sync"
"time" "time"
"github.com/google/go-github/v32/github" githubLib "github.com/google/go-github/v32/github"
"golang.org/x/oauth2"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs" "github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/selfstat" "github.com/influxdata/telegraf/selfstat"
"golang.org/x/oauth2"
) )
// GitHub - plugin main structure // GitHub - plugin main structure
@ -23,7 +24,7 @@ type GitHub struct {
AdditionalFields []string `toml:"additional_fields"` AdditionalFields []string `toml:"additional_fields"`
EnterpriseBaseURL string `toml:"enterprise_base_url"` EnterpriseBaseURL string `toml:"enterprise_base_url"`
HTTPTimeout config.Duration `toml:"http_timeout"` HTTPTimeout config.Duration `toml:"http_timeout"`
githubClient *github.Client githubClient *githubLib.Client
obfuscatedToken string obfuscatedToken string
@ -68,7 +69,7 @@ func (g *GitHub) Description() string {
} }
// Create GitHub Client // Create GitHub Client
func (g *GitHub) createGitHubClient(ctx context.Context) (*github.Client, error) { func (g *GitHub) createGitHubClient(ctx context.Context) (*githubLib.Client, error) {
httpClient := &http.Client{ httpClient := &http.Client{
Transport: &http.Transport{ Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment, Proxy: http.ProxyFromEnvironment,
@ -93,11 +94,11 @@ func (g *GitHub) createGitHubClient(ctx context.Context) (*github.Client, error)
return g.newGithubClient(httpClient) return g.newGithubClient(httpClient)
} }
func (g *GitHub) newGithubClient(httpClient *http.Client) (*github.Client, error) { func (g *GitHub) newGithubClient(httpClient *http.Client) (*githubLib.Client, error) {
if g.EnterpriseBaseURL != "" { if g.EnterpriseBaseURL != "" {
return github.NewEnterpriseClient(g.EnterpriseBaseURL, "", httpClient) return githubLib.NewEnterpriseClient(g.EnterpriseBaseURL, "", httpClient)
} }
return github.NewClient(httpClient), nil return githubLib.NewClient(httpClient), nil
} }
// Gather GitHub Metrics // Gather GitHub Metrics
@ -172,16 +173,16 @@ func (g *GitHub) Gather(acc telegraf.Accumulator) error {
return nil return nil
} }
func (g *GitHub) handleRateLimit(response *github.Response, err error) { func (g *GitHub) handleRateLimit(response *githubLib.Response, err error) {
if err == nil { if err == nil {
g.RateLimit.Set(int64(response.Rate.Limit)) g.RateLimit.Set(int64(response.Rate.Limit))
g.RateRemaining.Set(int64(response.Rate.Remaining)) g.RateRemaining.Set(int64(response.Rate.Remaining))
} else if _, ok := err.(*github.RateLimitError); ok { } else if _, ok := err.(*githubLib.RateLimitError); ok {
g.RateLimitErrors.Incr(1) g.RateLimitErrors.Incr(1)
} }
} }
func splitRepositoryName(repositoryName string) (string, string, error) { func splitRepositoryName(repositoryName string) (owner string, repository string, err error) {
splits := strings.SplitN(repositoryName, "/", 2) splits := strings.SplitN(repositoryName, "/", 2)
if len(splits) != 2 { if len(splits) != 2 {
@ -191,7 +192,7 @@ func splitRepositoryName(repositoryName string) (string, string, error) {
return splits[0], splits[1], nil return splits[0], splits[1], nil
} }
func getLicense(rI *github.Repository) string { func getLicense(rI *githubLib.Repository) string {
if licenseName := rI.GetLicense().GetName(); licenseName != "" { if licenseName := rI.GetLicense().GetName(); licenseName != "" {
return licenseName return licenseName
} }
@ -199,7 +200,7 @@ func getLicense(rI *github.Repository) string {
return "None" return "None"
} }
func getTags(repositoryInfo *github.Repository) map[string]string { func getTags(repositoryInfo *githubLib.Repository) map[string]string {
return map[string]string{ return map[string]string{
"owner": repositoryInfo.GetOwner().GetLogin(), "owner": repositoryInfo.GetOwner().GetLogin(),
"name": repositoryInfo.GetName(), "name": repositoryInfo.GetName(),
@ -208,7 +209,7 @@ func getTags(repositoryInfo *github.Repository) map[string]string {
} }
} }
func getFields(repositoryInfo *github.Repository) map[string]interface{} { func getFields(repositoryInfo *githubLib.Repository) map[string]interface{} {
return map[string]interface{}{ return map[string]interface{}{
"stars": repositoryInfo.GetStargazersCount(), "stars": repositoryInfo.GetStargazersCount(),
"subscribers": repositoryInfo.GetSubscribersCount(), "subscribers": repositoryInfo.GetSubscribersCount(),
@ -221,9 +222,9 @@ func getFields(repositoryInfo *github.Repository) map[string]interface{} {
} }
func (g *GitHub) getPullRequestFields(ctx context.Context, owner, repo string) (map[string]interface{}, error) { func (g *GitHub) getPullRequestFields(ctx context.Context, owner, repo string) (map[string]interface{}, error) {
options := github.SearchOptions{ options := githubLib.SearchOptions{
TextMatch: false, TextMatch: false,
ListOptions: github.ListOptions{ ListOptions: githubLib.ListOptions{
PerPage: 100, PerPage: 100,
Page: 1, Page: 1,
}, },

View File

@ -14,16 +14,17 @@ import (
"sync" "sync"
"time" "time"
gnmiLib "github.com/openconfig/gnmi/proto/gnmi"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
internaltls "github.com/influxdata/telegraf/plugins/common/tls" internaltls "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs" "github.com/influxdata/telegraf/plugins/inputs"
jsonparser "github.com/influxdata/telegraf/plugins/parsers/json" jsonparser "github.com/influxdata/telegraf/plugins/parsers/json"
"github.com/openconfig/gnmi/proto/gnmi"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
) )
// gNMI plugin instance // gNMI plugin instance
@ -51,10 +52,10 @@ type GNMI struct {
internaltls.ClientConfig internaltls.ClientConfig
// Internal state // Internal state
aliases map[string]string internalAliases map[string]string
acc telegraf.Accumulator acc telegraf.Accumulator
cancel context.CancelFunc cancel context.CancelFunc
wg sync.WaitGroup wg sync.WaitGroup
Log telegraf.Logger Log telegraf.Logger
} }
@ -79,7 +80,7 @@ func (c *GNMI) Start(acc telegraf.Accumulator) error {
var err error var err error
var ctx context.Context var ctx context.Context
var tlscfg *tls.Config var tlscfg *tls.Config
var request *gnmi.SubscribeRequest var request *gnmiLib.SubscribeRequest
c.acc = acc c.acc = acc
ctx, c.cancel = context.WithCancel(context.Background()) ctx, c.cancel = context.WithCancel(context.Background())
@ -102,9 +103,9 @@ func (c *GNMI) Start(acc telegraf.Accumulator) error {
} }
// Invert explicit alias list and prefill subscription names // Invert explicit alias list and prefill subscription names
c.aliases = make(map[string]string, len(c.Subscriptions)+len(c.Aliases)) c.internalAliases = make(map[string]string, len(c.Subscriptions)+len(c.Aliases))
for _, subscription := range c.Subscriptions { for _, subscription := range c.Subscriptions {
var gnmiLongPath, gnmiShortPath *gnmi.Path var gnmiLongPath, gnmiShortPath *gnmiLib.Path
// Build the subscription path without keys // Build the subscription path without keys
if gnmiLongPath, err = parsePath(subscription.Origin, subscription.Path, ""); err != nil { if gnmiLongPath, err = parsePath(subscription.Origin, subscription.Path, ""); err != nil {
@ -129,12 +130,12 @@ func (c *GNMI) Start(acc telegraf.Accumulator) error {
name = path.Base(shortPath) name = path.Base(shortPath)
} }
if len(name) > 0 { if len(name) > 0 {
c.aliases[longPath] = name c.internalAliases[longPath] = name
c.aliases[shortPath] = name c.internalAliases[shortPath] = name
} }
} }
for alias, path := range c.Aliases { for alias, encodingPath := range c.Aliases {
c.aliases[path] = alias c.internalAliases[encodingPath] = alias
} }
// Create a goroutine for each device, dial and subscribe // Create a goroutine for each device, dial and subscribe
@ -158,21 +159,21 @@ func (c *GNMI) Start(acc telegraf.Accumulator) error {
} }
// Create a new gNMI SubscribeRequest // Create a new gNMI SubscribeRequest
func (c *GNMI) newSubscribeRequest() (*gnmi.SubscribeRequest, error) { func (c *GNMI) newSubscribeRequest() (*gnmiLib.SubscribeRequest, error) {
// Create subscription objects // Create subscription objects
subscriptions := make([]*gnmi.Subscription, len(c.Subscriptions)) subscriptions := make([]*gnmiLib.Subscription, len(c.Subscriptions))
for i, subscription := range c.Subscriptions { for i, subscription := range c.Subscriptions {
gnmiPath, err := parsePath(subscription.Origin, subscription.Path, "") gnmiPath, err := parsePath(subscription.Origin, subscription.Path, "")
if err != nil { if err != nil {
return nil, err return nil, err
} }
mode, ok := gnmi.SubscriptionMode_value[strings.ToUpper(subscription.SubscriptionMode)] mode, ok := gnmiLib.SubscriptionMode_value[strings.ToUpper(subscription.SubscriptionMode)]
if !ok { if !ok {
return nil, fmt.Errorf("invalid subscription mode %s", subscription.SubscriptionMode) return nil, fmt.Errorf("invalid subscription mode %s", subscription.SubscriptionMode)
} }
subscriptions[i] = &gnmi.Subscription{ subscriptions[i] = &gnmiLib.Subscription{
Path: gnmiPath, Path: gnmiPath,
Mode: gnmi.SubscriptionMode(mode), Mode: gnmiLib.SubscriptionMode(mode),
SampleInterval: uint64(time.Duration(subscription.SampleInterval).Nanoseconds()), SampleInterval: uint64(time.Duration(subscription.SampleInterval).Nanoseconds()),
SuppressRedundant: subscription.SuppressRedundant, SuppressRedundant: subscription.SuppressRedundant,
HeartbeatInterval: uint64(time.Duration(subscription.HeartbeatInterval).Nanoseconds()), HeartbeatInterval: uint64(time.Duration(subscription.HeartbeatInterval).Nanoseconds()),
@ -189,12 +190,12 @@ func (c *GNMI) newSubscribeRequest() (*gnmi.SubscribeRequest, error) {
return nil, fmt.Errorf("unsupported encoding %s", c.Encoding) return nil, fmt.Errorf("unsupported encoding %s", c.Encoding)
} }
return &gnmi.SubscribeRequest{ return &gnmiLib.SubscribeRequest{
Request: &gnmi.SubscribeRequest_Subscribe{ Request: &gnmiLib.SubscribeRequest_Subscribe{
Subscribe: &gnmi.SubscriptionList{ Subscribe: &gnmiLib.SubscriptionList{
Prefix: gnmiPath, Prefix: gnmiPath,
Mode: gnmi.SubscriptionList_STREAM, Mode: gnmiLib.SubscriptionList_STREAM,
Encoding: gnmi.Encoding(gnmi.Encoding_value[strings.ToUpper(c.Encoding)]), Encoding: gnmiLib.Encoding(gnmiLib.Encoding_value[strings.ToUpper(c.Encoding)]),
Subscription: subscriptions, Subscription: subscriptions,
UpdatesOnly: c.UpdatesOnly, UpdatesOnly: c.UpdatesOnly,
}, },
@ -203,7 +204,7 @@ func (c *GNMI) newSubscribeRequest() (*gnmi.SubscribeRequest, error) {
} }
// SubscribeGNMI and extract telemetry data // SubscribeGNMI and extract telemetry data
func (c *GNMI) subscribeGNMI(ctx context.Context, address string, tlscfg *tls.Config, request *gnmi.SubscribeRequest) error { func (c *GNMI) subscribeGNMI(ctx context.Context, address string, tlscfg *tls.Config, request *gnmiLib.SubscribeRequest) error {
var opt grpc.DialOption var opt grpc.DialOption
if tlscfg != nil { if tlscfg != nil {
opt = grpc.WithTransportCredentials(credentials.NewTLS(tlscfg)) opt = grpc.WithTransportCredentials(credentials.NewTLS(tlscfg))
@ -217,7 +218,7 @@ func (c *GNMI) subscribeGNMI(ctx context.Context, address string, tlscfg *tls.Co
} }
defer client.Close() defer client.Close()
subscribeClient, err := gnmi.NewGNMIClient(client).Subscribe(ctx) subscribeClient, err := gnmiLib.NewGNMIClient(client).Subscribe(ctx)
if err != nil { if err != nil {
return fmt.Errorf("failed to setup subscription: %v", err) return fmt.Errorf("failed to setup subscription: %v", err)
} }
@ -233,7 +234,7 @@ func (c *GNMI) subscribeGNMI(ctx context.Context, address string, tlscfg *tls.Co
c.Log.Debugf("Connection to gNMI device %s established", address) c.Log.Debugf("Connection to gNMI device %s established", address)
defer c.Log.Debugf("Connection to gNMI device %s closed", address) defer c.Log.Debugf("Connection to gNMI device %s closed", address)
for ctx.Err() == nil { for ctx.Err() == nil {
var reply *gnmi.SubscribeResponse var reply *gnmiLib.SubscribeResponse
if reply, err = subscribeClient.Recv(); err != nil { if reply, err = subscribeClient.Recv(); err != nil {
if err != io.EOF && ctx.Err() == nil { if err != io.EOF && ctx.Err() == nil {
return fmt.Errorf("aborted gNMI subscription: %v", err) return fmt.Errorf("aborted gNMI subscription: %v", err)
@ -246,17 +247,17 @@ func (c *GNMI) subscribeGNMI(ctx context.Context, address string, tlscfg *tls.Co
return nil return nil
} }
func (c *GNMI) handleSubscribeResponse(address string, reply *gnmi.SubscribeResponse) { func (c *GNMI) handleSubscribeResponse(address string, reply *gnmiLib.SubscribeResponse) {
switch response := reply.Response.(type) { switch response := reply.Response.(type) {
case *gnmi.SubscribeResponse_Update: case *gnmiLib.SubscribeResponse_Update:
c.handleSubscribeResponseUpdate(address, response) c.handleSubscribeResponseUpdate(address, response)
case *gnmi.SubscribeResponse_Error: case *gnmiLib.SubscribeResponse_Error:
c.Log.Errorf("Subscribe error (%d), %q", response.Error.Code, response.Error.Message) c.Log.Errorf("Subscribe error (%d), %q", response.Error.Code, response.Error.Message)
} }
} }
// Handle SubscribeResponse_Update message from gNMI and parse contained telemetry data // Handle SubscribeResponse_Update message from gNMI and parse contained telemetry data
func (c *GNMI) handleSubscribeResponseUpdate(address string, response *gnmi.SubscribeResponse_Update) { func (c *GNMI) handleSubscribeResponseUpdate(address string, response *gnmiLib.SubscribeResponse_Update) {
var prefix, prefixAliasPath string var prefix, prefixAliasPath string
grouper := metric.NewSeriesGrouper() grouper := metric.NewSeriesGrouper()
timestamp := time.Unix(0, response.Update.Timestamp) timestamp := time.Unix(0, response.Update.Timestamp)
@ -289,7 +290,7 @@ func (c *GNMI) handleSubscribeResponseUpdate(address string, response *gnmi.Subs
// Lookup alias if alias-path has changed // Lookup alias if alias-path has changed
if aliasPath != lastAliasPath { if aliasPath != lastAliasPath {
name = prefix name = prefix
if alias, ok := c.aliases[aliasPath]; ok { if alias, ok := c.internalAliases[aliasPath]; ok {
name = alias name = alias
} else { } else {
c.Log.Debugf("No measurement alias for gNMI path: %s", name) c.Log.Debugf("No measurement alias for gNMI path: %s", name)
@ -325,13 +326,13 @@ func (c *GNMI) handleSubscribeResponseUpdate(address string, response *gnmi.Subs
} }
// Add grouped measurements // Add grouped measurements
for _, metric := range grouper.Metrics() { for _, metricToAdd := range grouper.Metrics() {
c.acc.AddMetric(metric) c.acc.AddMetric(metricToAdd)
} }
} }
// HandleTelemetryField and add it to a measurement // HandleTelemetryField and add it to a measurement
func (c *GNMI) handleTelemetryField(update *gnmi.Update, tags map[string]string, prefix string) (string, map[string]interface{}) { func (c *GNMI) handleTelemetryField(update *gnmiLib.Update, tags map[string]string, prefix string) (string, map[string]interface{}) {
gpath, aliasPath, err := c.handlePath(update.Path, tags, prefix) gpath, aliasPath, err := c.handlePath(update.Path, tags, prefix)
if err != nil { if err != nil {
c.Log.Errorf("handling path %q failed: %v", update.Path, err) c.Log.Errorf("handling path %q failed: %v", update.Path, err)
@ -347,25 +348,25 @@ func (c *GNMI) handleTelemetryField(update *gnmi.Update, tags map[string]string,
} }
switch val := update.Val.Value.(type) { switch val := update.Val.Value.(type) {
case *gnmi.TypedValue_AsciiVal: case *gnmiLib.TypedValue_AsciiVal:
value = val.AsciiVal value = val.AsciiVal
case *gnmi.TypedValue_BoolVal: case *gnmiLib.TypedValue_BoolVal:
value = val.BoolVal value = val.BoolVal
case *gnmi.TypedValue_BytesVal: case *gnmiLib.TypedValue_BytesVal:
value = val.BytesVal value = val.BytesVal
case *gnmi.TypedValue_DecimalVal: case *gnmiLib.TypedValue_DecimalVal:
value = float64(val.DecimalVal.Digits) / math.Pow(10, float64(val.DecimalVal.Precision)) value = float64(val.DecimalVal.Digits) / math.Pow(10, float64(val.DecimalVal.Precision))
case *gnmi.TypedValue_FloatVal: case *gnmiLib.TypedValue_FloatVal:
value = val.FloatVal value = val.FloatVal
case *gnmi.TypedValue_IntVal: case *gnmiLib.TypedValue_IntVal:
value = val.IntVal value = val.IntVal
case *gnmi.TypedValue_StringVal: case *gnmiLib.TypedValue_StringVal:
value = val.StringVal value = val.StringVal
case *gnmi.TypedValue_UintVal: case *gnmiLib.TypedValue_UintVal:
value = val.UintVal value = val.UintVal
case *gnmi.TypedValue_JsonIetfVal: case *gnmiLib.TypedValue_JsonIetfVal:
jsondata = val.JsonIetfVal jsondata = val.JsonIetfVal
case *gnmi.TypedValue_JsonVal: case *gnmiLib.TypedValue_JsonVal:
jsondata = val.JsonVal jsondata = val.JsonVal
} }
@ -387,13 +388,12 @@ func (c *GNMI) handleTelemetryField(update *gnmi.Update, tags map[string]string,
} }
// Parse path to path-buffer and tag-field // Parse path to path-buffer and tag-field
func (c *GNMI) handlePath(path *gnmi.Path, tags map[string]string, prefix string) (string, string, error) { func (c *GNMI) handlePath(gnmiPath *gnmiLib.Path, tags map[string]string, prefix string) (pathBuffer string, aliasPath string, err error) {
var aliasPath string
builder := bytes.NewBufferString(prefix) builder := bytes.NewBufferString(prefix)
// Prefix with origin // Prefix with origin
if len(path.Origin) > 0 { if len(gnmiPath.Origin) > 0 {
if _, err := builder.WriteString(path.Origin); err != nil { if _, err := builder.WriteString(gnmiPath.Origin); err != nil {
return "", "", err return "", "", err
} }
if _, err := builder.WriteRune(':'); err != nil { if _, err := builder.WriteRune(':'); err != nil {
@ -402,7 +402,7 @@ func (c *GNMI) handlePath(path *gnmi.Path, tags map[string]string, prefix string
} }
// Parse generic keys from prefix // Parse generic keys from prefix
for _, elem := range path.Elem { for _, elem := range gnmiPath.Elem {
if len(elem.Name) > 0 { if len(elem.Name) > 0 {
if _, err := builder.WriteRune('/'); err != nil { if _, err := builder.WriteRune('/'); err != nil {
return "", "", err return "", "", err
@ -413,7 +413,7 @@ func (c *GNMI) handlePath(path *gnmi.Path, tags map[string]string, prefix string
} }
name := builder.String() name := builder.String()
if _, exists := c.aliases[name]; exists { if _, exists := c.internalAliases[name]; exists {
aliasPath = name aliasPath = name
} }
@ -435,21 +435,21 @@ func (c *GNMI) handlePath(path *gnmi.Path, tags map[string]string, prefix string
} }
//ParsePath from XPath-like string to gNMI path structure //ParsePath from XPath-like string to gNMI path structure
func parsePath(origin string, path string, target string) (*gnmi.Path, error) { func parsePath(origin string, pathToParse string, target string) (*gnmiLib.Path, error) {
var err error var err error
gnmiPath := gnmi.Path{Origin: origin, Target: target} gnmiPath := gnmiLib.Path{Origin: origin, Target: target}
if len(path) > 0 && path[0] != '/' { if len(pathToParse) > 0 && pathToParse[0] != '/' {
return nil, fmt.Errorf("path does not start with a '/': %s", path) return nil, fmt.Errorf("path does not start with a '/': %s", pathToParse)
} }
elem := &gnmi.PathElem{} elem := &gnmiLib.PathElem{}
start, name, value, end := 0, -1, -1, -1 start, name, value, end := 0, -1, -1, -1
path = path + "/" pathToParse = pathToParse + "/"
for i := 0; i < len(path); i++ { for i := 0; i < len(pathToParse); i++ {
if path[i] == '[' { if pathToParse[i] == '[' {
if name >= 0 { if name >= 0 {
break break
} }
@ -458,37 +458,37 @@ func parsePath(origin string, path string, target string) (*gnmi.Path, error) {
elem.Key = make(map[string]string) elem.Key = make(map[string]string)
} }
name = i + 1 name = i + 1
} else if path[i] == '=' { } else if pathToParse[i] == '=' {
if name <= 0 || value >= 0 { if name <= 0 || value >= 0 {
break break
} }
value = i + 1 value = i + 1
} else if path[i] == ']' { } else if pathToParse[i] == ']' {
if name <= 0 || value <= name { if name <= 0 || value <= name {
break break
} }
elem.Key[path[name:value-1]] = strings.Trim(path[value:i], "'\"") elem.Key[pathToParse[name:value-1]] = strings.Trim(pathToParse[value:i], "'\"")
name, value = -1, -1 name, value = -1, -1
} else if path[i] == '/' { } else if pathToParse[i] == '/' {
if name < 0 { if name < 0 {
if end < 0 { if end < 0 {
end = i end = i
} }
if end > start { if end > start {
elem.Name = path[start:end] elem.Name = pathToParse[start:end]
gnmiPath.Elem = append(gnmiPath.Elem, elem) gnmiPath.Elem = append(gnmiPath.Elem, elem)
gnmiPath.Element = append(gnmiPath.Element, path[start:i]) gnmiPath.Element = append(gnmiPath.Element, pathToParse[start:i])
} }
start, name, value, end = i+1, -1, -1, -1 start, name, value, end = i+1, -1, -1, -1
elem = &gnmi.PathElem{} elem = &gnmiLib.PathElem{}
} }
} }
} }
if name >= 0 || value >= 0 { if name >= 0 || value >= 0 {
err = fmt.Errorf("Invalid gNMI path: %s", path) err = fmt.Errorf("Invalid gNMI path: %s", pathToParse)
} }
if err != nil { if err != nil {

View File

@ -9,54 +9,54 @@ import (
"testing" "testing"
"time" "time"
"github.com/influxdata/telegraf" gnmiLib "github.com/openconfig/gnmi/proto/gnmi"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
"github.com/openconfig/gnmi/proto/gnmi"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/metadata" "google.golang.org/grpc/metadata"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
) )
func TestParsePath(t *testing.T) { func TestParsePath(t *testing.T) {
path := "/foo/bar/bla[shoo=woo][shoop=/woop/]/z" path := "/foo/bar/bla[shoo=woo][shoop=/woop/]/z"
parsed, err := parsePath("theorigin", path, "thetarget") parsed, err := parsePath("theorigin", path, "thetarget")
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, parsed.Origin, "theorigin") require.Equal(t, "theorigin", parsed.Origin)
assert.Equal(t, parsed.Target, "thetarget") require.Equal(t, "thetarget", parsed.Target)
assert.Equal(t, parsed.Element, []string{"foo", "bar", "bla[shoo=woo][shoop=/woop/]", "z"}) require.Equal(t, []string{"foo", "bar", "bla[shoo=woo][shoop=/woop/]", "z"}, parsed.Element)
assert.Equal(t, parsed.Elem, []*gnmi.PathElem{{Name: "foo"}, {Name: "bar"}, require.Equal(t, []*gnmiLib.PathElem{{Name: "foo"}, {Name: "bar"},
{Name: "bla", Key: map[string]string{"shoo": "woo", "shoop": "/woop/"}}, {Name: "z"}}) {Name: "bla", Key: map[string]string{"shoo": "woo", "shoop": "/woop/"}}, {Name: "z"}}, parsed.Elem)
parsed, err = parsePath("", "", "") parsed, err = parsePath("", "", "")
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, *parsed, gnmi.Path{}) require.Equal(t, gnmiLib.Path{}, *parsed)
parsed, err = parsePath("", "/foo[[", "") parsed, err = parsePath("", "/foo[[", "")
assert.Nil(t, parsed) require.Nil(t, parsed)
assert.Equal(t, errors.New("Invalid gNMI path: /foo[[/"), err) require.Equal(t, errors.New("Invalid gNMI path: /foo[[/"), err)
} }
type MockServer struct { type MockServer struct {
SubscribeF func(gnmi.GNMI_SubscribeServer) error SubscribeF func(gnmiLib.GNMI_SubscribeServer) error
GRPCServer *grpc.Server GRPCServer *grpc.Server
} }
func (s *MockServer) Capabilities(context.Context, *gnmi.CapabilityRequest) (*gnmi.CapabilityResponse, error) { func (s *MockServer) Capabilities(context.Context, *gnmiLib.CapabilityRequest) (*gnmiLib.CapabilityResponse, error) {
return nil, nil return nil, nil
} }
func (s *MockServer) Get(context.Context, *gnmi.GetRequest) (*gnmi.GetResponse, error) { func (s *MockServer) Get(context.Context, *gnmiLib.GetRequest) (*gnmiLib.GetResponse, error) {
return nil, nil return nil, nil
} }
func (s *MockServer) Set(context.Context, *gnmi.SetRequest) (*gnmi.SetResponse, error) { func (s *MockServer) Set(context.Context, *gnmiLib.SetRequest) (*gnmiLib.SetResponse, error) {
return nil, nil return nil, nil
} }
func (s *MockServer) Subscribe(server gnmi.GNMI_SubscribeServer) error { func (s *MockServer) Subscribe(server gnmiLib.GNMI_SubscribeServer) error {
return s.SubscribeF(server) return s.SubscribeF(server)
} }
@ -66,12 +66,12 @@ func TestWaitError(t *testing.T) {
grpcServer := grpc.NewServer() grpcServer := grpc.NewServer()
gnmiServer := &MockServer{ gnmiServer := &MockServer{
SubscribeF: func(server gnmi.GNMI_SubscribeServer) error { SubscribeF: func(server gnmiLib.GNMI_SubscribeServer) error {
return fmt.Errorf("testerror") return fmt.Errorf("testerror")
}, },
GRPCServer: grpcServer, GRPCServer: grpcServer,
} }
gnmi.RegisterGNMIServer(grpcServer, gnmiServer) gnmiLib.RegisterGNMIServer(grpcServer, gnmiServer)
plugin := &GNMI{ plugin := &GNMI{
Log: testutil.Logger{}, Log: testutil.Logger{},
@ -107,7 +107,7 @@ func TestUsernamePassword(t *testing.T) {
grpcServer := grpc.NewServer() grpcServer := grpc.NewServer()
gnmiServer := &MockServer{ gnmiServer := &MockServer{
SubscribeF: func(server gnmi.GNMI_SubscribeServer) error { SubscribeF: func(server gnmiLib.GNMI_SubscribeServer) error {
metadata, ok := metadata.FromIncomingContext(server.Context()) metadata, ok := metadata.FromIncomingContext(server.Context())
if !ok { if !ok {
return errors.New("failed to get metadata") return errors.New("failed to get metadata")
@ -127,7 +127,7 @@ func TestUsernamePassword(t *testing.T) {
}, },
GRPCServer: grpcServer, GRPCServer: grpcServer,
} }
gnmi.RegisterGNMIServer(grpcServer, gnmiServer) gnmiLib.RegisterGNMIServer(grpcServer, gnmiServer)
plugin := &GNMI{ plugin := &GNMI{
Log: testutil.Logger{}, Log: testutil.Logger{},
@ -159,12 +159,12 @@ func TestUsernamePassword(t *testing.T) {
errors.New("aborted gNMI subscription: rpc error: code = Unknown desc = success")) errors.New("aborted gNMI subscription: rpc error: code = Unknown desc = success"))
} }
func mockGNMINotification() *gnmi.Notification { func mockGNMINotification() *gnmiLib.Notification {
return &gnmi.Notification{ return &gnmiLib.Notification{
Timestamp: 1543236572000000000, Timestamp: 1543236572000000000,
Prefix: &gnmi.Path{ Prefix: &gnmiLib.Path{
Origin: "type", Origin: "type",
Elem: []*gnmi.PathElem{ Elem: []*gnmiLib.PathElem{
{ {
Name: "model", Name: "model",
Key: map[string]string{"foo": "bar"}, Key: map[string]string{"foo": "bar"},
@ -172,35 +172,35 @@ func mockGNMINotification() *gnmi.Notification {
}, },
Target: "subscription", Target: "subscription",
}, },
Update: []*gnmi.Update{ Update: []*gnmiLib.Update{
{ {
Path: &gnmi.Path{ Path: &gnmiLib.Path{
Elem: []*gnmi.PathElem{ Elem: []*gnmiLib.PathElem{
{Name: "some"}, {Name: "some"},
{ {
Name: "path", Name: "path",
Key: map[string]string{"name": "str", "uint64": "1234"}}, Key: map[string]string{"name": "str", "uint64": "1234"}},
}, },
}, },
Val: &gnmi.TypedValue{Value: &gnmi.TypedValue_IntVal{IntVal: 5678}}, Val: &gnmiLib.TypedValue{Value: &gnmiLib.TypedValue_IntVal{IntVal: 5678}},
}, },
{ {
Path: &gnmi.Path{ Path: &gnmiLib.Path{
Elem: []*gnmi.PathElem{ Elem: []*gnmiLib.PathElem{
{Name: "other"}, {Name: "other"},
{Name: "path"}, {Name: "path"},
}, },
}, },
Val: &gnmi.TypedValue{Value: &gnmi.TypedValue_StringVal{StringVal: "foobar"}}, Val: &gnmiLib.TypedValue{Value: &gnmiLib.TypedValue_StringVal{StringVal: "foobar"}},
}, },
{ {
Path: &gnmi.Path{ Path: &gnmiLib.Path{
Elem: []*gnmi.PathElem{ Elem: []*gnmiLib.PathElem{
{Name: "other"}, {Name: "other"},
{Name: "this"}, {Name: "this"},
}, },
}, },
Val: &gnmi.TypedValue{Value: &gnmi.TypedValue_StringVal{StringVal: "that"}}, Val: &gnmiLib.TypedValue{Value: &gnmiLib.TypedValue_StringVal{StringVal: "that"}},
}, },
}, },
} }
@ -229,20 +229,20 @@ func TestNotification(t *testing.T) {
}, },
}, },
server: &MockServer{ server: &MockServer{
SubscribeF: func(server gnmi.GNMI_SubscribeServer) error { SubscribeF: func(server gnmiLib.GNMI_SubscribeServer) error {
notification := mockGNMINotification() notification := mockGNMINotification()
err := server.Send(&gnmi.SubscribeResponse{Response: &gnmi.SubscribeResponse_Update{Update: notification}}) err := server.Send(&gnmiLib.SubscribeResponse{Response: &gnmiLib.SubscribeResponse_Update{Update: notification}})
if err != nil { if err != nil {
return err return err
} }
err = server.Send(&gnmi.SubscribeResponse{Response: &gnmi.SubscribeResponse_SyncResponse{SyncResponse: true}}) err = server.Send(&gnmiLib.SubscribeResponse{Response: &gnmiLib.SubscribeResponse_SyncResponse{SyncResponse: true}})
if err != nil { if err != nil {
return err return err
} }
notification.Prefix.Elem[0].Key["foo"] = "bar2" notification.Prefix.Elem[0].Key["foo"] = "bar2"
notification.Update[0].Path.Elem[1].Key["name"] = "str2" notification.Update[0].Path.Elem[1].Key["name"] = "str2"
notification.Update[0].Val = &gnmi.TypedValue{Value: &gnmi.TypedValue_JsonVal{JsonVal: []byte{'"', '1', '2', '3', '"'}}} notification.Update[0].Val = &gnmiLib.TypedValue{Value: &gnmiLib.TypedValue_JsonVal{JsonVal: []byte{'"', '1', '2', '3', '"'}}}
return server.Send(&gnmi.SubscribeResponse{Response: &gnmi.SubscribeResponse_Update{Update: notification}}) return server.Send(&gnmiLib.SubscribeResponse{Response: &gnmiLib.SubscribeResponse_Update{Update: notification}})
}, },
}, },
expected: []telegraf.Metric{ expected: []telegraf.Metric{
@ -318,14 +318,14 @@ func TestNotification(t *testing.T) {
}, },
}, },
server: &MockServer{ server: &MockServer{
SubscribeF: func(server gnmi.GNMI_SubscribeServer) error { SubscribeF: func(server gnmiLib.GNMI_SubscribeServer) error {
response := &gnmi.SubscribeResponse{ response := &gnmiLib.SubscribeResponse{
Response: &gnmi.SubscribeResponse_Update{ Response: &gnmiLib.SubscribeResponse_Update{
Update: &gnmi.Notification{ Update: &gnmiLib.Notification{
Timestamp: 1543236572000000000, Timestamp: 1543236572000000000,
Prefix: &gnmi.Path{ Prefix: &gnmiLib.Path{
Origin: "type", Origin: "type",
Elem: []*gnmi.PathElem{ Elem: []*gnmiLib.PathElem{
{ {
Name: "state", Name: "state",
}, },
@ -342,11 +342,11 @@ func TestNotification(t *testing.T) {
}, },
Target: "subscription", Target: "subscription",
}, },
Update: []*gnmi.Update{ Update: []*gnmiLib.Update{
{ {
Path: &gnmi.Path{}, Path: &gnmiLib.Path{},
Val: &gnmi.TypedValue{ Val: &gnmiLib.TypedValue{
Value: &gnmi.TypedValue_IntVal{IntVal: 42}, Value: &gnmiLib.TypedValue_IntVal{IntVal: 42},
}, },
}, },
}, },
@ -382,7 +382,7 @@ func TestNotification(t *testing.T) {
grpcServer := grpc.NewServer() grpcServer := grpc.NewServer()
tt.server.GRPCServer = grpcServer tt.server.GRPCServer = grpcServer
gnmi.RegisterGNMIServer(grpcServer, tt.server) gnmiLib.RegisterGNMIServer(grpcServer, tt.server)
var acc testutil.Accumulator var acc testutil.Accumulator
err = tt.plugin.Start(&acc) err = tt.plugin.Start(&acc)
@ -424,10 +424,10 @@ func TestSubscribeResponseError(t *testing.T) {
ml := &MockLogger{} ml := &MockLogger{}
plugin := &GNMI{Log: ml} plugin := &GNMI{Log: ml}
// TODO: FIX SA1019: gnmi.Error is deprecated: Do not use. // TODO: FIX SA1019: gnmi.Error is deprecated: Do not use.
errorResponse := &gnmi.SubscribeResponse_Error{Error: &gnmi.Error{Message: me, Code: mc}} errorResponse := &gnmiLib.SubscribeResponse_Error{Error: &gnmiLib.Error{Message: me, Code: mc}}
plugin.handleSubscribeResponse("127.0.0.1:0", &gnmi.SubscribeResponse{Response: errorResponse}) plugin.handleSubscribeResponse("127.0.0.1:0", &gnmiLib.SubscribeResponse{Response: errorResponse})
require.NotEmpty(t, ml.lastFormat) require.NotEmpty(t, ml.lastFormat)
require.Equal(t, ml.lastArgs, []interface{}{mc, me}) require.Equal(t, []interface{}{mc, me}, ml.lastArgs)
} }
func TestRedial(t *testing.T) { func TestRedial(t *testing.T) {
@ -443,13 +443,13 @@ func TestRedial(t *testing.T) {
grpcServer := grpc.NewServer() grpcServer := grpc.NewServer()
gnmiServer := &MockServer{ gnmiServer := &MockServer{
SubscribeF: func(server gnmi.GNMI_SubscribeServer) error { SubscribeF: func(server gnmiLib.GNMI_SubscribeServer) error {
notification := mockGNMINotification() notification := mockGNMINotification()
return server.Send(&gnmi.SubscribeResponse{Response: &gnmi.SubscribeResponse_Update{Update: notification}}) return server.Send(&gnmiLib.SubscribeResponse{Response: &gnmiLib.SubscribeResponse_Update{Update: notification}})
}, },
GRPCServer: grpcServer, GRPCServer: grpcServer,
} }
gnmi.RegisterGNMIServer(grpcServer, gnmiServer) gnmiLib.RegisterGNMIServer(grpcServer, gnmiServer)
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(1) wg.Add(1)
@ -473,16 +473,16 @@ func TestRedial(t *testing.T) {
grpcServer = grpc.NewServer() grpcServer = grpc.NewServer()
gnmiServer = &MockServer{ gnmiServer = &MockServer{
SubscribeF: func(server gnmi.GNMI_SubscribeServer) error { SubscribeF: func(server gnmiLib.GNMI_SubscribeServer) error {
notification := mockGNMINotification() notification := mockGNMINotification()
notification.Prefix.Elem[0].Key["foo"] = "bar2" notification.Prefix.Elem[0].Key["foo"] = "bar2"
notification.Update[0].Path.Elem[1].Key["name"] = "str2" notification.Update[0].Path.Elem[1].Key["name"] = "str2"
notification.Update[0].Val = &gnmi.TypedValue{Value: &gnmi.TypedValue_BoolVal{BoolVal: false}} notification.Update[0].Val = &gnmiLib.TypedValue{Value: &gnmiLib.TypedValue_BoolVal{BoolVal: false}}
return server.Send(&gnmi.SubscribeResponse{Response: &gnmi.SubscribeResponse_Update{Update: notification}}) return server.Send(&gnmiLib.SubscribeResponse{Response: &gnmiLib.SubscribeResponse_Update{Update: notification}})
}, },
GRPCServer: grpcServer, GRPCServer: grpcServer,
} }
gnmi.RegisterGNMIServer(grpcServer, gnmiServer) gnmiLib.RegisterGNMIServer(grpcServer, gnmiServer)
wg.Add(1) wg.Add(1)
go func() { go func() {