summaryrefslogtreecommitdiff
path: root/gstat/main.go
blob: 147f645ead87999fa2b6368aed143cd26a933b4f (plain)
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
// gstat (C) 2015 Paul Buetow (gstat@dev.buetow.org)

package main

import (
	"container/list"
	"errors"
	"flag"
	"fmt"
	"github.com/buetow/gstat/diskstats"
	"github.com/buetow/gstat/process"
	"github.com/buetow/gstat/utils"
	"golang.org/x/crypto/ssh/terminal"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var config struct {
	banner   string
	interval time.Duration
	binary   *bool
	mode     *int
	modeName string
}

type twoP struct {
	first, second      process.Process
	diff, diffR, diffW int
	exited             bool
}
type mapP map[string]twoP

func timedGather(tChan <-chan bool, dRxChan chan<- diskstats.Diskstats, pRxChan chan<- process.Process) {
	for {
		switch <-tChan {
		case false:
			{
				break
			}
		case true:
			{
				go diskstats.Gather(dRxChan)
				go process.Gather(pRxChan)
			}
		}
	}
	close(dRxChan)
	close(pRxChan)
}

func receiveD(dRxChan <-chan diskstats.Diskstats) {
	for d := range dRxChan {
		//diskstats.Print()
		// Implemented later
		_ = d
	}
}

func sortP(lastP *mapP) *list.List {
	remove := list.New()
	sorted := list.New()

	for _, val := range *lastP {
		nowTimestamp := int32(time.Now().Unix())
		if val.first.Timestamp+2 < nowTimestamp {
			// Schedule remove obsolete pids from lastP
			remove.PushBack(val.first.Id)
			// Display this process one more time, but in a fancy way
			val.exited = true
		}

		if val.diff > 0 {
			// Insertion sort
			if sorted.Len() > 0 {
				for e := sorted.Front(); e != nil; e = e.Next() {
					diff := e.Value.(twoP).diff
					if diff < val.diff {
						//fmt.Printf("Inserting %d before %d\n", val.diff, diff)
						sorted.InsertBefore(val, e)
						break
					}
				}
			} else {
				sorted.PushFront(val)
			}
		}
	}

	// Rremove obsolete pids from lastP
	for e := remove.Front(); e != nil; e = e.Next() {
		id := e.Value.(string)
		//fmt.Println("Removing stale process: " + id)
		delete(*lastP, id)
	}

	return sorted
}

func printP(sortedP *list.List) {
	tWidth, tHeight, err := terminal.GetSize(0)
	if err != nil {
		log.Fatal(err)
	}

	// Clear the screen + print header
	fmt.Printf("\033[H\033[2J")
	fmt.Printf("Mode: %s, Interval: %s\n", config.modeName, config.interval)
	fmt.Printf("(Hit Ctr-C to quit, re-run with -h for flags)\n")
	fmt.Printf("%5s/%5s %5s %s\n", "WRITE", "READS", "PID", "COMMAND")

	// Print the results
	row := 3
	for e := sortedP.Front(); e != nil; e = e.Next() {
		row++
		if row > tHeight {
			break
		}
		val := e.Value.(twoP)
		first := val.first

		var outstr string

		if val.exited {
			outstr = fmt.Sprintf("XXXXXXXXXXX %5d %s", first.Pid, first.Cmdline)

		} else {
			var humanW, humanR string

			if *config.binary {
				humanW, humanR = utils.HumanBinary(val.diffW), utils.HumanBinary(val.diffR)
			} else {
				humanW, humanR = utils.Human(val.diffW), utils.Human(val.diffR)
			}

			outstr = fmt.Sprintf("%5s %5s %5d %s", humanW, humanR, first.Pid, first.Cmdline)
		}

		l := len(outstr)
		if l > tWidth {
			l = tWidth
		}
		fmt.Printf("%s\n", outstr[0:l])
	}
}

func modeNames() (string, string, string, error) {
	switch *config.mode {
	case 0:
		return "read_bytes", "write_bytes", "bytes", nil
	case 1:
		return "syscr", "syscw", "syscalls", nil
	case 2:
		return "rchar", "wchar", "chars", nil
	}

	errstr := fmt.Sprintf("No such mode: %d\n", *config.mode)
	return "", "", "", errors.New(errstr)
}

func receiveP(pRxChan <-chan process.Process) {
	lastP := make(mapP)
	flag := false

	readKey, writeKey, modeName, err := modeNames()
	if err != nil {
		log.Fatal(err)
	}
	config.modeName = modeName

	makeDiff := func(first, second process.Process) twoP {
		firstValR, firstValW := first.Count[readKey], first.Count[writeKey]
		secondValR, secondValW := second.Count[readKey], second.Count[writeKey]
		diffR, diffW := utils.Abs(firstValR-secondValR), utils.Abs(firstValW-secondValW)
		diff := diffR + diffW
		return twoP{first, second, diff, diffR, diffW, false}
	}

	for p := range pRxChan {
		if p.Last {
			if flag {
				printP(sortP(&lastP))
			}
			flag = !flag
		} else {
			if val, ok := lastP[p.Id]; ok {
				if flag {
					lastP[p.Id] = makeDiff(val.first, p)
				} else {
					lastP[p.Id] = makeDiff(p, val.second)
				}
			} else {
				lastP[p.Id] = twoP{first: p}
			}
		}
	}
}

func parseFlags() {
	helpF := flag.Bool("v", false, "Print the version")
	interF := flag.Int("i", 2, "Update interval in seconds")

	config.binary = flag.Bool("b", false, "Use binary instead of deciman (e.g. kiB an not kB")
	config.mode = flag.Int("m", 1, "The stats mode: 0:bytes 1:syscalls 2:chars")

	flag.Parse()

	config.banner = "gstat v0.1 (C) 2015 Paul buetow <http://gstat.buetow.org>"

	if *helpF {
		fmt.Println(config.banner)
		os.Exit(0)
	}

	config.interval = time.Duration(*interF) * time.Second
}

func main() {
	parseFlags()

	tChan := make(chan bool)
	dRxChan := make(chan diskstats.Diskstats)
	pRxChan := make(chan process.Process)

	go timedGather(tChan, dRxChan, pRxChan)
	go receiveD(dRxChan)
	go receiveP(pRxChan)

	termChan := make(chan os.Signal, 1)
	signal.Notify(termChan, os.Interrupt)
	signal.Notify(termChan, syscall.SIGTERM)

	go func() {
		<-termChan
		tChan <- false
		fmt.Println("Good bye! This was:")
		fmt.Println(config.banner)
		os.Exit(0)
	}()

	for {
		tChan <- true
		time.Sleep(config.interval)
	}
}