forked from open-telemetry/opentelemetry-collector-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscraper.go
236 lines (200 loc) · 7.58 KB
/
scraper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package sqlserverreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/sqlserverreceiver"
import (
"context"
"database/sql"
"errors"
"fmt"
"strconv"
"time"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
"go.opentelemetry.io/collector/receiver/scraperhelper"
"go.uber.org/zap"
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/sqlquery"
"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/sqlserverreceiver/internal/metadata"
)
const instanceNameKey = "sql_instance"
type sqlServerScraperHelper struct {
id component.ID
sqlQuery string
instanceName string
scrapeCfg scraperhelper.ControllerConfig
clientProviderFunc sqlquery.ClientProviderFunc
dbProviderFunc sqlquery.DbProviderFunc
logger *zap.Logger
telemetry sqlquery.TelemetryConfig
client sqlquery.DbClient
db *sql.DB
mb *metadata.MetricsBuilder
}
var _ scraperhelper.Scraper = (*sqlServerScraperHelper)(nil)
func newSQLServerScraper(id component.ID,
query string,
instanceName string,
scrapeCfg scraperhelper.ControllerConfig,
logger *zap.Logger,
telemetry sqlquery.TelemetryConfig,
dbProviderFunc sqlquery.DbProviderFunc,
clientProviderFunc sqlquery.ClientProviderFunc,
mb *metadata.MetricsBuilder) *sqlServerScraperHelper {
return &sqlServerScraperHelper{
id: id,
sqlQuery: query,
instanceName: instanceName,
scrapeCfg: scrapeCfg,
logger: logger,
telemetry: telemetry,
dbProviderFunc: dbProviderFunc,
clientProviderFunc: clientProviderFunc,
mb: mb,
}
}
func (s *sqlServerScraperHelper) ID() component.ID {
return s.id
}
func (s *sqlServerScraperHelper) Start(context.Context, component.Host) error {
var err error
s.db, err = s.dbProviderFunc()
if err != nil {
return fmt.Errorf("failed to open Db connection: %w", err)
}
s.client = s.clientProviderFunc(sqlquery.DbWrapper{Db: s.db}, s.sqlQuery, s.logger, s.telemetry)
return nil
}
func (s *sqlServerScraperHelper) Scrape(ctx context.Context) (pmetric.Metrics, error) {
var err error
rb := s.mb.NewResourceBuilder()
switch s.sqlQuery {
case getSQLServerDatabaseIOQuery(s.instanceName):
err = s.recordDatabaseIOMetrics(ctx, rb)
case getSQLServerPerformanceCounterQuery(s.instanceName):
err = s.recordDatabasePerfCounterMetrics(ctx, rb)
case getSQLServerPropertiesQuery(s.instanceName):
err = s.recordDatabaseStatusMetrics(ctx, rb)
default:
return pmetric.Metrics{}, fmt.Errorf("Attempted to get metrics from unsupported query: %s", s.sqlQuery)
}
if err != nil {
return pmetric.Metrics{}, err
}
return s.mb.Emit(metadata.WithResource(rb.Emit())), nil
}
func (s *sqlServerScraperHelper) Shutdown(_ context.Context) error {
if s.db != nil {
return s.db.Close()
}
return nil
}
func (s *sqlServerScraperHelper) recordDatabaseIOMetrics(ctx context.Context, rb *metadata.ResourceBuilder) error {
// TODO: Move constants out to the package level when other queries are added.
const computerNameKey = "computer_name"
const databaseNameKey = "database_name"
const physicalFilenameKey = "physical_filename"
const logicalFilenameKey = "logical_filename"
const fileTypeKey = "file_type"
const readLatencyMsKey = "read_latency_ms"
rows, err := s.client.QueryRows(ctx)
if err != nil {
if errors.Is(err, sqlquery.ErrNullValueWarning) {
s.logger.Warn("problems encountered getting metric rows", zap.Error(err))
} else {
return fmt.Errorf("sqlServerScraperHelper: %w", err)
}
}
var errs []error
now := pcommon.NewTimestampFromTime(time.Now())
var val float64
for i, row := range rows {
if i == 0 {
rb.SetSqlserverComputerName(row[computerNameKey])
rb.SetSqlserverDatabaseName(row[databaseNameKey])
rb.SetSqlserverInstanceName(row[instanceNameKey])
}
val, err = strconv.ParseFloat(row[readLatencyMsKey], 64)
if err != nil {
err = fmt.Errorf("row %d: %w", i, err)
errs = append(errs, err)
} else {
s.mb.RecordSqlserverDatabaseIoReadLatencyDataPoint(now, val/1e3, row[physicalFilenameKey], row[logicalFilenameKey], row[fileTypeKey])
}
}
if len(rows) == 0 {
s.logger.Info("SQLServerScraperHelper: No rows found by query")
}
return errors.Join(errs...)
}
func (s *sqlServerScraperHelper) recordDatabasePerfCounterMetrics(ctx context.Context, rb *metadata.ResourceBuilder) error {
const counterKey = "counter"
const valueKey = "value"
// Constants are the columns for metrics from query
const diskReadIOThrottled = "Disk Read IO Throttled/sec"
const diskWriteIOThrottled = "Disk Write IO Throttled/sec"
const lockWaits = "Lock Waits/sec"
const processesBlocked = "Processes blocked"
rows, err := s.client.QueryRows(ctx)
if err != nil {
if errors.Is(err, sqlquery.ErrNullValueWarning) {
s.logger.Warn("problems encountered getting metric rows", zap.Error(err))
} else {
return fmt.Errorf("sqlServerScraperHelper: %w", err)
}
}
var errs []error
now := pcommon.NewTimestampFromTime(time.Now())
for i, row := range rows {
if i == 0 {
rb.SetSqlserverInstanceName(row[instanceNameKey])
}
switch row[counterKey] {
case diskReadIOThrottled:
errs = append(errs, s.mb.RecordSqlserverResourcePoolDiskThrottledReadRateDataPoint(now, row[valueKey]))
case diskWriteIOThrottled:
errs = append(errs, s.mb.RecordSqlserverResourcePoolDiskThrottledWriteRateDataPoint(now, row[valueKey]))
case lockWaits:
val, err := strconv.ParseFloat(row[valueKey], 64)
if err != nil {
err = fmt.Errorf("row %d: %w", i, err)
errs = append(errs, err)
} else {
s.mb.RecordSqlserverLockWaitRateDataPoint(now, val)
}
case processesBlocked:
errs = append(errs, s.mb.RecordSqlserverProcessesBlockedDataPoint(now, row[valueKey]))
}
}
return errors.Join(errs...)
}
func (s *sqlServerScraperHelper) recordDatabaseStatusMetrics(ctx context.Context, rb *metadata.ResourceBuilder) error {
// Constants are the column names of the database status
const dbOnline = "db_online"
const dbRestoring = "db_restoring"
const dbRecovering = "db_recovering"
const dbPendingRecovery = "db_recoveryPending"
const dbSuspect = "db_suspect"
const dbOffline = "db_offline"
rows, err := s.client.QueryRows(ctx)
if err != nil {
if errors.Is(err, sqlquery.ErrNullValueWarning) {
s.logger.Warn("problems encountered getting metric rows", zap.Error(err))
} else {
return fmt.Errorf("sqlServerScraperHelper failed getting metric rows: %w", err)
}
}
var errs []error
now := pcommon.NewTimestampFromTime(time.Now())
for i, row := range rows {
if i == 0 {
rb.SetSqlserverInstanceName(row[instanceNameKey])
}
errs = append(errs, s.mb.RecordSqlserverDatabaseCountDataPoint(now, row[dbOnline], metadata.AttributeDatabaseStatusOnline))
errs = append(errs, s.mb.RecordSqlserverDatabaseCountDataPoint(now, row[dbRestoring], metadata.AttributeDatabaseStatusRestoring))
errs = append(errs, s.mb.RecordSqlserverDatabaseCountDataPoint(now, row[dbRecovering], metadata.AttributeDatabaseStatusRecovering))
errs = append(errs, s.mb.RecordSqlserverDatabaseCountDataPoint(now, row[dbPendingRecovery], metadata.AttributeDatabaseStatusPendingRecovery))
errs = append(errs, s.mb.RecordSqlserverDatabaseCountDataPoint(now, row[dbSuspect], metadata.AttributeDatabaseStatusSuspect))
errs = append(errs, s.mb.RecordSqlserverDatabaseCountDataPoint(now, row[dbOffline], metadata.AttributeDatabaseStatusOffline))
}
return errors.Join(errs...)
}