Skip to content

[receiver/sqlserver]update resources attributes to export identifying attributes #39449

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
merged 4 commits into from
Apr 17, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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/update-resources-attributes.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: breaking

# 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: We used to export those attributes on the log level, this is not alignihg with the semantic convention, also, the old way will cause waste of disk resources, as we can group them to a higher level to avoid repeat them all the places.

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

# (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]
54 changes: 33 additions & 21 deletions receiver/sqlserverreceiver/scraper.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,15 +116,17 @@ func (s *sqlServerScraperHelper) ScrapeMetrics(ctx context.Context) (pmetric.Met

func (s *sqlServerScraperHelper) ScrapeLogs(ctx context.Context) (plog.Logs, error) {
var err error
var resources pcommon.Resource
switch s.sqlQuery {
case getSQLServerQueryTextAndPlanQuery():
err = s.recordDatabaseQueryTextAndPlan(ctx, s.config.TopQueryCount)
resources, err = s.recordDatabaseQueryTextAndPlan(ctx, s.config.TopQueryCount)
case getSQLServerQuerySamplesQuery():
err = s.recordDatabaseSampleQuery(ctx)
resources, err = s.recordDatabaseSampleQuery(ctx)
default:
return plog.Logs{}, fmt.Errorf("Attempted to get logs from unsupported query: %s", s.sqlQuery)
}
return s.lb.Emit(), err

return s.lb.Emit(metadata.WithLogsResource(resources)), err
}

func (s *sqlServerScraperHelper) Shutdown(_ context.Context) error {
Expand Down Expand Up @@ -501,7 +503,7 @@ func (s *sqlServerScraperHelper) recordDatabaseStatusMetrics(ctx context.Context
return errors.Join(errs...)
}

func (s *sqlServerScraperHelper) recordDatabaseQueryTextAndPlan(ctx context.Context, topQueryCount uint) error {
func (s *sqlServerScraperHelper) recordDatabaseQueryTextAndPlan(ctx context.Context, topQueryCount uint) (pcommon.Resource, error) {
// Constants are the column names of the database status
const (
dbPrefix = "sqlserver."
Expand All @@ -521,6 +523,8 @@ func (s *sqlServerScraperHelper) recordDatabaseQueryTextAndPlan(ctx context.Cont
totalWorkerTime = "total_worker_time"
)

resources := pcommon.NewResource()

rows, err := s.client.QueryRows(
ctx,
sql.Named("lookbackTime", -s.config.LookbackTime),
Expand All @@ -529,7 +533,7 @@ func (s *sqlServerScraperHelper) recordDatabaseQueryTextAndPlan(ctx context.Cont
)
if err != nil {
if !errors.Is(err, sqlquery.ErrNullValueWarning) {
return fmt.Errorf("sqlServerScraperHelper failed getting rows: %w", err)
return resources, fmt.Errorf("sqlServerScraperHelper failed getting rows: %w", err)
}
s.logger.Warn("problems encountered getting log rows", zap.Error(err))
}
Expand Down Expand Up @@ -561,6 +565,7 @@ func (s *sqlServerScraperHelper) recordDatabaseQueryTextAndPlan(ctx context.Cont
// sort the totalElapsedTimeDiffs in descending order as well
sort.Slice(totalElapsedTimeDiffsMicrosecond, func(i, j int) bool { return totalElapsedTimeDiffsMicrosecond[i] > totalElapsedTimeDiffsMicrosecond[j] })

resourcesAdded := false
timestamp := pcommon.NewTimestampFromTime(time.Now())
for i, row := range rows {
// skipping the rest of the rows as totalElapsedTimeDiffs is sorted in descending order
Expand All @@ -577,12 +582,6 @@ func (s *sqlServerScraperHelper) recordDatabaseQueryTextAndPlan(ctx context.Cont
record.SetEventName("top query")

attributes := []internalAttribute{
{
key: computerNameKey,
columnName: computerNameKey,
valueRetriever: vanillaRetriever,
valueSetter: setString,
},
{
key: "db.query.text",
columnName: queryText,
Expand Down Expand Up @@ -655,12 +654,6 @@ func (s *sqlServerScraperHelper) recordDatabaseQueryTextAndPlan(ctx context.Cont
valueRetriever: defaultValueRetriever("microsoft.sql_server"),
valueSetter: setString,
},
{
key: instanceNameKey,
columnName: instanceNameKey,
valueRetriever: vanillaRetriever,
valueSetter: setString,
},
{
key: serverAddressKey,
valueRetriever: defaultValueRetriever(s.config.Server),
Expand Down Expand Up @@ -712,9 +705,17 @@ func (s *sqlServerScraperHelper) recordDatabaseQueryTextAndPlan(ctx context.Cont
attr.valueSetter(record.Attributes(), attr.key, value)
}
}
if !resourcesAdded {
resourceAttributes := resources.Attributes()
resourceAttributes.PutStr("host.name", s.config.Server)
resourceAttributes.PutStr("sqlserver.computer.name", row[computerNameKey])
resourceAttributes.PutStr("sqlserver.instance.name", row[instanceNameKey])

resourcesAdded = true
}
s.lb.AppendLogRecord(record)
}
return errors.Join(errs...)
return resources, errors.Join(errs...)
}

// cacheAndDiff store row(in int) with query hash and query plan hash variables
Expand Down Expand Up @@ -864,7 +865,7 @@ func setDouble(attributes pcommon.Map, key string, value any) {
attributes.PutDouble(key, value.(float64))
}

func (s *sqlServerScraperHelper) recordDatabaseSampleQuery(ctx context.Context) error {
func (s *sqlServerScraperHelper) recordDatabaseSampleQuery(ctx context.Context) (pcommon.Resource, error) {
const blockingSessionID = "blocking_session_id"
const clientAddress = "client_address"
const clientPort = "client_port"
Expand Down Expand Up @@ -902,16 +903,18 @@ func (s *sqlServerScraperHelper) recordDatabaseSampleQuery(ctx context.Context)
ctx,
sql.Named("top", s.config.TopQueryCount),
)
resources := pcommon.NewResource()
if err != nil {
if !errors.Is(err, sqlquery.ErrNullValueWarning) {
return fmt.Errorf("sqlServerScraperHelper failed getting log rows: %w", err)
return resources, fmt.Errorf("sqlServerScraperHelper failed getting log rows: %w", err)
}
// in case the sql returned rows contains null value, we just log a warning and continue
s.logger.Warn("problems encountered getting log rows", zap.Error(err))
}

var errs []error

resourcesAdded := false
for _, row := range rows {
queryHashVal := hex.EncodeToString([]byte(row[queryHash]))
queryPlanHashVal := hex.EncodeToString([]byte(row[queryPlanHash]))
Expand Down Expand Up @@ -1148,6 +1151,15 @@ func (s *sqlServerScraperHelper) recordDatabaseSampleQuery(ctx context.Context)

record.Body().SetStr("sample")
s.lb.AppendLogRecord(record)

if !resourcesAdded {
resourceAttributes := resources.Attributes()
resourceAttributes.PutStr("host.name", s.config.Server)
resourceAttributes.PutStr("sqlserver.computer.name", row[computerNameKey])
resourceAttributes.PutStr("sqlserver.instance.name", row[instanceNameKey])

resourcesAdded = true
}
}
return errors.Join(errs...)
return resources, errors.Join(errs...)
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
SELECT TOP(@top)
REPLACE(@@SERVERNAME,'\',':') AS [sql_instance],
HOST_NAME() AS [computer_name],
DB_NAME(r.database_id) AS db_name,
ISNULL(c.client_net_address, '') as client_address,
ISNULL(c.client_tcp_port, '') AS client_port,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
resourceLogs:
- resource:
attributes: []
attributes:
- key: sqlserver.computer.name
value:
stringValue: DESKTOP-GHAEGRD
- key: sqlserver.instance.name
value:
stringValue: sqlserver
- key: host.name
value:
stringValue: "0.0.0.0"
scopeLogs:
- logRecords:
- attributes:
- key: db.system.name
value:
stringValue: microsoft.sql_server
- key: computer_name
value:
stringValue: DESKTOP-GHAEGRD
- key: sql_instance
value:
stringValue: sqlserver

- key: server.address
value:
stringValue: 0.0.0.0
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
resourceLogs:
- resource:
attributes: []
attributes:
- key: sqlserver.computer.name
value:
stringValue: DESKTOP-GHAEGRD
- key: sqlserver.instance.name
value:
stringValue: sqlserver
- key: host.name
value:
stringValue: "0.0.0.0"
scopeLogs:
- logRecords:
- attributes:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
resourceLogs:
- resource:
attributes: []
attributes:
- key: sqlserver.computer.name
value:
stringValue: DESKTOP-GHAEGRD
- key: sqlserver.instance.name
value:
stringValue: sqlserver
- key: host.name
value:
stringValue: "0.0.0.0"
scopeLogs:
- logRecords:
- attributes:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
[
{
"computer_name": "DESKTOP-GHAEGRD",
"sql_instance": "sqlserver",
"db_name": "master",
"client_address": "172.19.0.1",
"client_port": "59286",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
[
{
"computer_name": "DESKTOP-GHAEGRD",
"sql_instance": "sqlserver",
"db_name": "master",
"client_address": "172.19.0.1",
"client_port": "a59286",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
SELECT TOP(@top)
REPLACE(@@SERVERNAME,'\',':') AS [sql_instance],
HOST_NAME() AS [computer_name],
DB_NAME(r.database_id) AS db_name,
ISNULL(c.client_net_address, '') as client_address,
ISNULL(c.client_tcp_port, '') AS client_port,
Expand Down
Loading