Skip to content

Commit

Permalink
Merge pull request #707 from fluxcd/trim-condition-msg
Browse files Browse the repository at this point in the history
runtime: Trim the condition message to the max accepted length
  • Loading branch information
stefanprodan authored Dec 13, 2023
2 parents b446682 + dcc7e93 commit 1169458
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
25 changes: 24 additions & 1 deletion runtime/conditions/setter.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ import (
"sort"
"time"

"github.com/fluxcd/pkg/apis/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

"github.com/fluxcd/pkg/apis/meta"
)

// Setter is an interface that defines methods a Kubernetes object should implement in order to
Expand All @@ -51,6 +52,9 @@ func Set(to Setter, condition *metav1.Condition) {
// Always set the observed generation on the condition.
condition.ObservedGeneration = to.GetGeneration()

// Trim the message to the maximum accepted length.
condition.Message = trimConditionMessage(condition.Message, maxMessageLength)

// Check if the new conditions already exists, and change it only if there is a status
// transition (otherwise we should preserve the current last transition time)-
conditions := to.GetConditions()
Expand Down Expand Up @@ -223,3 +227,22 @@ func hasSameState(i, j *metav1.Condition) bool {
i.Reason == j.Reason &&
i.Message == j.Message
}

const (
maxMessageLength = 32768
trimmedMessageSuffix = "..."
)

// trimConditionMessage trims the condition message to the specified maximum length.
func trimConditionMessage(msg string, maxLength int) string {
if maxLength < len(trimmedMessageSuffix) {
maxLength = len(trimmedMessageSuffix)
}

if len(msg) <= maxLength {
return msg
}

trimmedMsg := msg[:maxLength-len(trimmedMessageSuffix)] + trimmedMessageSuffix
return trimmedMsg
}
30 changes: 30 additions & 0 deletions runtime/conditions/setter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,36 @@ func TestSetAggregate(t *testing.T) {
g.Expect(Has(target, "foo")).To(BeTrue())
}

func TestTrimConditionMessage(t *testing.T) {
tests := []struct {
message string
maxLength int
expected string
}{
{
message: "message too long",
maxLength: 10,
expected: "message...",
},
{
message: "message that fits",
maxLength: 17,
expected: "message that fits",
},
}

for _, tt := range tests {
t.Run(tt.message, func(t *testing.T) {
g := NewWithT(t)

condition := TrueCondition(meta.ReadyCondition, "", tt.message)
condition.Message = trimConditionMessage(condition.Message, tt.maxLength)
g.Expect(len(condition.Message)).To(Equal(tt.maxLength))
g.Expect(condition.Message).To(Equal(tt.expected))
})
}
}

func setterWithConditions(conditions ...*metav1.Condition) Setter {
obj := &testdata.Fake{}
obj.SetConditions(conditionList(conditions...))
Expand Down

0 comments on commit 1169458

Please sign in to comment.