Skip to content

Commit

Permalink
[receiver/postgresql] Added postgresql.deadlocks metric. (open-teleme…
Browse files Browse the repository at this point in the history
…try#25792)

**Description:** Added new metric -- `postgresql.deadlocks` -- number of
deadlocks detected in a database.

**Link to tracking Issue:**
open-telemetry#25688
  • Loading branch information
bjandras committed Aug 15, 2023
1 parent 6dca288 commit cbe537d
Show file tree
Hide file tree
Showing 20 changed files with 322 additions and 6 deletions.
27 changes: 27 additions & 0 deletions .chloggen/postgresql_deadlocks.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: postgresqlreceiver

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Added `postgresql.deadlocks` metric.

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

# (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]
8 changes: 5 additions & 3 deletions receiver/postgresqlreceiver/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,11 @@ func (c *postgreSQLClient) Close() error {
type databaseStats struct {
transactionCommitted int64
transactionRollback int64
deadlocks int64
}

func (c *postgreSQLClient) getDatabaseStats(ctx context.Context, databases []string) (map[databaseName]databaseStats, error) {
query := filterQueryByDatabases("SELECT datname, xact_commit, xact_rollback FROM pg_stat_database", databases, false)
query := filterQueryByDatabases("SELECT datname, xact_commit, xact_rollback, deadlocks FROM pg_stat_database", databases, false)
rows, err := c.client.QueryContext(ctx, query)
if err != nil {
return nil, err
Expand All @@ -143,8 +144,8 @@ func (c *postgreSQLClient) getDatabaseStats(ctx context.Context, databases []str
dbStats := map[databaseName]databaseStats{}
for rows.Next() {
var datname string
var transactionCommitted, transactionRollback int64
err = rows.Scan(&datname, &transactionCommitted, &transactionRollback)
var transactionCommitted, transactionRollback, deadlocks int64
err = rows.Scan(&datname, &transactionCommitted, &transactionRollback, &deadlocks)
if err != nil {
errs = multierr.Append(errs, err)
continue
Expand All @@ -153,6 +154,7 @@ func (c *postgreSQLClient) getDatabaseStats(ctx context.Context, databases []str
dbStats[databaseName(datname)] = databaseStats{
transactionCommitted: transactionCommitted,
transactionRollback: transactionRollback,
deadlocks: deadlocks,
}
}
}
Expand Down
24 changes: 24 additions & 0 deletions receiver/postgresqlreceiver/documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,30 @@ This metric requires WAL to be enabled with at least one replica.
| operation | The operation which is responsible for the lag. | Str: ``flush``, ``replay``, ``write`` |
| replication_client | The IP address of the client connected to this backend. If this field is "unix", it indicates either that the client is connected via a Unix socket. | Any Str |

## Optional Metrics

The following metrics are not emitted by default. Each of them can be enabled by applying the following configuration:

```yaml
metrics:
<metric_name>:
enabled: true
```

### postgresql.deadlocks

The number of deadlocks.

| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic |
| ---- | ----------- | ---------- | ----------------------- | --------- |
| {deadlock} | Sum | Int | Cumulative | true |

#### Attributes

| Name | Description | Values |
| ---- | ----------- | ------ |
| database | The name of the database. | Any Str |

## Resource Attributes

| Name | Description | Values | Enabled |
Expand Down
1 change: 1 addition & 0 deletions receiver/postgresqlreceiver/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ func integrationTest(name string, databases []string) func(*testing.T) {
rCfg.Username = "otelu"
rCfg.Password = "otelp"
rCfg.Insecure = true
rCfg.Metrics.PostgresqlDeadlocks.Enabled = true
}),
scraperinttest.WithExpectedFile(expectedFile),
scraperinttest.WithCompareOptions(
Expand Down
15 changes: 15 additions & 0 deletions receiver/postgresqlreceiver/internal/metadata/custom.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,21 @@ func (m *metricPostgresqlRollbacks) recordDatapointWithoutDatabase(start pcommon
dp.SetIntValue(val)
}

// RecordPostgresqlDeadlocksDataPointWithoutDatabase adds a data point to postgresql.deadlocks metric without the database metric attribute.
func (mb *MetricsBuilder) RecordPostgresqlDeadlocksDataPointWithoutDatabase(ts pcommon.Timestamp, val int64) {
mb.metricPostgresqlDeadlocks.recordDatapointWithoutDatabase(mb.startTime, ts, val)
}

func (m *metricPostgresqlDeadlocks) recordDatapointWithoutDatabase(start pcommon.Timestamp, ts pcommon.Timestamp, val int64) {
if !m.config.Enabled {
return
}
dp := m.data.Sum().DataPoints().AppendEmpty()
dp.SetStartTimestamp(start)
dp.SetTimestamp(ts)
dp.SetIntValue(val)
}

// RecordPostgresqlRowsDataPointWithoutDatabaseAndTable adds a data point to postgresql.rows metric without the database or table metric attribute.
func (mb *MetricsBuilder) RecordPostgresqlRowsDataPointWithoutDatabaseAndTable(ts pcommon.Timestamp, val int64, stateAttributeValue AttributeState) {
mb.metricPostgresqlRows.recordDatapointWithoutDatabaseAndTable(mb.startTime, ts, val, stateAttributeValue.String())
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

61 changes: 61 additions & 0 deletions receiver/postgresqlreceiver/internal/metadata/generated_metrics.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ all_set:
enabled: true
postgresql.db_size:
enabled: true
postgresql.deadlocks:
enabled: true
postgresql.index.scans:
enabled: true
postgresql.index.size:
Expand Down Expand Up @@ -76,6 +78,8 @@ none_set:
enabled: false
postgresql.db_size:
enabled: false
postgresql.deadlocks:
enabled: false
postgresql.index.scans:
enabled: false
postgresql.index.size:
Expand Down
9 changes: 9 additions & 0 deletions receiver/postgresqlreceiver/metadata.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,15 @@ metrics:
monotonic: true
aggregation_temporality: cumulative
attributes: [database]
postgresql.deadlocks:
enabled: false
description: The number of deadlocks.
unit: "{deadlock}"
sum:
value_type: int
monotonic: true
aggregation_temporality: cumulative
attributes: [database]
postgresql.table.count:
attributes: []
description: Number of user tables in a database.
Expand Down
1 change: 1 addition & 0 deletions receiver/postgresqlreceiver/scraper.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ func (p *postgreSQLScraper) recordDatabase(now pcommon.Timestamp, db string, r *
if stats, ok := r.dbStats[dbName]; ok {
p.mb.RecordPostgresqlCommitsDataPointWithoutDatabase(now, stats.transactionCommitted)
p.mb.RecordPostgresqlRollbacksDataPointWithoutDatabase(now, stats.transactionRollback)
p.mb.RecordPostgresqlDeadlocksDataPointWithoutDatabase(now, stats.deadlocks)
}
rb := p.mb.NewResourceBuilder()
rb.SetPostgresqlDatabaseName(db)
Expand Down
12 changes: 9 additions & 3 deletions receiver/postgresqlreceiver/scraper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func TestScraper(t *testing.T) {

cfg := createDefaultConfig().(*Config)
cfg.Databases = []string{"otel"}
cfg.Metrics.PostgresqlDeadlocks.Enabled = true
scraper := newPostgreSQLScraper(receivertest.NewNopCreateSettings(), cfg, factory)

actualMetrics, err := scraper.scrape(context.Background())
Expand All @@ -55,6 +56,7 @@ func TestScraperNoDatabaseSingle(t *testing.T) {
factory.initMocks([]string{"otel"})

cfg := createDefaultConfig().(*Config)
cfg.Metrics.PostgresqlDeadlocks.Enabled = true
scraper := newPostgreSQLScraper(receivertest.NewNopCreateSettings(), cfg, factory)

actualMetrics, err := scraper.scrape(context.Background())
Expand All @@ -73,6 +75,7 @@ func TestScraperNoDatabaseMultiple(t *testing.T) {
factory.initMocks([]string{"otel", "open", "telemetry"})

cfg := createDefaultConfig().(*Config)
cfg.Metrics.PostgresqlDeadlocks.Enabled = true
scraper := newPostgreSQLScraper(receivertest.NewNopCreateSettings(), cfg, &factory)

actualMetrics, err := scraper.scrape(context.Background())
Expand All @@ -91,6 +94,7 @@ func TestScraperWithResourceAttributeFeatureGate(t *testing.T) {
factory.initMocks([]string{"otel", "open", "telemetry"})

cfg := createDefaultConfig().(*Config)
cfg.Metrics.PostgresqlDeadlocks.Enabled = true
scraper := newPostgreSQLScraper(receivertest.NewNopCreateSettings(), cfg, &factory)

actualMetrics, err := scraper.scrape(context.Background())
Expand All @@ -109,6 +113,7 @@ func TestScraperWithResourceAttributeFeatureGateSingle(t *testing.T) {
factory.initMocks([]string{"otel"})

cfg := createDefaultConfig().(*Config)
cfg.Metrics.PostgresqlDeadlocks.Enabled = true
scraper := newPostgreSQLScraper(receivertest.NewNopCreateSettings(), cfg, &factory)

actualMetrics, err := scraper.scrape(context.Background())
Expand Down Expand Up @@ -210,20 +215,21 @@ func (m *mockClient) initMocks(database string, databases []string, index int) {
if database == "" {
m.On("listDatabases").Return(databases, nil)

commitsAndRollbacks := map[databaseName]databaseStats{}
dbStats := map[databaseName]databaseStats{}
dbSize := map[databaseName]int64{}
backends := map[databaseName]int64{}

for idx, db := range databases {
commitsAndRollbacks[databaseName(db)] = databaseStats{
dbStats[databaseName(db)] = databaseStats{
transactionCommitted: int64(idx + 1),
transactionRollback: int64(idx + 2),
deadlocks: int64(idx + 3),
}
dbSize[databaseName(db)] = int64(idx + 4)
backends[databaseName(db)] = int64(idx + 3)
}

m.On("getDatabaseStats", databases).Return(commitsAndRollbacks, nil)
m.On("getDatabaseStats", databases).Return(dbStats, nil)
m.On("getDatabaseSize", databases).Return(dbSize, nil)
m.On("getBackends", databases).Return(backends, nil)
m.On("getBGWriterStats", mock.Anything).Return(&bgStat{
Expand Down
Loading

0 comments on commit cbe537d

Please sign in to comment.