Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
399 lines (357 loc) · 12.1 KB
/
Copy pathmain.go
File metadata and controls
399 lines (357 loc) · 12.1 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package main
import (
"bytes"
"context"
"errors"
"flag"
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"runtime"
"runtime/debug"
"strconv"
"strings"
"syscall"
"time"
"github.com/cilium/ebpf"
"github.com/cilium/ebpf/features"
"github.com/coroot/coroot-node-agent/common"
"github.com/coroot/coroot-node-agent/containers"
"github.com/coroot/coroot-node-agent/flags"
"github.com/coroot/coroot-node-agent/gpu"
"github.com/coroot/coroot-node-agent/logs"
"github.com/coroot/coroot-node-agent/node"
"github.com/coroot/coroot-node-agent/proc"
"github.com/coroot/coroot-node-agent/profiling"
"github.com/coroot/coroot-node-agent/prom"
"github.com/coroot/coroot-node-agent/tracing"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/sys/unix"
"golang.org/x/time/rate"
"inet.af/netaddr"
"k8s.io/client-go/kubernetes"
"k8s.io/klog/v2"
)
var (
version = flags.Version
)
func uname() (string, string, error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
f, err := os.Open("/proc/1/ns/uts")
if err != nil {
return "", "", err
}
defer f.Close()
self, err := os.Open("/proc/self/ns/uts")
if err != nil {
return "", "", err
}
defer self.Close()
defer func() {
unix.Setns(int(self.Fd()), unix.CLONE_NEWUTS)
}()
err = unix.Setns(int(f.Fd()), unix.CLONE_NEWUTS)
if err != nil {
return "", "", err
}
var utsname unix.Utsname
if err := unix.Uname(&utsname); err != nil {
return "", "", err
}
hostname := string(bytes.Split(utsname.Nodename[:], []byte{0})[0])
kernelVersion := string(bytes.Split(utsname.Release[:], []byte{0})[0])
return hostname, kernelVersion, nil
}
func machineID() string {
for _, p := range []string{"/etc/machine-id", "/var/lib/dbus/machine-id", "/sys/devices/virtual/dmi/id/product_uuid"} {
payload, err := os.ReadFile(proc.HostPath(p))
if err != nil {
klog.Warningln("failed to read machine-id:", err)
continue
}
id := strings.TrimSpace(strings.Replace(string(payload), "-", "", -1))
klog.Infoln("machine-id: ", id)
return id
}
return ""
}
func systemUUID() string {
payload, err := os.ReadFile(proc.HostPath("/sys/devices/virtual/dmi/id/product_uuid"))
if err != nil {
klog.Warningln("failed to read system-uuid:", err)
return ""
}
return strings.TrimSpace(string(payload))
}
func whitelistNodeExternalNetworks() {
netdevs, err := node.NetDevices()
if err != nil {
klog.Warningln("failed to get network interfaces:", err)
return
}
for _, iface := range netdevs {
for _, p := range iface.IPPrefixes {
if p.IP().IsLoopback() || common.IsIpPrivate(p.IP()) {
continue
}
// if the node has an external network IP, whitelist that network
common.ConnectionFilter.WhitelistPrefix(p)
}
}
}
func localIPs() ([]netaddr.IP, error) {
netdevs, err := node.NetDevices()
if err != nil {
return nil, err
}
var ips []netaddr.IP
for _, iface := range netdevs {
for _, p := range iface.IPPrefixes {
ips = append(ips, p.IP())
}
}
return ips, nil
}
func newIPResolver(hostname string) (containers.IPResolver, error) {
config, err := common.KubernetesConfig()
if err != nil {
return nil, fmt.Errorf("kubernetes config: %w", err)
}
if config == nil {
klog.Infoln("no kubernetes API found, running in standalone host mode")
return common.NewVMIPResolver(hostname, localIPs, *flags.ResolveDns)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("kubernetes clientset: %w", err)
}
return common.NewK8sIPResolver(clientset, *flags.ResolveDns)
}
func main() {
// Set GOMEMLIMIT to 60% of cgroup memory limit if available, otherwise use env var.
// Use 60% (not 90%) because the cgroup OOM killer counts kernel memory (~80MB for
// eBPF maps) and file page cache (~200MB from /proc reads) which GOMEMLIMIT doesn't
// control. At 90%, Go heap + kernel + page cache exceeds the cgroup limit.
if os.Getenv("GOMEMLIMIT") == "" {
if limit, err := readCgroupMemoryLimit(); err == nil && limit > 0 {
softLimit := int64(float64(limit) * 0.6)
debug.SetMemoryLimit(softLimit)
log.Printf("GOMEMLIMIT set to %dMiB (60%% of cgroup limit %dMiB)", softLimit/1024/1024, limit/1024/1024)
}
}
// Initialize klog flags to prevent duplicate output
klog.InitFlags(nil)
if v := os.Getenv("KLOG_V"); v != "" {
flag.Set("v", v)
}
flag.Set("logtostderr", "false")
flag.Set("alsologtostderr", "false")
flag.Set("stderrthreshold", "FATAL")
// SetOutput gives every severity the same writer, and klog writes a
// message to its own severity's writer and every lower one's: without
// one_output each warning was logged twice and each error three times.
flag.Set("one_output", "true")
klog.SetOutput(&RateLimitedLogOutput{limiter: rate.NewLimiter(rate.Limit(*flags.LogPerSecond), *flags.LogBurst)})
klog.Infoln("agent version:", version)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
sigChannel := make(chan os.Signal, 1)
signal.Notify(sigChannel, os.Interrupt, syscall.SIGTERM)
<-sigChannel
klog.Infoln("Received signal, shutting down")
cancel()
}()
hostname, kv, err := uname()
if err != nil {
klog.Exitln("failed to get uname:", err)
}
klog.Infoln("hostname:", hostname)
klog.Infoln("kernel version:", kv)
if err = common.SetKernelVersion(kv); err != nil {
klog.Exitln(err)
}
// L7 events go through a BPF ring buffer (BPF_MAP_TYPE_RINGBUF), which
// every program variant uses: without it the programs fail to load
// further on, with a less clear error. Probe for the map type rather than
// checking for 5.8: RHEL 8 kernels (4.18) backport it. Kernels before
// 5.11 charge the probe's map to RLIMIT_MEMLOCK, so raise it first, as the
// tracer does before loading. Only a definite "not supported" is fatal:
// any other probe error (missing privileges) is left for the program
// loader to report.
_ = unix.Setrlimit(unix.RLIMIT_MEMLOCK, &unix.Rlimit{Cur: unix.RLIM_INFINITY, Max: unix.RLIM_INFINITY})
if err := features.HaveMapType(ebpf.RingBuf); errors.Is(err, ebpf.ErrNotSupported) {
klog.Exitf("the kernel does not support BPF ring buffers (Linux 5.8 or later, or a distribution kernel that backports them, such as RHEL 8): %s", err)
} else if err != nil {
klog.Warningf("failed to probe for BPF ring buffer support: %s", err)
}
resolver, err := newIPResolver(hostname)
if err != nil {
log.Fatalf("Error creating resolver: %v", err)
}
err = resolver.StartWatching()
if err != nil {
klog.Errorf("Error starting resolver: %v", err)
}
defer resolver.StopWatching()
whitelistNodeExternalNetworks()
machineId := machineID()
systemUuid := systemUUID()
tracing.Init(machineId, hostname, version)
logs.Init(machineId, hostname, version)
// Without Kubernetes there is usually no node_exporter: export the host's
// filesystem, load and swap metrics under its names.
_, standalone := resolver.(*common.VMIPResolver)
nodeCollector := node.NewCollector(hostname, kv, standalone)
registry := prometheus.NewRegistry()
registerer := prometheus.WrapRegistererWith(
prometheus.Labels{"machine_id": machineId, "system_uuid": systemUuid},
registry,
)
if err := registerer.Register(nodeCollector); err != nil {
klog.Exitln(err)
}
gpuCollector, err := gpu.NewCollector()
if err != nil {
klog.Warningln("failed to initialize GPU collector:", err)
}
if err := registerer.Register(gpuCollector); err != nil {
klog.Exitln(err)
}
registerer.MustRegister(info("node_agent_info", version))
registerer.MustRegister(logs.RecordsDroppedTotal)
az := ""
region := ""
if md := nodeCollector.Metadata(); md != nil {
region = md.Region
az = md.AvailabilityZone
if region != "" && az != "" {
registerer = prometheus.WrapRegistererWith(prometheus.Labels{"az": az, "region": region}, registerer)
}
}
processInfoCh := profiling.Init(machineId, hostname)
// Pass both the wrapped registerer (for ip2fqdn and LLM metrics) and the raw
// registry (for containers) to avoid WrapRegistererWith allocation overhead on
// the hot path. Container metrics embed const labels directly.
cr, err := containers.NewRegistry(registerer, registry, processInfoCh, resolver, gpuCollector.ProcessUsageSampleCh, machineId, systemUuid, az, region)
if err != nil {
klog.Exitln(err)
}
defer cr.Close()
profiling.Start()
defer profiling.Stop()
if err := prom.StartAgent(registry, machineId, systemUuid); err != nil {
klog.Exitln(err)
}
// Metrics endpoint with timeout protection
http.Handle("/metrics", http.TimeoutHandler(
promhttp.HandlerFor(registry, promhttp.HandlerOpts{ErrorLog: logger{}, Registry: registerer, ErrorHandling: promhttp.ContinueOnError}),
30*time.Second,
"Metrics collection timeout",
))
srv := &http.Server{Addr: *flags.ListenAddress}
go func() {
<-ctx.Done()
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer shutdownCancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
klog.Errorf("HTTP server shutdown error: %v", err)
}
}()
klog.Infoln("listening on:", *flags.ListenAddress)
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
if *flags.MetricsEndpoint == nil {
// Nothing can scrape the agent: exit non-zero so the service
// manager restarts it.
klog.Exitln(err)
} else {
// Metrics are pushed: the local endpoint is optional, so a
// taken port must not stop the agent.
klog.Errorln("local metrics endpoint unavailable, metrics are still pushed:", err)
<-ctx.Done()
}
}
// Before anything else stops: deliver the log lines already read and save how
// far each file got, within the pod's 30 s default termination grace period.
logs.Shutdown(logsShutdownTimeout)
klog.Infoln("shutdown complete")
}
const logsShutdownTimeout = 15 * time.Second
func info(name, version string) prometheus.Collector {
g := prometheus.NewGauge(prometheus.GaugeOpts{
Name: name,
ConstLabels: prometheus.Labels{"version": version},
})
g.Set(1)
return g
}
type logger struct{}
func (l logger) Println(v ...interface{}) {
klog.Errorln(v...)
}
type RateLimitedLogOutput struct {
limiter *rate.Limiter
}
func (o *RateLimitedLogOutput) Write(data []byte) (int, error) {
if !o.limiter.Allow() {
return len(data), nil
}
return os.Stderr.Write(data)
}
// readCgroupMemoryLimit reads the memory limit from cgroup v2 or v1.
// The agent runs with hostPID, so /proc/1/cgroup points to the host root (init.scope)
// which has no memory limit. We use /proc/self/cgroup to find the container's own
// cgroup path where kubelet enforces the pod memory limit.
func readCgroupMemoryLimit() (int64, error) {
// Parse /proc/self/cgroup to find the container's own cgroup path.
// cgroupv2: "0::/kubepods.slice/.../cri-containerd-xxx.scope"
// cgroupv1: "N:memory:/kubepods/burstable/pod-xxx/container-yyy"
if data, err := os.ReadFile("/proc/self/cgroup"); err == nil {
for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
parts := strings.SplitN(line, ":", 3)
if len(parts) < 3 {
continue
}
var cgPath string
if parts[0] == "0" { // cgroup v2
cgPath = "/sys/fs/cgroup" + parts[2] + "/memory.max"
} else if strings.Contains(parts[1], "memory") { // cgroup v1
cgPath = "/sys/fs/cgroup/memory" + parts[2] + "/memory.limit_in_bytes"
}
if cgPath != "" {
if mem, err := os.ReadFile(cgPath); err == nil {
s := strings.TrimSpace(string(mem))
if s != "max" {
if limit, err := strconv.ParseInt(s, 10, 64); err == nil && limit > 0 && limit < 1<<62 {
return limit, nil
}
}
}
}
}
}
// Fallback: try cgroup v2 at root (non-hostPID containers)
if data, err := os.ReadFile("/sys/fs/cgroup/memory.max"); err == nil {
s := strings.TrimSpace(string(data))
if s != "max" {
if limit, err := strconv.ParseInt(s, 10, 64); err == nil {
return limit, nil
}
}
}
// Fallback: try cgroup v1 at root (non-hostPID containers)
if data, err := os.ReadFile("/sys/fs/cgroup/memory/memory.limit_in_bytes"); err == nil {
s := strings.TrimSpace(string(data))
if limit, err := strconv.ParseInt(s, 10, 64); err == nil {
if limit < 1<<62 {
return limit, nil
}
}
}
return 0, fmt.Errorf("unable to read cgroup memory limit")
}