Skip to content

Commit

Permalink
Merge branch 'v3' into cciutea/fix_storer_file_collision
Browse files Browse the repository at this point in the history
  • Loading branch information
cristianciutea authored Mar 30, 2021
2 parents bbcd118 + 30ec2d6 commit 2e12863
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 13 deletions.
22 changes: 17 additions & 5 deletions jmx/jmx.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
Expand All @@ -23,7 +24,6 @@ import (
const (
jmxLineInitialBuffer = 4 * 1024 // initial 4KB per line, it'll be increased when required
cmdStdChanLen = 1000
defaultNrjmxExec = "/usr/bin/nrjmx" // defaultNrjmxExec default nrjmx tool executable path
)

// Error vars to ease Query response handling.
Expand Down Expand Up @@ -80,7 +80,7 @@ func (cfg *connectionConfig) isSSL() bool {
}

func (cfg *connectionConfig) command() []string {
c := make([]string, 0)
var c []string
if os.Getenv("NR_JMX_TOOL") != "" {
c = strings.Split(os.Getenv("NR_JMX_TOOL"), " ")
} else {
Expand Down Expand Up @@ -133,7 +133,7 @@ func Open(hostname, port, username, password string, opts ...Option) error {
port: port,
username: username,
password: password,
executablePath: defaultNrjmxExec,
executablePath: filepath.Clean(defaultNrjmxExec),
}

for _, opt := range opts {
Expand Down Expand Up @@ -342,6 +342,7 @@ func Query(objectPattern string, timeoutMillis int) (result map[string]interface

// receiveResult checks for channels to receive result from nrjmx command.
func receiveResult(lineC chan []byte, queryErrC chan error, cancelFn context.CancelFunc, objectPattern string, timeout time.Duration) (result map[string]interface{}, err error) {
defer logAvailableWarnings(cmdWarnC)
var warn string
for {
select {
Expand All @@ -362,12 +363,11 @@ func receiveResult(lineC chan []byte, queryErrC chan error, cancelFn context.Can
for k, v := range r {
result[k] = v
}

return

case warn = <-cmdWarnC:
// change on the API is required to return warnings
log.Warn(warn)
return

case err = <-cmdErrC:
return
Expand All @@ -384,3 +384,15 @@ func receiveResult(lineC chan []byte, queryErrC chan error, cancelFn context.Can
}
}
}

func logAvailableWarnings(channel chan string) {
var warn string
for {
select {
case warn = <-channel:
log.Warn(warn)
default:
return
}
}
}
43 changes: 35 additions & 8 deletions jmx/jmx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@ package jmx

import (
"bufio"
"bytes"
"context"
"flag"
"fmt"
"os"
"runtime"
"strings"
"testing"
"time"

"github.com/newrelic/infra-integrations-sdk/log"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -41,7 +44,7 @@ func TestMain(m *testing.M) {
if testType == "" {
// Set the NR_JMX_TOOL to ourselves (the test binary) with the extra
// parameter test.type=helper and run the tests as usual.
os.Setenv("NR_JMX_TOOL", fmt.Sprintf("%s -test.type helper --", os.Args[0]))
_ = os.Setenv("NR_JMX_TOOL", fmt.Sprintf("%s -test.type helper --", os.Args[0]))
os.Exit(m.Run())
} else if testType == "helper" {
// The test suite becomes a JMX Tool
Expand All @@ -59,10 +62,12 @@ func TestMain(m *testing.M) {
fmt.Println("{}")
} else if command == cmdBigPayload {
// Create a payload of more than 64K
fmt.Println(fmt.Sprintf("{\"first\": 1%s}", strings.Repeat(", \"s\": 2", 70*1024)))
str := fmt.Sprintf("{\"first\": 1%s}", strings.Repeat(", \"s\": 2", 70*1024))
fmt.Println(str)
} else if command == cmdBigPayloadErr {
// Create a payload of more than 4M
fmt.Println(fmt.Sprintf("{\"first\": 1%s}", strings.Repeat(", \"s\": 2", 4*1024*1024)))
str := fmt.Sprintf("{\"first\": 1%s}", strings.Repeat(", \"s\": 2", 4*1024*1024))
fmt.Println(str)
}

}
Expand Down Expand Up @@ -177,17 +182,39 @@ func openWaitWithSSL(hostname, port, username, password, keyStore, keyStorePassw
}

func Test_receiveResult_warningsDoNotBreakResultReception(t *testing.T) {

var buf bytes.Buffer
log.SetOutput(&buf)

_, cancelFn := context.WithCancel(context.Background())

// clean cmdErrC global variable to avoid test fail on different execution orders.
cmdErrC = make(chan error, cmdStdChanLen)
resultCh := make(chan []byte, 1)
queryErrCh := make(chan error)
outTimeout := time.Duration(timeoutMillis) * time.Millisecond
warningMessage := fmt.Sprint("WARNING foo bar")
cmdWarnC <- warningMessage

_, _ = receiveResult(resultCh, queryErrCh, cancelFn, "empty", outTimeout)
resultCh <- []byte("{\"foo\":1}")

cmdErrC <- fmt.Errorf("WARNING foo bar")
assert.Equal(t, <-cmdErrC, fmt.Errorf("WARNING foo bar"))
result, err := receiveResult(resultCh, queryErrCh, cancelFn, "foo", outTimeout)

resultCh <- []byte("{foo}")
assert.Equal(t, string(<-resultCh), "{foo}")
assert.NoError(t, err)
assert.Equal(t, map[string]interface{}{
"foo": 1.,
}, result)
assert.Equal(t, fmt.Sprintf("[WARN] %s\n", warningMessage), buf.String())
}

func Test_DefaultPath_IsCorrectForOs(t *testing.T) {
os := runtime.GOOS
switch os {
case "windows":
case "darwin":
case "linux":
assert.True(t, len(defaultNrjmxExec) > 0)
default:
t.Fatal("unexpected value")
}
}
11 changes: 11 additions & 0 deletions jmx/jmx_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// +build linux darwin

/*
Package jmx is a library to get metrics through JMX. It requires additional
setup. Read https://github.com/newrelic/infra-integrations-sdk#jmx-support for
instructions. */
package jmx

const (
defaultNrjmxExec = "/usr/bin/nrjmx" // defaultNrjmxExec default nrjmx tool executable path
)
11 changes: 11 additions & 0 deletions jmx/jmx_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// +build windows

/*
Package jmx is a library to get metrics through JMX. It requires additional
setup. Read https://github.com/newrelic/infra-integrations-sdk#jmx-support for
instructions. */
package jmx

const (
defaultNrjmxExec = "c:\\progra~1\\newrel~1\\nrjmx\\nrjmx.bat" // defaultNrjmxExec default nrjmx tool executable path
)
5 changes: 5 additions & 0 deletions log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ func SetupLogging(verbose bool) {
}
}

// SetOutput sets output stream
func SetOutput(w io.Writer) {
globalLogger.logger.SetOutput(w)
}

// Debug logs a formatted message at level Debug.
func Debug(format string, args ...interface{}) {
globalLogger.Debugf(format, args...)
Expand Down

0 comments on commit 2e12863

Please sign in to comment.