diff --git a/beater/config/instrumentation.go b/beater/config/instrumentation.go index aa0f17686da..f0b4c679df1 100644 --- a/beater/config/instrumentation.go +++ b/beater/config/instrumentation.go @@ -21,6 +21,7 @@ import ( "time" "github.com/elastic/beats/libbeat/logp" + "github.com/elastic/go-ucfg" ) const ( @@ -33,12 +34,21 @@ const ( type InstrumentationConfig struct { Enabled *bool `config:"enabled"` Environment *string `config:"environment"` - Hosts urls `config:"hosts" validate:"nonzero"` + Hosts urls `config:"hosts"` //TODO(simi): add `validate:"nonzero"` again once https://github.com/elastic/go-ucfg/issues/147 is fixed Profiling ProfilingConfig `config:"profiling"` APIKey string `config:"api_key"` SecretToken string `config:"secret_token"` } +func (c *InstrumentationConfig) Validate() error { + for _, h := range c.Hosts { + if h == nil || h.Host == "" { + return ucfg.ErrZeroValue + } + } + return nil +} + // IsEnabled indicates whether self instrumentation is enabled func (c *InstrumentationConfig) IsEnabled() bool { // self instrumentation is disabled by default. diff --git a/beater/config/instrumentation_test.go b/beater/config/instrumentation_test.go new file mode 100644 index 00000000000..87b73ed7b9f --- /dev/null +++ b/beater/config/instrumentation_test.go @@ -0,0 +1,47 @@ +// Licensed to Elasticsearch B.V. under one or more contributor +// license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright +// ownership. Elasticsearch B.V. licenses this file to you 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 ( + "testing" + + "github.com/elastic/go-ucfg" + + "github.com/elastic/beats/libbeat/common" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNonzeroHosts(t *testing.T) { + t.Run("ZeroHost", func(t *testing.T) { + cfg, err := NewConfig("9.9.9", + common.MustNewConfigFrom(map[string]interface{}{ + "instrumentation.enabled": true, "instrumentation.hosts": []string{""}}), nil) + require.Error(t, err) + assert.Contains(t, err.Error(), ucfg.ErrZeroValue.Error()) + assert.Nil(t, cfg) + }) + + t.Run("Valid", func(t *testing.T) { + cfg, err := NewConfig("9.9.9", + common.MustNewConfigFrom(map[string]interface{}{"instrumentation.enabled": true}), nil) + require.NoError(t, err) + assert.True(t, *cfg.SelfInstrumentation.Enabled) + assert.Empty(t, cfg.SelfInstrumentation.Hosts) + }) +}