Skip to content

Commit a74c75d

Browse files
authored
feat: collect metrics on available storage (#2730)
Adds a `nodejs_fs_usage_bytes` metric that reports how much disk space is available.
1 parent 9308bc1 commit a74c75d

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

packages/metrics-prometheus/src/index.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@
6666
* ```
6767
*/
6868

69+
import { statfs } from 'node:fs/promises'
70+
import { totalmem } from 'node:os'
6971
import { serviceCapabilities } from '@libp2p/interface'
7072
import each from 'it-foreach'
7173
import { collectDefaultMetrics, type DefaultMetricsCollectorConfiguration, register, type Registry, type RegistryContentType } from 'prom-client'
@@ -111,6 +113,14 @@ export interface PrometheusMetricsInit {
111113
* pass true here
112114
*/
113115
preserveExistingMetrics?: boolean
116+
117+
/**
118+
* The current filesystem usage is reported as the metric
119+
* `nodejs_fs_usage_bytes` using the `statfs` function from `node:fs` - the
120+
* default location to stat is the current working directory, configured this
121+
* location here
122+
*/
123+
statfsLocation?: string
114124
}
115125

116126
export interface PrometheusCalculatedMetricOptions<T=number> extends CalculatedMetricOptions<T> {
@@ -178,6 +188,25 @@ class PrometheusMetrics implements Metrics {
178188
}
179189
}
180190
})
191+
const totalMemoryMetric = this.registerMetric('nodejs_memory_total_bytes')
192+
totalMemoryMetric.update(totalmem())
193+
194+
this.log('Collecting filesystem metrics')
195+
this.registerMetricGroup('nodejs_fs_usage_bytes', {
196+
label: 'filesystem',
197+
calculate: async () => {
198+
const stats = await statfs(init?.statfsLocation ?? process.cwd())
199+
const total = stats.bsize * stats.blocks
200+
const available = stats.bsize * stats.bavail
201+
202+
return {
203+
total,
204+
free: stats.bsize * stats.bfree,
205+
available,
206+
used: (available / total) * 100
207+
}
208+
}
209+
})
181210
}
182211

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

0 commit comments

Comments
 (0)