Skip to content

Add datasource, aka "connection string", option to sqlserverreceiver #39235

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

Merged
Show file tree
Hide file tree
Changes from all 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
27 changes: 27 additions & 0 deletions .chloggen/receiver-sqlserverreceiver-datasource.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: sqlserverreceiver

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Allow full control of the "connection string" via the `datasource` configuration option

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [39235]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:

# If your change doesn't affect end users or the exported elements of any package,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: [user]
3 changes: 3 additions & 0 deletions receiver/sqlserverreceiver/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ Direct connection options (optional, but all must be specified to enable):
- `server`: IP Address or hostname of SQL Server instance to connect to.
- `port`: Port of the SQL Server instance to connect to.

For finer control over the direct connection use the `datasource`, a.k.a. the "connection string", instead.
Note: it can't be used in conjunction with the `username`, `password`, `server` and `port` options.

Windows-specific options:
- `computer_name` (optional): The computer name identifies the SQL Server name or IP address of the computer being monitored.
If specified, `instance_name` is also required to be defined. This option is ignored in non-Windows environments.
Expand Down
34 changes: 27 additions & 7 deletions receiver/sqlserverreceiver/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,16 @@ type Config struct {
InstanceName string `mapstructure:"instance_name"`
ComputerName string `mapstructure:"computer_name"`

// The following options currently do nothing. Functionality will be added in a future PR.
DataSource string `mapstructure:"datasource"`

Password configopaque.String `mapstructure:"password"`
Port uint `mapstructure:"port"`
Server string `mapstructure:"server"`
Username string `mapstructure:"username"`

// Flag to check if the connection is direct or not. It should only be
// used after a successful call to the `Validate` method.
isDirectDBConnectionEnabled bool
}

