-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
scraper.go
302 lines (265 loc) · 10.5 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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
// 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.opentelemetry.io/collector/scraper"
"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 (
computerNameKey = "computer_name"
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 _ scraper.Metrics = (*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) ScrapeMetrics(ctx context.Context) (pmetric.Metrics, error) {
var err error
switch s.sqlQuery {
case getSQLServerDatabaseIOQuery(s.instanceName):
err = s.recordDatabaseIOMetrics(ctx)
case getSQLServerPerformanceCounterQuery(s.instanceName):
err = s.recordDatabasePerfCounterMetrics(ctx)
case getSQLServerPropertiesQuery(s.instanceName):
err = s.recordDatabaseStatusMetrics(ctx)
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(), 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) error {
const databaseNameKey = "database_name"
const physicalFilenameKey = "physical_filename"
const logicalFilenameKey = "logical_filename"
const fileTypeKey = "file_type"
const readLatencyMsKey = "read_latency_ms"
const writeLatencyMsKey = "write_latency_ms"
const readCountKey = "reads"
const writeCountKey = "writes"
const readBytesKey = "read_bytes"
const writeBytesKey = "write_bytes"
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 {
rb := s.mb.NewResourceBuilder()
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.RecordSqlserverDatabaseLatencyDataPoint(now, val/1e3, row[physicalFilenameKey], row[logicalFilenameKey], row[fileTypeKey], metadata.AttributeDirectionRead)
}
val, err = strconv.ParseFloat(row[writeLatencyMsKey], 64)
if err != nil {
err = fmt.Errorf("row %d: %w", i, err)
errs = append(errs, err)
} else {
s.mb.RecordSqlserverDatabaseLatencyDataPoint(now, val/1e3, row[physicalFilenameKey], row[logicalFilenameKey], row[fileTypeKey], metadata.AttributeDirectionWrite)
}
errs = append(errs, s.mb.RecordSqlserverDatabaseOperationsDataPoint(now, row[readCountKey], row[physicalFilenameKey], row[logicalFilenameKey], row[fileTypeKey], metadata.AttributeDirectionRead))
errs = append(errs, s.mb.RecordSqlserverDatabaseOperationsDataPoint(now, row[writeCountKey], row[physicalFilenameKey], row[logicalFilenameKey], row[fileTypeKey], metadata.AttributeDirectionWrite))
errs = append(errs, s.mb.RecordSqlserverDatabaseIoDataPoint(now, row[readBytesKey], row[physicalFilenameKey], row[logicalFilenameKey], row[fileTypeKey], metadata.AttributeDirectionRead))
errs = append(errs, s.mb.RecordSqlserverDatabaseIoDataPoint(now, row[writeBytesKey], row[physicalFilenameKey], row[logicalFilenameKey], row[fileTypeKey], metadata.AttributeDirectionWrite))
s.mb.EmitForResource(metadata.WithResource(rb.Emit()))
}
if len(rows) == 0 {
s.logger.Info("SQLServerScraperHelper: No rows found by query")
}
return errors.Join(errs...)
}
func (s *sqlServerScraperHelper) recordDatabasePerfCounterMetrics(ctx context.Context) error {
const counterKey = "counter"
const valueKey = "value"
// Constants are the columns for metrics from query
const batchRequestRate = "Batch Requests/sec"
const bufferCacheHitRatio = "Buffer cache hit ratio"
const diskReadIOThrottled = "Disk Read IO Throttled/sec"
const diskWriteIOThrottled = "Disk Write IO Throttled/sec"
const lockWaits = "Lock Waits/sec"
const processesBlocked = "Processes blocked"
const sqlCompilationRate = "SQL Compilations/sec"
const sqlReCompilationsRate = "SQL Re-Compilations/sec"
const userConnCount = "User Connections"
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 {
rb := s.mb.NewResourceBuilder()
rb.SetSqlserverComputerName(row[computerNameKey])
rb.SetSqlserverInstanceName(row[instanceNameKey])
switch row[counterKey] {
case batchRequestRate:
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.RecordSqlserverBatchRequestRateDataPoint(now, val)
}
case bufferCacheHitRatio:
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.RecordSqlserverPageBufferCacheHitRatioDataPoint(now, val)
}
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]))
case sqlCompilationRate:
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.RecordSqlserverBatchSQLCompilationRateDataPoint(now, val)
}
case sqlReCompilationsRate:
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.RecordSqlserverBatchSQLRecompilationRateDataPoint(now, val)
}
case userConnCount:
val, err := strconv.ParseInt(row[valueKey], 10, 64)
if err != nil {
err = fmt.Errorf("row %d: %w", i, err)
errs = append(errs, err)
} else {
s.mb.RecordSqlserverUserConnectionCountDataPoint(now, val)
}
}
s.mb.EmitForResource(metadata.WithResource(rb.Emit()))
}
return errors.Join(errs...)
}
func (s *sqlServerScraperHelper) recordDatabaseStatusMetrics(ctx context.Context) 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 _, row := range rows {
rb := s.mb.NewResourceBuilder()
rb.SetSqlserverComputerName(row[computerNameKey])
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))
s.mb.EmitForResource(metadata.WithResource(rb.Emit()))
}
return errors.Join(errs...)
}