fork of https://github.com/sourcegraph/zoekt
1package main
2
3import (
4 "path"
5
6 "github.com/prometheus/client_golang/prometheus"
7 "github.com/prometheus/procfs"
8 sglog "github.com/sourcegraph/log"
9)
10
11func mustRegisterMemoryMapMetrics(logger sglog.Logger) {
12 logger = logger.Scoped("memoryMapMetrics")
13
14 // The memory map metrics are collected via /proc, which
15 // is only available on linux-based operating systems.
16
17 // Instantiate shared FS objects for accessing /proc and /proc/self,
18 // and skip metrics registration if we're aren't able to instantiate them
19 // for whatever reason.
20
21 fs, err := procfs.NewDefaultFS()
22 if err != nil {
23 logger.Debug(
24 "skipping registration",
25 sglog.String("reason", "failed to initialize proc FS"),
26 sglog.String("error", err.Error()),
27 )
28
29 return
30 }
31
32 info, err := fs.Self()
33 if err != nil {
34 logger.Debug(
35 "skipping registration",
36 sglog.String("path", path.Join(procfs.DefaultMountPoint, "self")),
37 sglog.String("reason", "failed to initialize process info object for current process"),
38 sglog.String("error", err.Error()),
39 )
40
41 return
42 }
43
44 // Register Prometheus memory map metrics
45
46 prometheus.MustRegister(prometheus.NewGaugeFunc(prometheus.GaugeOpts{
47 Name: "proc_metrics_memory_map_max_limit",
48 Help: "Upper limit on amount of memory mapped regions a process may have.",
49 }, func() float64 {
50 vm, err := fs.VM()
51 if err != nil {
52 logger.Debug(
53 "failed to read virtual memory statistics for the current process",
54 sglog.String("path", path.Join(procfs.DefaultMountPoint, "sys", "vm")),
55 sglog.String("error", err.Error()),
56 )
57
58 return 0
59 }
60
61 if vm.MaxMapCount == nil {
62 return 0
63 }
64
65 return float64(*vm.MaxMapCount)
66 }))
67
68 prometheus.MustRegister(prometheus.NewGaugeFunc(prometheus.GaugeOpts{
69 Name: "proc_metrics_memory_map_current_count",
70 Help: "Amount of memory mapped regions this process is currently using.",
71 }, func() float64 {
72 procMaps, err := info.ProcMaps()
73 if err != nil {
74 logger.Debug(
75 "failed to read memory mappings for current process",
76 sglog.String("path", path.Join(procfs.DefaultMountPoint, "self", "maps")),
77 sglog.String("error", err.Error()),
78 )
79
80 return 0
81 }
82
83 return float64(len(procMaps))
84 }))
85}