Skip to content

Commit

Permalink
feat: collect metrics on available storage (#2730)
Browse files Browse the repository at this point in the history
Adds a `nodejs_fs_usage_bytes` metric that reports how much disk
space is available.
  • Loading branch information
achingbrain authored Sep 27, 2024
1 parent 9308bc1 commit a74c75d
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions packages/metrics-prometheus/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@
* ```
*/

import { statfs } from 'node:fs/promises'
import { totalmem } from 'node:os'
import { serviceCapabilities } from '@libp2p/interface'
import each from 'it-foreach'
import { collectDefaultMetrics, type DefaultMetricsCollectorConfiguration, register, type Registry, type RegistryContentType } from 'prom-client'
Expand Down Expand Up @@ -111,6 +113,14 @@ export interface PrometheusMetricsInit {
* pass true here
*/
preserveExistingMetrics?: boolean

/**
* The current filesystem usage is reported as the metric
* `nodejs_fs_usage_bytes` using the `statfs` function from `node:fs` - the
* default location to stat is the current working directory, configured this
* location here
*/
statfsLocation?: string
}

export interface PrometheusCalculatedMetricOptions<T=number> extends CalculatedMetricOptions<T> {
Expand Down Expand Up @@ -178,6 +188,25 @@ class PrometheusMetrics implements Metrics {
}
}
})
const totalMemoryMetric = this.registerMetric('nodejs_memory_total_bytes')
totalMemoryMetric.update(totalmem())

this.log('Collecting filesystem metrics')
this.registerMetricGroup('nodejs_fs_usage_bytes', {
label: 'filesystem',
calculate: async () => {
const stats = await statfs(init?.statfsLocation ?? process.cwd())
const total = stats.bsize * stats.blocks
const available = stats.bsize * stats.bavail

return {
total,
free: stats.bsize * stats.bfree,
available,
used: (available / total) * 100
}
}
})
}

readonly [Symbol.toStringTag] = '@libp2p/metrics-prometheus'
Expand Down

0 comments on commit a74c75d

Please sign in to comment.