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