Skip to content

Add error and event for mismatching input property #6763

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ To learn more about active deprecations, we recommend checking [GitHub Discussio

### New

- TODO ([#XXX](https://github.com/kedacore/keda/issues/XXX))
- **General**: Add error and event for mismatching input property ([#6721](https://github.com/kedacore/keda/issues/6721))

#### Experimental

Expand Down
65 changes: 49 additions & 16 deletions pkg/scalers/scalersconfig/typed_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ import (
"strings"
"time"

"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
logf "sigs.k8s.io/controller-runtime/pkg/log"

"github.com/kedacore/keda/v2/pkg/eventreason"
)
Expand Down Expand Up @@ -158,21 +160,30 @@ func (sc *ScalerConfig) TypedConfig(typedConfig any) (err error) {
err = fmt.Errorf("failed to parse typed config %T resulted in panic\n%v", r, string(debug.Stack()))
}
}()
err = sc.parseTypedConfig(typedConfig, false)

logger := logf.Log.WithName("typed_config").WithValues("type", sc.ScalableObjectType, "namespace", sc.ScalableObjectNamespace, "name", sc.ScalableObjectName)

parsedParamNames, err := sc.parseTypedConfig(typedConfig, false)

if err == nil {
sc.checkUnexpectedParameterExist(parsedParamNames, logger)
}

return
}

// parseTypedConfig is a function that is used to unmarshal the TriggerMetadata, ResolvedEnv and AuthParams
// this can be called recursively to parse nested structures
func (sc *ScalerConfig) parseTypedConfig(typedConfig any, parentOptional bool) error {
func (sc *ScalerConfig) parseTypedConfig(typedConfig any, parentOptional bool) ([]string, error) {
t := reflect.TypeOf(typedConfig)
if t.Kind() != reflect.Pointer {
return fmt.Errorf("typedConfig must be a pointer")
return nil, fmt.Errorf("typedConfig must be a pointer")
}
t = t.Elem()
v := reflect.ValueOf(typedConfig).Elem()

errs := []error{}
parsedParamNames := []string{}
for i := 0; i < t.NumField(); i++ {
fieldType := t.Field(i)
fieldValue := v.Field(i)
Expand All @@ -186,23 +197,26 @@ func (sc *ScalerConfig) parseTypedConfig(typedConfig any, parentOptional bool) e
continue
}
tagParams.Optional = tagParams.Optional || parentOptional
if err := sc.setValue(fieldValue, tagParams); err != nil {
parsed, err := sc.setValue(fieldValue, tagParams)
if err != nil {
errs = append(errs, err)
} else {
parsedParamNames = append(parsedParamNames, parsed...)
}
}
if validator, ok := typedConfig.(CustomValidator); ok {
if err := validator.Validate(); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
return parsedParamNames, errors.Join(errs...)
}

// setValue is a function that sets the value of the field based on the provided params
func (sc *ScalerConfig) setValue(field reflect.Value, params Params) error {
// setValue is a function that sets the value of the field based on the provided params, will return error and param names that set value
func (sc *ScalerConfig) setValue(field reflect.Value, params Params) ([]string, error) {
valFromConfig, exists := sc.configParamValue(params)
if exists && params.IsDeprecated() {
return fmt.Errorf("parameter %q is deprecated%v", params.Name(), params.DeprecatedMessage())
return nil, fmt.Errorf("parameter %q is deprecated%v", params.Name(), params.DeprecatedMessage())
}
if exists && params.DeprecatedAnnounce != "" {
if sc.Recorder != nil {
Expand All @@ -216,14 +230,14 @@ func (sc *ScalerConfig) setValue(field reflect.Value, params Params) error {
valFromConfig = params.Default
}
if !exists && (params.Optional || params.IsDeprecated()) {
return nil
return nil, nil
}
if !exists && !(params.Optional || params.IsDeprecated()) {
if len(params.Order) == 0 {
apo := slices.Sorted(maps.Keys(allowedParsingOrderMap))
return fmt.Errorf("missing required parameter %q, no 'order' tag, provide any from %v", params.Name(), apo)
return nil, fmt.Errorf("missing required parameter %q, no 'order' tag, provide any from %v", params.Name(), apo)
}
return fmt.Errorf("missing required parameter %q in %v", params.Name(), params.Order)
return nil, fmt.Errorf("missing required parameter %q in %v", params.Name(), params.Order)
}
if params.Enum != nil {
enumMap := make(map[string]bool)
Expand All @@ -239,7 +253,7 @@ func (sc *ScalerConfig) setValue(field reflect.Value, params Params) error {
}
}
if len(missingMap) > 0 {
return fmt.Errorf("parameter %q value %q must be one of %v", params.Name(), valFromConfig, params.Enum)
return nil, fmt.Errorf("parameter %q value %q must be one of %v", params.Name(), valFromConfig, params.Enum)
}
}
if params.ExclusiveSet != nil {
Expand All @@ -256,7 +270,7 @@ func (sc *ScalerConfig) setValue(field reflect.Value, params Params) error {
}
}
if exclusiveCount > 1 {
return fmt.Errorf("parameter %q value %q must contain only one of %v", params.Name(), valFromConfig, params.ExclusiveSet)
return nil, fmt.Errorf("parameter %q value %q must contain only one of %v", params.Name(), valFromConfig, params.ExclusiveSet)
}
}
if params.IsNested() {
Expand All @@ -265,14 +279,14 @@ func (sc *ScalerConfig) setValue(field reflect.Value, params Params) error {
field = field.Elem()
}
if field.Kind() != reflect.Struct {
return fmt.Errorf("nested parameter %q must be a struct, has kind %q", params.FieldName, field.Kind())
return nil, fmt.Errorf("nested parameter %q must be a struct, has kind %q", params.FieldName, field.Kind())
}
return sc.parseTypedConfig(field.Addr().Interface(), params.Optional)
}
if err := setConfigValueHelper(params, valFromConfig, field); err != nil {
return fmt.Errorf("unable to set param %q value %q: %w", params.Name(), valFromConfig, err)
return nil, fmt.Errorf("unable to set param %q value %q: %w", params.Name(), valFromConfig, err)
}
return nil
return []string{params.Name()}, nil
}

// setConfigValueURLParams is a function that sets the value of the url.Values field
Expand Down Expand Up @@ -478,6 +492,25 @@ func (sc *ScalerConfig) configParamValue(params Params) (string, bool) {
return "", params.IsNested()
}

// checkUnexpectedParameterExist is a function that checks if there are any unexpected parameters in the TriggerMetadata
func (sc *ScalerConfig) checkUnexpectedParameterExist(parsedParamNames []string, logger logr.Logger) {
for k := range sc.TriggerMetadata {
suffix := "FromEnv"
if !strings.HasSuffix(k, "FromEnv") {
suffix = ""
}
key := strings.TrimSuffix(k, suffix)
if !slices.Contains(parsedParamNames, key) {
if sc.Recorder != nil {
message := fmt.Sprintf("Unmatched input property %s in scaler %s", key+suffix, sc.ScalableObjectType)
// Just logging as it's optional property checking and should not block the scaling
logger.Error(nil, message)
sc.Recorder.Event(sc.ScaledObject, corev1.EventTypeNormal, eventreason.KEDAScalersInfo, message)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we use corev1.EventTypeWarning instead of corev1.EventTypeNormal here?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could see a good rationale for either type. My usual rule of thumb is

  • use Normal when something successfully happened and a user should know about it - e.g. volume is mounted, some connection was established...
  • use Warning when something unexpected happened and it has negative impact for the user - e.g. volume didn't get mounted, some connection got broken...

This case "an extra parameter user provided is ignored". KEDA is successful at ignoring it but it might have unexpected result for the user, so a bit of both. I'd probably also pick Warning event but I can be easily convinced for Normal.

}
}
}
}

// paramsFromTag is a function that returns the Params struct based on the field tag
func paramsFromTag(tag string, field reflect.StructField) (Params, error) {
params := Params{FieldName: field.Name}
Expand Down
41 changes: 41 additions & 0 deletions pkg/scalers/scalersconfig/typed_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -613,15 +613,56 @@ func TestDeprecatedAnnounce(t *testing.T) {
Expect(mockRecorder.Message).To(Equal("Scaler info: This parameter is deprecated. Use newParam instead"))
}

// TestUnexpectedOptional tests the unexpected optional input
func TestUnexpectedOptional(t *testing.T) {
RegisterTestingT(t)

// Create a mock recorder to capture the event
mockRecorder := &MockEventRecorder{Messages: make([]string, 0)}

sc := &ScalerConfig{
TriggerMetadata: map[string]string{
"stringVal": "value1",
"nestVal": "nestVal",
"notexistVal": "aaa",
"notValFromEnv": "bbb",
},
ResolvedEnv: map[string]string{
"bbb": "1.1",
},
Recorder: mockRecorder,
ScalableObjectType: "test",
}
type nestStruct struct {
Nest string `keda:"name=nestVal, order=triggerMetadata"`
}

type testStruct struct {
BA nestStruct `keda:""`
StringVal string `keda:"name=stringVal, order=triggerMetadata"`
}

ts := testStruct{}
err := sc.TypedConfig(&ts)
Expect(err).To(BeNil())

// Verify that the deprecation event was recorded
Expect(mockRecorder.EventCalled).To(BeTrue())
Expect(mockRecorder.Messages[0]).To(Equal("Unmatched input property notexistVal in scaler test"))
Expect(mockRecorder.Messages[1]).To(Equal("Unmatched input property notValFromEnv in scaler test"))
}

// MockEventRecorder is a mock implementation of record.EventRecorder
type MockEventRecorder struct {
EventCalled bool
Message string
Messages []string
}

func (m *MockEventRecorder) Event(object runtime.Object, eventtype, reason, message string) {
m.EventCalled = true
m.Message = message
m.Messages = append(m.Messages, message)
}

func (m *MockEventRecorder) Eventf(object runtime.Object, eventtype, reason, messageFmt string, args ...interface{}) {
Expand Down
Loading