-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonproc.go
196 lines (181 loc) · 4.42 KB
/
monproc.go
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
package main
/*
rootVIII
monproc - Displays CPU usage for each process
Intended for Debian Linux Distros
24OCT2019
USAGE: ./monproc <max results>
Max results should be a non-negative integer
*/
// #include <unistd.h>
// static int cpuSeconds() {
// return sysconf(_SC_CLK_TCK);
// }
import "C"
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
)
type process struct {
percentage float64
uptime float64
utime int
stime int
cutime int
cstime int
starttime int
hertz int
state string
pid string
name string
path string
}
func (mp *process) setState(s rune) {
statemap := map[rune]string{
'I': "Idle",
'R': "Running",
'S': "Sleeping",
'D': "Waiting",
'Z': "Zombie",
'T': "Stopped",
't': "Tracing stop",
'X': "Dead",
'x': "Dead",
'K': "Wakekill",
'W': "Waking",
'P': "Parked",
}
mp.state = statemap[s]
}
func (mp *process) getProcessDetails() (string, string, float64) {
return mp.name, mp.state, mp.percentage
}
func (mp *process) calcCPU() {
var total int = mp.utime + mp.stime + mp.cutime + mp.cstime
var sec float64 = mp.uptime - (float64(mp.starttime) / float64(mp.hertz))
mp.percentage = 100 * ((float64(total) / float64(mp.hertz)) / sec)
}
func (mp *process) getCPUSeconds(out chan<- struct{}) {
mp.hertz = int(C.cpuSeconds())
out <- struct{}{}
}
func (mp *process) rFile(p string) []byte {
content, _ := ioutil.ReadFile(mp.path + p)
return content
}
func (mp *process) getUptime(out chan<- struct{}) {
uptimeOut := bytes.Split(mp.rFile("uptime"), []byte(" "))
var uptime float64
fmt.Fscanf(bytes.NewReader(uptimeOut[0]), "%f", &uptime)
mp.uptime = uptime
out <- struct{}{}
}
func (mp *process) getStat(out chan<- struct{}) {
statOut := strings.Split(string(mp.rFile(mp.pid+"/stat")), " ")
if !strings.Contains(statOut[1], ")") {
revisedName := fmt.Sprintf("%s %s", statOut[1], statOut[2])
statOut[1] = revisedName
statOut = append(statOut[:2], statOut[3:]...)
}
mp.name = statOut[1][1 : len(statOut[1])-1]
mp.setState([]rune(statOut[2])[0])
mp.utime, _ = strconv.Atoi(statOut[13])
mp.stime, _ = strconv.Atoi(statOut[14])
mp.cutime, _ = strconv.Atoi(statOut[15])
mp.cstime, _ = strconv.Atoi(statOut[16])
mp.starttime, _ = strconv.Atoi(statOut[21])
out <- struct{}{}
}
func monProcWrpr(procPath string, pid string, toMain chan<- []string) {
ch := make(chan struct{})
var monproc = &process{path: procPath, pid: pid}
go monproc.getStat(ch)
go monproc.getCPUSeconds(ch)
go monproc.getUptime(ch)
for i := 0; i < 3; i++ {
<-ch
}
monproc.calcCPU()
name, status, percent := monproc.getProcessDetails()
results := []string{name, pid, fmt.Sprintf("%.2f", percent), status}
toMain <- results
}
func bubbleSort(procs [][]string) [][]string {
for {
sorted := true
for i := 0; i < len(procs)-1; i++ {
for j := 0; j < 4; j++ {
left, _ := strconv.ParseFloat(procs[i][2], 64)
right, _ := strconv.ParseFloat(procs[i+1][2], 64)
if left < right {
sorted = false
temp := procs[i+1]
procs[i+1] = procs[i]
procs[i] = temp
}
}
}
if sorted == true {
break
}
}
return procs
}
// GetProcesses - get percentage of CPU usage per running process.
func GetProcesses(max int) [][]string {
var path string = "/proc/"
files, err := ioutil.ReadDir(path)
if err != nil {
fmt.Println("Read error")
os.Exit(2)
}
toMain := make(chan []string)
var index int
for _, pid := range files {
_, err := strconv.Atoi(pid.Name())
if err != nil {
continue
}
go monProcWrpr(path, pid.Name(), toMain)
index++
}
final := make([][]string, 0)
for i := 0; i < index; i++ {
temp := <-toMain
resultRow := make([]string, len(temp))
for j := 0; j < len(temp); j++ {
resultRow[j] = temp[j]
}
if resultRow[0] != "go" && resultRow[0] != "monproc" {
final = append(final, resultRow)
}
}
if len(final) < max {
return bubbleSort(final)
}
return bubbleSort(final)[:max]
}
func help() string {
help := "\nEnter the max records to return.\n"
help += "EX: monproc 5 monproc 10 monproc 100 etc.\n\n"
return help
}
func main() {
if len(os.Args) < 2 {
fmt.Printf(help())
os.Exit(1)
}
maxRecords, err := strconv.Atoi(os.Args[1])
if err != nil || maxRecords < 0 {
fmt.Printf("Error" + help())
os.Exit(1)
}
fmt.Printf("%-10s %-30s %-19s %-10s\n", "PID", "NAME", "CPU%", "STATE")
for _, p := range GetProcesses(maxRecords) {
fmt.Printf("%-10s %-30s %-20s %-12s\n", p[1], p[0], p[2], p[3])
}
}