func (cfg *Config) Validate() error {
Expand All @@ -66,12 +71,27 @@ func (cfg *Config) Validate() error {
return errors.New("`top_query_count` must be less than or equal to `max_query_sample_count`")
}

if !directDBConnectionEnabled(cfg) {
if cfg.Server != "" || cfg.Username != "" || string(cfg.Password) != "" {
return errors.New("Found one or more of the following configuration options set: [server, port, username, password]. " +
"All of these options must be configured to directly connect to a SQL Server instance.")
}
cfg.isDirectDBConnectionEnabled, err = directDBConnectionEnabled(cfg)

return err
}

func directDBConnectionEnabled(config *Config) (bool, error) {
noneOfServerUserPasswordPortSet := config.Server == "" && config.Username == "" && string(config.Password) == "" && config.Port == 0
if config.DataSource == "" && noneOfServerUserPasswordPortSet {
// If no connection information is provided, we can't connect directly and this is a valid config.
return false, nil
}

anyOfServerUserPasswordPortSet := config.Server != "" || config.Username != "" || string(config.Password) != "" || config.Port != 0
if config.DataSource != "" && anyOfServerUserPasswordPortSet {
return false, errors.New("wrong config: when specifying 'datasource' no other connection parameters ('server', 'username', 'password', or 'port') should be set")
}

if config.DataSource == "" && (config.Server == "" || config.Username == "" || string(config.Password) == "" || config.Port == 0) {
return false, errors.New("wrong config: when specifying either 'server', 'username', 'password', or 'port' all of them need to be specified")
}

return nil
// It is a valid direct connection configuration
return true, nil
}
20 changes: 19 additions & 1 deletion receiver/sqlserverreceiver/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,24 @@ func TestValidate(t *testing.T) {
},
expectedSuccess: false,
},
{
desc: "invalid config with datasource and any direct connect settings",
cfg: &Config{
ControllerConfig: scraperhelper.NewDefaultControllerConfig(),
DataSource: "a connection string",
Username: "sa",
Port: 1433,
},
expectedSuccess: false,
},
{
desc: "valid config only datasource and none direct connect settings",
cfg: &Config{
ControllerConfig: scraperhelper.NewDefaultControllerConfig(),
DataSource: "a connection string",
},
expectedSuccess: true,
},
{
desc: "valid config with all direct connection settings",
cfg: &Config{
Expand Down Expand Up @@ -160,7 +178,7 @@ func TestLoadConfig(t *testing.T) {
require.NoError(t, sub.Unmarshal(cfg))

assert.NoError(t, xconfmap.Validate(cfg))
if diff := cmp.Diff(expected, cfg, cmpopts.IgnoreUnexported(metadata.MetricConfig{}), cmpopts.IgnoreUnexported(metadata.ResourceAttributeConfig{})); diff != "" {
if diff := cmp.Diff(expected, cfg, cmpopts.IgnoreUnexported(Config{}), cmpopts.IgnoreUnexported(metadata.MetricConfig{}), cmpopts.IgnoreUnexported(metadata.ResourceAttributeConfig{})); diff != "" {
t.Errorf("Config mismatch (-expected +actual):\n%s", diff)
}
})
Expand Down
13 changes: 5 additions & 8 deletions receiver/sqlserverreceiver/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,20 +94,17 @@ func setupLogQueries(cfg *Config) []string {
return queries
}

func directDBConnectionEnabled(config *Config) bool {
return config.Server != "" &&
config.Username != "" &&
string(config.Password) != ""
}

// Assumes config has all information necessary to directly connect to the database
func getDBConnectionString(config *Config) string {
if config.DataSource != "" {
return config.DataSource
}
return fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d", config.Server, config.Username, string(config.Password), config.Port)
}

// SQL Server scraper creation is split out into a separate method for the sake of testing.
func setupSQLServerScrapers(params receiver.Settings, cfg *Config) []*sqlServerScraperHelper {
if !directDBConnectionEnabled(cfg) {
if !cfg.isDirectDBConnectionEnabled {
params.Logger.Info("No direct connection will be made to the SQL Server: Configuration doesn't include some options.")
return nil
}
Expand Down Expand Up @@ -147,7 +144,7 @@ func setupSQLServerScrapers(params receiver.Settings, cfg *Config) []*sqlServerS

// SQL Server scraper creation is split out into a separate method for the sake of testing.
func setupSQLServerLogsScrapers(params receiver.Settings, cfg *Config) []*sqlServerScraperHelper {
if !directDBConnectionEnabled(cfg) {
if !cfg.isDirectDBConnectionEnabled {
params.Logger.Info("No direct connection will be made to the SQL Server: Configuration doesn't include some options.")
return nil
}
Expand Down
4 changes: 2 additions & 2 deletions receiver/sqlserverreceiver/factory_others_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func TestFactoryOtherOS(t *testing.T) {
cfg.Metrics.SqlserverDatabaseLatency.Enabled = true
require.NoError(t, cfg.Validate())

require.True(t, directDBConnectionEnabled(cfg))
require.True(t, cfg.isDirectDBConnectionEnabled)
require.Equal(t, "server=0.0.0.0;user id=sa;password=password;port=1433", getDBConnectionString(cfg))

params := receivertest.NewNopSettings(metadata.Type)
Expand Down Expand Up @@ -78,7 +78,7 @@ func TestFactoryOtherOS(t *testing.T) {
cfg.Port = 1433
require.NoError(t, cfg.Validate())

require.True(t, directDBConnectionEnabled(cfg))
require.True(t, cfg.isDirectDBConnectionEnabled)
require.Equal(t, "server=0.0.0.0;user id=sa;password=password;port=1433", getDBConnectionString(cfg))

params := receivertest.NewNopSettings(metadata.Type)
Expand Down
4 changes: 2 additions & 2 deletions receiver/sqlserverreceiver/factory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ func TestFactory(t *testing.T) {
require.NoError(t, cfg.Validate())
cfg.Metrics.SqlserverDatabaseLatency.Enabled = true

require.True(t, directDBConnectionEnabled(cfg))
require.True(t, cfg.isDirectDBConnectionEnabled)
require.Equal(t, "server=0.0.0.0;user id=sa;password=password;port=1433", getDBConnectionString(cfg))

params := receivertest.NewNopSettings(metadata.Type)
Expand Down Expand Up @@ -190,7 +190,7 @@ func TestFactory(t *testing.T) {
require.NoError(t, cfg.Validate())
cfg.Metrics.SqlserverDatabaseLatency.Enabled = true

require.True(t, directDBConnectionEnabled(cfg))
require.True(t, cfg.isDirectDBConnectionEnabled)
require.Equal(t, "server=0.0.0.0;user id=sa;password=password;port=1433", getDBConnectionString(cfg))

params := receivertest.NewNopSettings(metadata.Type)
Expand Down
Loading