Debian Codegraph @

server/pse/pse_linux.go

raw
1 // Copyright 2015-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package pse
15
16 import (
17 "bytes"
18 "fmt"
19 "os"
20 "sync/atomic"
21 "syscall"
22 "time"
23 )
24
25 var (
26 procStatFile string
27 ticks int64
28 lastTotal int64
29 lastSeconds int64
30 ipcpu int64
31 pageSize int64
32 )
33
34 const (
35 utimePos = 13
36 stimePos = 14
37 startPos = 21
38 vssPos = 22
39 rssPos = 23
40 )
41
42 func init() {
43 // Avoiding to generate docker image without CGO
44 ticks = 100 // int64(C.sysconf(C._SC_CLK_TCK))
45 procStatFile = fmt.Sprintf("/proc/%d/stat", os.Getpid())
46 pageSize = int64(os.Getpagesize())
47 periodic()
48 }
49
50 // Sampling function to keep pcpu relevant.
51 func periodic() {
52 contents, err := os.ReadFile(procStatFile)
53 if err != nil {
54 return
55 }
56 fields := bytes.Fields(contents)
57
58 // PCPU
59 pstart := parseInt64(fields[startPos])
60 utime := parseInt64(fields[utimePos])
61 stime := parseInt64(fields[stimePos])
62 total := utime + stime
63
64 var sysinfo syscall.Sysinfo_t
65 if err := syscall.Sysinfo(&sysinfo); err != nil {
66 return
67 }
68
69 seconds := int64(sysinfo.Uptime) - (pstart / ticks)
70
71 // Save off temps
72 lt := lastTotal
73 ls := lastSeconds
74
75 // Update last sample
76 lastTotal = total
77 lastSeconds = seconds
78
79 // Adjust to current time window
80 total -= lt
81 seconds -= ls
82
83 if seconds > 0 {
84 atomic.StoreInt64(&ipcpu, (total*1000/ticks)/seconds)
85 }
86
87 time.AfterFunc(1*time.Second, periodic)
88 }
89
90 // ProcUsage returns CPU usage
91 func ProcUsage(pcpu *float64, rss, vss *int64) error {
92 contents, err := os.ReadFile(procStatFile)
93 if err != nil {
94 return err
95 }
96 fields := bytes.Fields(contents)
97
98 // Memory
99 *rss = (parseInt64(fields[rssPos])) * pageSize
100 *vss = parseInt64(fields[vssPos])
101
102 // PCPU
103 // We track this with periodic sampling, so just load and go.
104 *pcpu = float64(atomic.LoadInt64(&ipcpu)) / 10.0
105
106 return nil
107 }
108
109 // Ascii numbers 0-9
110 const (
111 asciiZero = 48
112 asciiNine = 57
113 )
114
115 // parseInt64 expects decimal positive numbers. We
116 // return -1 to signal error
117 func parseInt64(d []byte) (n int64) {
118 if len(d) == 0 {
119 return -1
120 }
121 for _, dec := range d {
122 if dec < asciiZero || dec > asciiNine {
123 return -1
124 }
125 n = n*10 + (int64(dec) - asciiZero)
126 }
127 return n
128 }