Skip to content

Commit 85a29ef

Browse files
cuichenliAkshayS198
authored andcommitted
[receiver/sqlserver]update resources attributes to export identifying attributes (open-telemetry#39449)
<!--Ex. Fixing a bug - Describe the bug and how this fixes the issue. Ex. Adding a feature - Explain what this achieves.--> #### Description 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. <!-- Issue number (e.g. open-telemetry#1234) or full URL to issue, if applicable. --> #### Link to tracking issue Fixes <!--Describe what testing was performed and which tests were added.--> #### Testing <!--Describe the documentation added.--> #### Documentation <!--Please delete paragraphs that you did not use before submitting.-->
1 parent 2f83bff commit 85a29ef

9 files changed

+99
-30
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Use this changelog template to create an entry for release notes.
2+
3+
# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
4+
change_type: breaking
5+
6+
# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
7+
component: sqlserverreceiver
8+
9+
# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
10+
note: "`host.name`, `sqlserver.computer.name`, and `sqlserver.instance.name` are now resource attributes instead of log attributes. We used to report `computer_name` and `instance_name` in the log attributes for top query collection and they are now deprecated. Now we report the three resources attributes in both top query collection and sample query collection."
11+
12+
# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
13+
issues: [39449]
14+
15+
# (Optional) One or more lines of additional information to render under the primary note.
16+
# These lines will be padded with 2 spaces and then inserted directly into the document.
17+
# Use pipe (|) for multiline entries.
18+
subtext: This change is only relevant for logs.
19+
20+
# If your change doesn't affect end users or the exported elements of any package,
21+
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
22+
# Optional: The change log or logs in which this entry should be included.
23+
# e.g. '[user]' or '[user, api]'
24+
# Include 'user' if the change is relevant to end users.
25+
# Include 'api' if there is a change to a library API.
26+
# Default: '[user]'
27+
change_logs: [user]

receiver/sqlserverreceiver/scraper.go

Lines changed: 33 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -116,15 +116,17 @@ func (s *sqlServerScraperHelper) ScrapeMetrics(ctx context.Context) (pmetric.Met
116116

117117
func (s *sqlServerScraperHelper) ScrapeLogs(ctx context.Context) (plog.Logs, error) {
118118
var err error
119+
var resources pcommon.Resource
119120
switch s.sqlQuery {
120121
case getSQLServerQueryTextAndPlanQuery():
121-
err = s.recordDatabaseQueryTextAndPlan(ctx, s.config.TopQueryCount)
122+
resources, err = s.recordDatabaseQueryTextAndPlan(ctx, s.config.TopQueryCount)
122123
case getSQLServerQuerySamplesQuery():
123-
err = s.recordDatabaseSampleQuery(ctx)
124+
resources, err = s.recordDatabaseSampleQuery(ctx)
124125
default:
125126
return plog.Logs{}, fmt.Errorf("Attempted to get logs from unsupported query: %s", s.sqlQuery)
126127
}
127-
return s.lb.Emit(), err
128+
129+
return s.lb.Emit(metadata.WithLogsResource(resources)), err
128130
}
129131

130132
func (s *sqlServerScraperHelper) Shutdown(_ context.Context) error {
@@ -501,7 +503,7 @@ func (s *sqlServerScraperHelper) recordDatabaseStatusMetrics(ctx context.Context
501503
return errors.Join(errs...)
502504
}
503505

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

526+
resources := pcommon.NewResource()
527+
524528
rows, err := s.client.QueryRows(
525529
ctx,
526530
sql.Named("lookbackTime", -s.config.LookbackTime),
@@ -529,7 +533,7 @@ func (s *sqlServerScraperHelper) recordDatabaseQueryTextAndPlan(ctx context.Cont
529533
)
530534
if err != nil {
531535
if !errors.Is(err, sqlquery.ErrNullValueWarning) {
532-
return fmt.Errorf("sqlServerScraperHelper failed getting rows: %w", err)
536+
return resources, fmt.Errorf("sqlServerScraperHelper failed getting rows: %w", err)
533537
}
534538
s.logger.Warn("problems encountered getting log rows", zap.Error(err))
535539
}
@@ -561,6 +565,7 @@ func (s *sqlServerScraperHelper) recordDatabaseQueryTextAndPlan(ctx context.Cont
561565
// sort the totalElapsedTimeDiffs in descending order as well
562566
sort.Slice(totalElapsedTimeDiffsMicrosecond, func(i, j int) bool { return totalElapsedTimeDiffsMicrosecond[i] > totalElapsedTimeDiffsMicrosecond[j] })
563567

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

579584
attributes := []internalAttribute{
580-
{
581-
key: computerNameKey,
582-
columnName: computerNameKey,
583-
valueRetriever: vanillaRetriever,
584-
valueSetter: setString,
585-
},
586585
{
587586
key: "db.query.text",
588587
columnName: queryText,
@@ -655,12 +654,6 @@ func (s *sqlServerScraperHelper) recordDatabaseQueryTextAndPlan(ctx context.Cont
655654
valueRetriever: defaultValueRetriever("microsoft.sql_server"),
656655
valueSetter: setString,
657656
},
658-
{
659-
key: instanceNameKey,
660-
columnName: instanceNameKey,
661-
valueRetriever: vanillaRetriever,
662-
valueSetter: setString,
663-
},
664657
{
665658
key: serverAddressKey,
666659
valueRetriever: defaultValueRetriever(s.config.Server),
@@ -712,9 +705,17 @@ func (s *sqlServerScraperHelper) recordDatabaseQueryTextAndPlan(ctx context.Cont
712705
attr.valueSetter(record.Attributes(), attr.key, value)
713706
}
714707
}
708+
if !resourcesAdded {
709+
resourceAttributes := resources.Attributes()
710+
resourceAttributes.PutStr("host.name", s.config.Server)
711+
resourceAttributes.PutStr("sqlserver.computer.name", row[computerNameKey])
712+
resourceAttributes.PutStr("sqlserver.instance.name", row[instanceNameKey])
713+
714+
resourcesAdded = true
715+
}
715716
s.lb.AppendLogRecord(record)
716717
}
717-
return errors.Join(errs...)
718+
return resources, errors.Join(errs...)
718719
}
719720

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

867-
func (s *sqlServerScraperHelper) recordDatabaseSampleQuery(ctx context.Context) error {
868+
func (s *sqlServerScraperHelper) recordDatabaseSampleQuery(ctx context.Context) (pcommon.Resource, error) {
868869
const blockingSessionID = "blocking_session_id"
869870
const clientAddress = "client_address"
870871
const clientPort = "client_port"
@@ -902,16 +903,18 @@ func (s *sqlServerScraperHelper) recordDatabaseSampleQuery(ctx context.Context)
902903
ctx,
903904
sql.Named("top", s.config.TopQueryCount),
904905
)
906+
resources := pcommon.NewResource()
905907
if err != nil {
906908
if !errors.Is(err, sqlquery.ErrNullValueWarning) {
907-
return fmt.Errorf("sqlServerScraperHelper failed getting log rows: %w", err)
909+
return resources, fmt.Errorf("sqlServerScraperHelper failed getting log rows: %w", err)
908910
}
909911
// in case the sql returned rows contains null value, we just log a warning and continue
910912
s.logger.Warn("problems encountered getting log rows", zap.Error(err))
911913
}
912914

913915
var errs []error
914916

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

11491152
record.Body().SetStr("sample")
11501153
s.lb.AppendLogRecord(record)
1154+
1155+
if !resourcesAdded {
1156+
resourceAttributes := resources.Attributes()
1157+
resourceAttributes.PutStr("host.name", s.config.Server)
1158+
resourceAttributes.PutStr("sqlserver.computer.name", row[computerNameKey])
1159+
resourceAttributes.PutStr("sqlserver.instance.name", row[instanceNameKey])
1160+
1161+
resourcesAdded = true
1162+
}
11511163
}
1152-
return errors.Join(errs...)
1164+
return resources, errors.Join(errs...)
11531165
}

receiver/sqlserverreceiver/templates/sqlServerQuerySample.tmpl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
SELECT TOP(@top)
2+
REPLACE(@@SERVERNAME,'\',':') AS [sql_instance],
3+
HOST_NAME() AS [computer_name],
24
DB_NAME(r.database_id) AS db_name,
35
ISNULL(c.client_net_address, '') as client_address,
46
ISNULL(c.client_tcp_port, '') AS client_port,

receiver/sqlserverreceiver/testdata/expectedQueryTextAndPlanQuery.yaml

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,22 @@
11
resourceLogs:
22
- resource:
3-
attributes: []
3+
attributes:
4+
- key: sqlserver.computer.name
5+
value:
6+
stringValue: DESKTOP-GHAEGRD
7+
- key: sqlserver.instance.name
8+
value:
9+
stringValue: sqlserver
10+
- key: host.name
11+
value:
12+
stringValue: "0.0.0.0"
413
scopeLogs:
514
- logRecords:
615
- attributes:
716
- key: db.system.name
817
value:
918
stringValue: microsoft.sql_server
10-
- key: computer_name
11-
value:
12-
stringValue: DESKTOP-GHAEGRD
13-
- key: sql_instance
14-
value:
15-
stringValue: sqlserver
19+
1620
- key: server.address
1721
value:
1822
stringValue: 0.0.0.0

receiver/sqlserverreceiver/testdata/expectedRecordDatabaseSampleQuery.yaml

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
resourceLogs:
22
- resource:
3-
attributes: []
3+
attributes:
4+
- key: sqlserver.computer.name
5+
value:
6+
stringValue: DESKTOP-GHAEGRD
7+
- key: sqlserver.instance.name
8+
value:
9+
stringValue: sqlserver
10+
- key: host.name
11+
value:
12+
stringValue: "0.0.0.0"
413
scopeLogs:
514
- logRecords:
615
- attributes:

receiver/sqlserverreceiver/testdata/expectedRecordDatabaseSampleQueryWithInvalidData.yaml

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
resourceLogs:
22
- resource:
3-
attributes: []
3+
attributes:
4+
- key: sqlserver.computer.name
5+
value:
6+
stringValue: DESKTOP-GHAEGRD
7+
- key: sqlserver.instance.name
8+
value:
9+
stringValue: sqlserver
10+
- key: host.name
11+
value:
12+
stringValue: "0.0.0.0"
413
scopeLogs:
514
- logRecords:
615
- attributes:

receiver/sqlserverreceiver/testdata/recordDatabaseSampleQueryData.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
[
22
{
3+
"computer_name": "DESKTOP-GHAEGRD",
4+
"sql_instance": "sqlserver",
35
"db_name": "master",
46
"client_address": "172.19.0.1",
57
"client_port": "59286",

receiver/sqlserverreceiver/testdata/recordInvalidDatabaseSampleQueryData.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
[
22
{
3+
"computer_name": "DESKTOP-GHAEGRD",
4+
"sql_instance": "sqlserver",
35
"db_name": "master",
46
"client_address": "172.19.0.1",
57
"client_port": "a59286",

receiver/sqlserverreceiver/testdata/testQuerySampleQuery.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
SELECT TOP(@top)
2+
REPLACE(@@SERVERNAME,'\',':') AS [sql_instance],
3+
HOST_NAME() AS [computer_name],
24
DB_NAME(r.database_id) AS db_name,
35
ISNULL(c.client_net_address, '') as client_address,
46
ISNULL(c.client_tcp_port, '') AS client_port,

0 commit comments

Comments
 (0)