-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprocess.go
More file actions
204 lines (177 loc) · 5.56 KB
/
process.go
File metadata and controls
204 lines (177 loc) · 5.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package main
import (
"fmt"
"net/http"
"os"
"strconv"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/shirou/gopsutil/v3/mem"
"github.com/shirou/gopsutil/v3/process"
"github.com/sirupsen/logrus"
)
const (
namespace = "node"
subsystem = "process"
)
// 定义指标的标签
var processLabels = []string{"name", "pid", "cmd", "user"}
// ProcessCollector 实现了 prometheus.Collector 接口
type ProcessCollector struct {
CPU *prometheus.Desc
Memory *prometheus.Desc
OpenFiles *prometheus.Desc
ReadBytesTotal *prometheus.Desc
WriteBytesTotal *prometheus.Desc
}
// NewProcessCollector 创建一个新的 ProcessCollector
func NewProcessCollector() *ProcessCollector {
return &ProcessCollector{
CPU: prometheus.NewDesc(
prometheus.BuildFQName(namespace, subsystem, "cpu_usage_percent"),
"Process CPU usage percentage.",
processLabels,
nil,
),
Memory: prometheus.NewDesc(
prometheus.BuildFQName(namespace, subsystem, "memory_usage_percent"),
"Process memory usage percentage.",
processLabels,
nil,
),
OpenFiles: prometheus.NewDesc(
prometheus.BuildFQName(namespace, subsystem, "open_files_count"),
"Number of open files by the process.",
processLabels,
nil,
),
ReadBytesTotal: prometheus.NewDesc(
prometheus.BuildFQName(namespace, subsystem, "read_bytes_total"),
"Total number of bytes read by the process.",
processLabels,
nil,
),
WriteBytesTotal: prometheus.NewDesc(
prometheus.BuildFQName(namespace, subsystem, "write_bytes_total"),
"Total number of bytes written by the process.",
processLabels,
nil,
),
}
}
// Describe 将所有指标的描述符发送到提供的 channel
func (pc *ProcessCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- pc.CPU
ch <- pc.Memory
ch <- pc.OpenFiles
ch <- pc.ReadBytesTotal
ch <- pc.WriteBytesTotal
}
// Collect 收集所有进程的指标数据
func (pc *ProcessCollector) Collect(ch chan<- prometheus.Metric) {
processes, err := process.Processes()
if err != nil {
logrus.Errorf("Failed to get processes: %v", err)
return
}
for _, proc := range processes {
pid := proc.Pid
name, err := proc.Name()
if err != nil {
logrus.Debugf("Failed to get name for PID %d, err: %v", pid, err)
continue
}
cmdline, err := proc.Cmdline()
if err != nil {
logrus.Debugf("Failed to get cmdline for PID %d (%s), err: %v", pid, name, err)
cmdline = ""
}
user, err := proc.Username()
if err != nil {
logrus.Debugf("Failed to get username for PID %d (%s), err: %v", pid, name, err)
user = "unknown"
}
// 创建标签值
labelValues := []string{name, strconv.Itoa(int(pid)), cmdline, user}
// 获取并注册 CPU 指标
if cpuPercent, err := proc.CPUPercent(); err == nil {
if cpuPercent > 0 {
ch <- prometheus.MustNewConstMetric(pc.CPU, prometheus.GaugeValue, cpuPercent, labelValues...)
}
} else {
logrus.Debugf("Failed to get CPU usage for PID %d (%s), err: %v", pid, name, err)
}
// 获取并注册内存指标
if memPercent, err := getProcMemoryPercent(proc); err == nil {
if memPercent > 0 {
ch <- prometheus.MustNewConstMetric(pc.Memory, prometheus.GaugeValue, memPercent, labelValues...)
}
} else {
logrus.Debugf("Failed to get memory usage for PID %d (%s), err: %v", pid, name, err)
}
// 获取并注册文件打开数指标
if openFiles, err := proc.OpenFiles(); err == nil {
count := len(openFiles)
if count > 0 {
ch <- prometheus.MustNewConstMetric(pc.OpenFiles, prometheus.GaugeValue, float64(count), labelValues...)
}
} else {
logrus.Debugf("Failed to get open files for PID %d (%s), err: %v", pid, name, err)
}
// 获取并注册磁盘读写
if ioCounters, err := proc.IOCounters(); err == nil {
ch <- prometheus.MustNewConstMetric(pc.ReadBytesTotal, prometheus.CounterValue, float64(ioCounters.ReadBytes), labelValues...)
ch <- prometheus.MustNewConstMetric(pc.WriteBytesTotal, prometheus.CounterValue, float64(ioCounters.WriteBytes), labelValues...)
} else {
logrus.Debugf("Failed to get IO counters for PID %d (%s), err: %v", pid, name, err)
}
}
}
// getProcMemoryPercent 计算单个进程的内存使用百分比
func getProcMemoryPercent(proc *process.Process) (float64, error) {
procMem, err := proc.MemoryInfo()
if err != nil {
return 0, err
}
nodeMem, err := mem.VirtualMemory()
if err != nil {
return 0, err
}
// 进程内存使用率 = (进程使用的物理内存 / 节点总物理内存) * 100
return (float64(procMem.RSS) / float64(nodeMem.Total)) * 100.0, nil
}
func main() {
var (
port int
level logrus.Level
)
ll := os.Getenv("LOG_LEVEL")
if ll == "debug" {
level = logrus.DebugLevel
} else {
level = logrus.InfoLevel
}
port, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil {
port = 9002
} else if port < 1024 {
logrus.Fatalf("Invalid port number: %d. Please use a port number greater than or equal to 1024.", port)
}
logrus.SetFormatter(&logrus.TextFormatter{})
logrus.SetLevel(level)
// 创建自定义采集器并注册
procCollector := NewProcessCollector()
registry := prometheus.NewRegistry()
registry.MustRegister(procCollector)
// 创建 HTTP 处理器
handler := promhttp.HandlerFor(registry, promhttp.HandlerOpts{
ErrorHandling: promhttp.ContinueOnError,
})
http.Handle("/metrics", handler)
addr := fmt.Sprintf(":%d", port)
logrus.Infof("Service started! Listening on %s", addr)
// 启动 HTTP 服务
if err := http.ListenAndServe(addr, nil); err != nil {
logrus.Fatalf("Failed to start HTTP server: %v", err)
}
}