From e07415227a9e1fcfeca48d705a56779625912f46 Mon Sep 17 00:00:00 2001 From: Julien Pivotto Date: Sun, 26 Jul 2020 01:20:40 +0200 Subject: [PATCH] discovery: check for nil triton_sd_config (#7671) * discovery: check for nil triton_sd_config Note: this was discovered thanks to the added test. The test is pretty low-level but also effective. Signed-off-by: Julien Pivotto --- discovery/config/config.go | 5 +++ discovery/config/config_test.go | 58 +++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 discovery/config/config_test.go diff --git a/discovery/config/config.go b/discovery/config/config.go index b21777c17..1ae0f952f 100644 --- a/discovery/config/config.go +++ b/discovery/config/config.go @@ -138,5 +138,10 @@ func (c *ServiceDiscoveryConfig) Validate() error { return errors.New("empty or null section in static_configs") } } + for _, cfg := range c.TritonSDConfigs { + if cfg == nil { + return errors.New("empty or null section in triton_sd_configs") + } + } return nil } diff --git a/discovery/config/config_test.go b/discovery/config/config_test.go new file mode 100644 index 000000000..a5723a240 --- /dev/null +++ b/discovery/config/config_test.go @@ -0,0 +1,58 @@ +// Copyright 2020 The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package config + +import ( + "fmt" + "reflect" + "strings" + "testing" + + "github.com/prometheus/prometheus/util/testutil" + "gopkg.in/yaml.v2" +) + +func TestForNilSDConfig(t *testing.T) { + // Get all the yaml fields names of the ServiceDiscoveryConfig struct. + s := reflect.ValueOf(ServiceDiscoveryConfig{}) + configType := s.Type() + n := s.NumField() + fieldsSlice := make([]string, n) + for i := 0; i < n; i++ { + field := configType.Field(i) + tag := field.Tag.Get("yaml") + tag = strings.Split(tag, ",")[0] + fieldsSlice = append(fieldsSlice, tag) + } + + // Unmarshall all possible yaml keys and validate errors check upon nil + // SD config. + for _, f := range fieldsSlice { + if f == "" { + continue + } + t.Run(f, func(t *testing.T) { + c := &ServiceDiscoveryConfig{} + err := yaml.Unmarshal([]byte(fmt.Sprintf(` +--- +%s: +- +`, f)), c) + testutil.Ok(t, err) + err = c.Validate() + testutil.NotOk(t, err) + testutil.Equals(t, fmt.Sprintf("empty or null section in %s", f), err.Error()) + }) + } +}