Skip to content

Commit

Permalink
fix: Linter fixes for plugins/inputs/m* (influxdata#10006)
Browse files Browse the repository at this point in the history
  • Loading branch information
zak-pawel authored Nov 2, 2021
1 parent e6b107b commit c1d4ce4
Show file tree
Hide file tree
Showing 22 changed files with 400 additions and 375 deletions.
30 changes: 16 additions & 14 deletions plugins/inputs/mailchimp/chimp_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"regexp"
"sync"
"time"

"github.com/influxdata/telegraf"
)

const (
Expand All @@ -22,11 +23,12 @@ var mailchimpDatacenter = regexp.MustCompile("[a-z]+[0-9]+$")

type ChimpAPI struct {
Transport http.RoundTripper
Debug bool
debug bool

sync.Mutex

url *url.URL
log telegraf.Logger
}

type ReportsParams struct {
Expand All @@ -53,12 +55,12 @@ func (p *ReportsParams) String() string {
return v.Encode()
}

func NewChimpAPI(apiKey string) *ChimpAPI {
func NewChimpAPI(apiKey string, log telegraf.Logger) *ChimpAPI {
u := &url.URL{}
u.Scheme = "https"
u.Host = fmt.Sprintf("%s.api.mailchimp.com", mailchimpDatacenter.FindString(apiKey))
u.User = url.UserPassword("", apiKey)
return &ChimpAPI{url: u}
return &ChimpAPI{url: u, log: log}
}

type APIError struct {
Expand Down Expand Up @@ -90,7 +92,7 @@ func (a *ChimpAPI) GetReports(params ReportsParams) (ReportsResponse, error) {
a.url.Path = reportsEndpoint

var response ReportsResponse
rawjson, err := runChimp(a, params)
rawjson, err := a.runChimp(params)
if err != nil {
return response, err
}
Expand All @@ -109,7 +111,7 @@ func (a *ChimpAPI) GetReport(campaignID string) (Report, error) {
a.url.Path = fmt.Sprintf(reportsEndpointCampaign, campaignID)

var response Report
rawjson, err := runChimp(a, ReportsParams{})
rawjson, err := a.runChimp(ReportsParams{})
if err != nil {
return response, err
}
Expand All @@ -122,21 +124,21 @@ func (a *ChimpAPI) GetReport(campaignID string) (Report, error) {
return response, nil
}

func runChimp(api *ChimpAPI, params ReportsParams) ([]byte, error) {
func (a *ChimpAPI) runChimp(params ReportsParams) ([]byte, error) {
client := &http.Client{
Transport: api.Transport,
Transport: a.Transport,
Timeout: 4 * time.Second,
}

var b bytes.Buffer
req, err := http.NewRequest("GET", api.url.String(), &b)
req, err := http.NewRequest("GET", a.url.String(), &b)
if err != nil {
return nil, err
}
req.URL.RawQuery = params.String()
req.Header.Set("User-Agent", "Telegraf-MailChimp-Plugin")
if api.Debug {
log.Printf("D! [inputs.mailchimp] request URL: %s", req.URL.String())
if a.debug {
a.log.Debugf("request URL: %s", req.URL.String())
}

resp, err := client.Do(req)
Expand All @@ -148,15 +150,15 @@ func runChimp(api *ChimpAPI, params ReportsParams) ([]byte, error) {
if resp.StatusCode != http.StatusOK {
// ignore the err here; LimitReader returns io.EOF and we're not interested in read errors.
body, _ := io.ReadAll(io.LimitReader(resp.Body, 200))
return nil, fmt.Errorf("%s returned HTTP status %s: %q", api.url.String(), resp.Status, body)
return nil, fmt.Errorf("%s returned HTTP status %s: %q", a.url.String(), resp.Status, body)
}

body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if api.Debug {
log.Printf("D! [inputs.mailchimp] response Body: %q", string(body))
if a.debug {
a.log.Debugf("response Body: %q", string(body))
}

if err = chimpErrorCheck(body); err != nil {
Expand Down
13 changes: 8 additions & 5 deletions plugins/inputs/mailchimp/mailchimp.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ type MailChimp struct {
APIKey string `toml:"api_key"`
DaysOld int `toml:"days_old"`
CampaignID string `toml:"campaign_id"`

Log telegraf.Logger `toml:"-"`
}

var sampleConfig = `
Expand All @@ -35,12 +37,13 @@ func (m *MailChimp) Description() string {
return "Gathers metrics from the /3.0/reports MailChimp API"
}

func (m *MailChimp) Gather(acc telegraf.Accumulator) error {
if m.api == nil {
m.api = NewChimpAPI(m.APIKey)
}
m.api.Debug = false
func (m *MailChimp) Init() error {
m.api = NewChimpAPI(m.APIKey, m.Log)

return nil
}

func (m *MailChimp) Gather(acc telegraf.Accumulator) error {
if m.CampaignID == "" {
since := ""
if m.DaysOld > 0 {
Expand Down
45 changes: 24 additions & 21 deletions plugins/inputs/mailchimp/mailchimp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import (
"net/url"
"testing"

"github.com/influxdata/telegraf/testutil"

"github.com/stretchr/testify/require"

"github.com/influxdata/telegraf/testutil"
)

func TestMailChimpGatherReports(t *testing.T) {
Expand All @@ -28,7 +28,8 @@ func TestMailChimpGatherReports(t *testing.T) {

api := &ChimpAPI{
url: u,
Debug: true,
debug: true,
log: testutil.Logger{},
}
m := MailChimp{
api: api,
Expand All @@ -43,22 +44,22 @@ func TestMailChimpGatherReports(t *testing.T) {
tags["campaign_title"] = "Freddie's Jokes Vol. 1"

fields := map[string]interface{}{
"emails_sent": int(200),
"abuse_reports": int(0),
"unsubscribed": int(2),
"hard_bounces": int(0),
"soft_bounces": int(2),
"syntax_errors": int(0),
"forwards_count": int(0),
"forwards_opens": int(0),
"opens_total": int(186),
"unique_opens": int(100),
"clicks_total": int(42),
"unique_clicks": int(400),
"unique_subscriber_clicks": int(42),
"facebook_recipient_likes": int(5),
"facebook_unique_likes": int(8),
"facebook_likes": int(42),
"emails_sent": 200,
"abuse_reports": 0,
"unsubscribed": 2,
"hard_bounces": 0,
"soft_bounces": 2,
"syntax_errors": 0,
"forwards_count": 0,
"forwards_opens": 0,
"opens_total": 186,
"unique_opens": 100,
"clicks_total": 42,
"unique_clicks": 400,
"unique_subscriber_clicks": 42,
"facebook_recipient_likes": 5,
"facebook_unique_likes": 8,
"facebook_likes": 42,
"open_rate": float64(42),
"click_rate": float64(42),
"industry_open_rate": float64(0.17076777144396),
Expand Down Expand Up @@ -92,7 +93,8 @@ func TestMailChimpGatherReport(t *testing.T) {

api := &ChimpAPI{
url: u,
Debug: true,
debug: true,
log: testutil.Logger{},
}
m := MailChimp{
api: api,
Expand Down Expand Up @@ -157,7 +159,8 @@ func TestMailChimpGatherError(t *testing.T) {

api := &ChimpAPI{
url: u,
Debug: true,
debug: true,
log: testutil.Logger{},
}
m := MailChimp{
api: api,
Expand Down
8 changes: 4 additions & 4 deletions plugins/inputs/marklogic/marklogic.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,9 @@ func (c *Marklogic) Gather(accumulator telegraf.Accumulator) error {
return nil
}

func (c *Marklogic) fetchAndInsertData(acc telegraf.Accumulator, url string) error {
func (c *Marklogic) fetchAndInsertData(acc telegraf.Accumulator, address string) error {
ml := &MlHost{}
if err := c.gatherJSONData(url, ml); err != nil {
if err := c.gatherJSONData(address, ml); err != nil {
return err
}

Expand Down Expand Up @@ -225,8 +225,8 @@ func (c *Marklogic) createHTTPClient() (*http.Client, error) {
return client, nil
}

func (c *Marklogic) gatherJSONData(url string, v interface{}) error {
req, err := http.NewRequest("GET", url, nil)
func (c *Marklogic) gatherJSONData(address string, v interface{}) error {
req, err := http.NewRequest("GET", address, nil)
if err != nil {
return err
}
Expand Down
21 changes: 11 additions & 10 deletions plugins/inputs/mcrouter/mcrouter.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,32 +146,33 @@ func (m *Mcrouter) Gather(acc telegraf.Accumulator) error {
}

// ParseAddress parses an address string into 'host:port' and 'protocol' parts
func (m *Mcrouter) ParseAddress(address string) (string, string, error) {
var protocol string
func (m *Mcrouter) ParseAddress(address string) (parsedAddress string, protocol string, err error) {
var host string
var port string

u, parseError := url.Parse(address)
parsedAddress = address

u, parseError := url.Parse(parsedAddress)

if parseError != nil {
return "", "", fmt.Errorf("Invalid server address")
return "", "", fmt.Errorf("invalid server address")
}

if u.Scheme != "tcp" && u.Scheme != "unix" {
return "", "", fmt.Errorf("Invalid server protocol")
return "", "", fmt.Errorf("invalid server protocol")
}

protocol = u.Scheme

if protocol == "unix" {
if u.Path == "" {
return "", "", fmt.Errorf("Invalid unix socket path")
return "", "", fmt.Errorf("invalid unix socket path")
}

address = u.Path
parsedAddress = u.Path
} else {
if u.Host == "" {
return "", "", fmt.Errorf("Invalid host")
return "", "", fmt.Errorf("invalid host")
}

host = u.Hostname()
Expand All @@ -185,10 +186,10 @@ func (m *Mcrouter) ParseAddress(address string) (string, string, error) {
port = defaultServerURL.Port()
}

address = host + ":" + port
parsedAddress = host + ":" + port
}

return address, protocol, nil
return parsedAddress, protocol, nil
}

func (m *Mcrouter) gatherServer(ctx context.Context, address string, acc telegraf.Accumulator) error {
Expand Down
20 changes: 10 additions & 10 deletions plugins/inputs/mcrouter/mcrouter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import (
"strings"
"testing"

"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/influxdata/telegraf/testutil"
)

func TestAddressParsing(t *testing.T) {
Expand All @@ -30,17 +30,17 @@ func TestAddressParsing(t *testing.T) {
for _, args := range acceptTests {
address, protocol, err := m.ParseAddress(args[0])

assert.Nil(t, err, args[0])
assert.True(t, address == args[1], args[0])
assert.True(t, protocol == args[2], args[0])
require.Nil(t, err, args[0])
require.Equal(t, args[1], address, args[0])
require.Equal(t, args[2], protocol, args[0])
}

for _, addr := range rejectTests {
address, protocol, err := m.ParseAddress(addr)

assert.NotNil(t, err, addr)
assert.Empty(t, address, addr)
assert.Empty(t, protocol, addr)
require.NotNil(t, err, addr)
require.Empty(t, address, addr)
require.Empty(t, protocol, addr)
}
}

Expand Down Expand Up @@ -129,11 +129,11 @@ func TestMcrouterGeneratesMetricsIntegration(t *testing.T) {
}

for _, metric := range intMetrics {
assert.True(t, acc.HasInt64Field("mcrouter", metric), metric)
require.True(t, acc.HasInt64Field("mcrouter", metric), metric)
}

for _, metric := range floatMetrics {
assert.True(t, acc.HasFloatField("mcrouter", metric), metric)
require.True(t, acc.HasFloatField("mcrouter", metric), metric)
}
}

Expand Down
11 changes: 6 additions & 5 deletions plugins/inputs/mdstat/mdstat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import (
"os"
"testing"

"github.com/stretchr/testify/require"

"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
)

func TestFullMdstatProcFile(t *testing.T) {
Expand All @@ -19,7 +20,7 @@ func TestFullMdstatProcFile(t *testing.T) {
}
acc := testutil.Accumulator{}
err := k.Gather(&acc)
assert.NoError(t, err)
require.NoError(t, err)

fields := map[string]interface{}{
"BlocksSynced": int64(10620027200),
Expand All @@ -46,7 +47,7 @@ func TestFailedDiskMdStatProcFile1(t *testing.T) {

acc := testutil.Accumulator{}
err := k.Gather(&acc)
assert.NoError(t, err)
require.NoError(t, err)

fields := map[string]interface{}{
"BlocksSynced": int64(5860144128),
Expand All @@ -73,7 +74,7 @@ func TestEmptyMdStatProcFile1(t *testing.T) {

acc := testutil.Accumulator{}
err := k.Gather(&acc)
assert.NoError(t, err)
require.NoError(t, err)
}

func TestInvalidMdStatProcFile1(t *testing.T) {
Expand All @@ -86,7 +87,7 @@ func TestInvalidMdStatProcFile1(t *testing.T) {

acc := testutil.Accumulator{}
err := k.Gather(&acc)
assert.Error(t, err)
require.Error(t, err)
}

const mdStatFileFull = `
Expand Down
Loading

0 comments on commit c1d4ce4

Please sign in to comment.