Commit cffb4c37 authored by Michael Schurter's avatar Michael Schurter
Browse files

consul: truncate output strings to 200 characters

parent 4fd5e8c5
Branches unavailable
No related merge requests found
Showing with 75 additions and 3 deletions
+75 -3
......@@ -3,6 +3,7 @@ package taskrunner
import (
"context"
"fmt"
"strings"
"sync"
"time"
......@@ -14,6 +15,7 @@ import (
"github.com/hashicorp/nomad/client/consul"
"github.com/hashicorp/nomad/client/taskenv"
agentconsul "github.com/hashicorp/nomad/command/agent/consul"
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/nomad/structs"
)
......@@ -21,8 +23,14 @@ var _ interfaces.TaskPoststartHook = &scriptCheckHook{}
var _ interfaces.TaskUpdateHook = &scriptCheckHook{}
var _ interfaces.TaskStopHook = &scriptCheckHook{}
// default max amount of time to wait for all scripts on shutdown.
const defaultShutdownWait = time.Minute
const (
// default max amount of time to wait for all scripts on shutdown.
defaultShutdownWait = time.Minute
// maxOutputMsgSize is the max length of script check output that will
// be logged
maxOutputMsgSize = 200
)
type scriptCheckHookConfig struct {
alloc *structs.Allocation
......@@ -372,7 +380,8 @@ func newScriptCheckCallback(s *scriptCheck) taskletCallback {
// If the check is unhealthy, log the output
if state == api.HealthCritical || state == api.HealthWarning {
s.logger.Warn("unhealthy script check", "health", state, "output", hclog.Quote(outputMsg))
trimmed := helper.TruncateString(strings.TrimSpace(outputMsg), maxOutputMsgSize)
s.logger.Warn("unhealthy script check", "health", state, "output", hclog.Quote(trimmed))
}
// heartbeat the check to Consul
......
......@@ -551,3 +551,14 @@ func PathEscapesSandbox(sandboxDir, path string) bool {
}
return false
}
// TruncateString ensures a string is below max characters. If not the string
// is truncated to "max-3" and "..." are appended.
//
// Max must be > 3
func TruncateString(s string, max int) string {
if len(s) > max {
return s[:max-3] + "..."
}
return s
}
......@@ -8,6 +8,7 @@ import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
......@@ -403,3 +404,54 @@ func TestPathEscapesSandbox(t *testing.T) {
})
}
}
func TestTruncateString(t *testing.T) {
cases := []struct {
In string
Max int
Out string
}{
{
In: "Hello World!",
Max: 3,
Out: "...",
},
{
In: "Hello World!",
Max: 4,
Out: "H...",
},
{
In: "Hello World!",
Max: 5,
Out: "He...",
},
{
In: "Hello World!",
Max: 11,
Out: "Hello Wo...",
},
{
In: "Hello World!",
Max: 12,
Out: "Hello World!",
},
{
In: "Hello World!",
Max: 13,
Out: "Hello World!",
},
{
In: "",
Max: 3,
Out: "",
},
}
for _, tc := range cases {
t.Run(fmt.Sprintf("%s-%d-%s", tc.In, tc.Max, tc.Out), func(t *testing.T) {
out := TruncateString(tc.In, tc.Max)
assert.Equal(t, tc.Out, out)
})
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment