16.08.2019 python

vmstat Visualizer

Prerequisites

This is a Python script to convert the output from vmstat into nifty graphs. It needs matplotlib and numpy, install it with:

$ python3 -m pip install numpy matplotlib

Usage

$ vmstat -n -w -S m 1 | tee ~/$HOSTNAME.vmstat.dat
$ vmstatviz.py ~/$HOSTNAME.vmstat.dat

You can also use the functions to customize the output. With the function custom, you can even build your own vmstat related graph.

Have fun \o/

Example output

CPU Load Graph

  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
#!/usr/bin/env python3
import itertools
import re
import sys
import matplotlib.pyplot as plt
import numpy as np
'''
MIT License

Copyright (c) 2019 Domeniko Gentner contact@tuxstash.de

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''


'''
   The official vmstat data structure is also used as keys for the internal dictionary:
   ------------ PROC -------------------
   r       : Processes running
   b       : Processes waiting for io
   ------------ MEM --------------------
   swpd    : virtual memory used
   free    : memory idle
   buff    : memory used as buffer
   cache   : memory used as cache
   ------------ SWAP -------------------
   si      : memory swapped from disk
   so      : memory swapped to disk
   ------------- IO --------------------
   bi      : data read from storage
   bo      : data written to storage
   ------------ SYS --------------------
   in      : interrupts/second
   cs      : context switches per second
   ------------ CPU --------------------
   us      : cpu executing user code
   sy      : cpu executing kernel code
   id      : cpu idle time

   These extra keys have also been added:
   cpu_load: us + sy to reflect the total load
'''

class VmStatVisualizer:

    def __init__(self):
        self.__vmstatData = dict()
        pass

    def parse(self, filename):
        """
        Parses the output generated by vmstat. Please make sure to have only one header
        printed by vmstats, using `-n` as parameter. The recommended usage for vmstat:
        `vmstat -n -w -S m 1`
        This outputs one line per second. This tool does not assume time, it simply treats
        the x-axis as time line.
        You supply the title for the axis, so you can alter it however you want.
        Please do not alter the vmstat default output with sed or awk.
        """
        f = open(filename, "r")
        r     = list()
        b     = list()
        swpd  = list()
        free  = list()
        buff  = list()
        cache = list()
        si    = list()
        so    = list()
        bi    = list()
        bo    = list()
        sysin = list()
        cs    = list()
        us    = list()
        sy    = list()
        id    = list()
        cpuLoad = list()

        for line in itertools.islice(f, 2, None):
            line = line.strip()
            line_data = re.split('\\s+', line)
            # proc
            r.append(int(line_data[0]))
            b.append(int(line_data[1]))
            # mem
            swpd.append(int(line_data[2]))
            free.append(int(line_data[3]))
            buff.append(int(line_data[4]))
            cache.append(int(line_data[5]))
            # swap
            si.append(int(line_data[6]))
            so.append(int(line_data[7]))
            # io
            bi.append(int(line_data[8]))
            bo.append(int(line_data[9]))
            # sys
            sysin.append(int(line_data[10]))
            cs.append(int(line_data[11]))
            # cpu
            us.append(int(line_data[12]))
            sy.append(int(line_data[13]))
            id.append(int(line_data[14]))
            cpuLoad.append(int(line_data[12]) + int(line_data[13]))

        self.__vmstatData['r'] = r
        self.__vmstatData['b'] = b
        self.__vmstatData['swpd'] = swpd
        self.__vmstatData['free'] = free
        self.__vmstatData['buff'] = buff
        self.__vmstatData['cache']= cache
        self.__vmstatData['si'] = so
        self.__vmstatData['so'] = si
        self.__vmstatData['bi'] = bi
        self.__vmstatData['bo'] = bo
        self.__vmstatData['sys'] = sysin
        self.__vmstatData['cs'] = cs
        self.__vmstatData['us'] = us
        self.__vmstatData['sy'] = sy
        self.__vmstatData['id'] = id
        self.__vmstatData['cpu_load'] = cpuLoad

    def custom(self, dataNames: list, colors: list, imgName, plotTitle, yLabel, xLabel):
        yMax = int()
        xMax = int()
        i = 0

        if (len(dataNames) != len(colors)):
            print("ERROR: Number of supplied colors does not match number of names. Exit.")
            exit(1)

        plt.figure()
        for name in dataNames:
            if yMax <= max(self.__vmstatData[name]):
                yMax = max(self.__vmstatData[name])

            if xMax <= max(self.__vmstatData[name]):
                xMax = max(self.__vmstatData[name])

            plt.plot(range(0, len(self.__vmstatData[name])), self.__vmstatData[name], colors[i])
            i = i+1

        # Image
        plt.gca().legend((dataNames))
        plt.yticks(np.arange(0, yMax, step=yMax/10))
        plt.axis(ymin=0, ymax=yMax, xmin=0, xmax=len(self.__vmstatData[dataNames[0]]))
        plt.title(plotTitle)
        plt.ylabel(yLabel)
        plt.xlabel(xLabel)
        plt.savefig(format="png", orientation="landscape", quality="95", fname=imgName)

    def all(self, directory):
        self.draw_r_b(directory+"r_b.png", "Processes", "Proc", "time in s")
        self.draw_free_memory(directory+"free_memory.png", "Memory load", "Memory", "time in s")
        self.draw_swap_activity(directory+"swap_activity.png", "Swap Activity", "Swap", "time in s")
        self.draw_bi_bo(directory+"bi_bo.png", "Input/Output", "Load", "time in s")
        self.draw_us_sy_id(directory+"us_sy_id.png", "CPU Load", "Load", "time in s")
        self.draw_cpu_load(directory+"cpu_load.png", "CPU Load", "Load", "time in s")


    def draw_r_b(self, imgName, plotTitle, yLabel, xLabel):
        yMax   = max(self.__vmstatData['r']+self.__vmstatData['b'])

        plt.figure()
        plt.yticks(np.arange(0, yMax, step=yMax/10))
        plt.plot(range(0, len(self.__vmstatData['r'])), self.__vmstatData['r'], 'g')
        plt.plot(range(0, len(self.__vmstatData['b'])), self.__vmstatData['b'], 'b')
        plt.gca().legend(('r', 'b'))
        plt.axis(ymin=0, ymax=yMax, xmin=0, xmax=len(self.__vmstatData['r']))
        plt.title(plotTitle)
        plt.ylabel(yLabel)
        plt.xlabel(xLabel)
        plt.savefig(format="png", orientation="landscape", quality="95", fname=imgName)

    def draw_free_memory(self, imgName, plotTitle, yLabel, xLabel):
        yMax = (
            max(self.__vmstatData['free'])+
            max(self.__vmstatData['buff'])+
            max(self.__vmstatData['cache'])
        )
        plt.figure()
        plt.yticks(np.arange(0, yMax, step=yMax/10))
        plt.plot(range(0, len(self.__vmstatData['free'])), self.__vmstatData['free'], 'g')
        plt.plot(range(0, len(self.__vmstatData['buff'])), self.__vmstatData['buff'], 'r')
        plt.plot(range(0, len(self.__vmstatData['cache'])), self.__vmstatData['cache'], 'c')
        plt.gca().legend(('free', 'buff', 'cache'))
        plt.axis(ymin=0, ymax=yMax, xmin=0, xmax=len(self.__vmstatData['free']))
        plt.title(plotTitle)
        plt.ylabel(yLabel)
        plt.xlabel(xLabel)
        plt.savefig(format="png", orientation="landscape", quality="95", fname=imgName)


    def draw_swap_activity(self, imgName, plotTitle, yLabel, xLabel):
        yMax = (
            max(self.__vmstatData['si']) +
            max(self.__vmstatData['so'])
        )
        plt.figure()
        plt.yticks(np.arange(0, yMax, step=yMax/10))
        plt.plot(range(0, len(self.__vmstatData['si'])), self.__vmstatData['si'], 'g')
        plt.plot(range(0, len(self.__vmstatData['so'])), self.__vmstatData['so'], 'b')
        plt.gca().legend(('ram <- disk', 'ram -> disk'))
        plt.axis(ymin=0, ymax=yMax, xmin=0, xmax=len(self.__vmstatData['r']))
        plt.title(plotTitle)
        plt.ylabel(yLabel)
        plt.xlabel(xLabel)
        plt.savefig(format="png", orientation="landscape", quality="95", fname=imgName)


    def draw_bi_bo(self, imgName, plotTitle, yLabel, xLabel):
        yMax = (
            max(self.__vmstatData['bi']) +
            max(self.__vmstatData['bo'])
        )
        plt.figure()
        plt.yticks(np.arange(0, yMax, step=yMax/10))
        plt.plot(range(0, len(self.__vmstatData['bi'])), self.__vmstatData['bi'], 'g')
        plt.plot(range(0, len(self.__vmstatData['bo'])), self.__vmstatData['bo'], 'b')
        plt.gca().legend(('read from disk', 'written to disk'))
        plt.axis(ymin=0, ymax=yMax, xmin=0, xmax=len(self.__vmstatData['r']))
        plt.title(plotTitle)
        plt.ylabel(yLabel)
        plt.xlabel(xLabel)
        plt.savefig(format="png", orientation="landscape", quality="95", fname=imgName)


    def draw_us_sy_id(self, imgName, plotTitle, yLabel, xLabel):
        yMax = (
            max(self.__vmstatData['us']) +
            max(self.__vmstatData['sy']) +
            max(self.__vmstatData['id'])
        )
        plt.figure()
        plt.yticks(np.arange(0, yMax, step=yMax/10))
        plt.plot(range(0, len(self.__vmstatData['us'])), self.__vmstatData['us'], 'r')
        plt.plot(range(0, len(self.__vmstatData['sy'])), self.__vmstatData['sy'], 'g')
        plt.plot(range(0, len(self.__vmstatData['id'])), self.__vmstatData['id'], 'b')
        plt.gca().legend(('user cpu time', 'system cpu time', 'idle cpu time'))
        plt.axis(ymin=0, ymax=yMax, xmin=0, xmax=len(self.__vmstatData['id']))
        plt.title(plotTitle)
        plt.ylabel(yLabel)
        plt.xlabel(xLabel)
        plt.savefig(format="png", orientation="landscape", quality="95", fname=imgName)


    def draw_cpu_load(self, imgName, plotTitle, yLabel, xLabel):
        yMax   = 110
        datLen = len(self.__vmstatData['cpu_load'])

        plt.figure()
        plt.yticks(np.arange(0, yMax, step=10))
        plt.plot(range(0, datLen), self.__vmstatData['cpu_load'], 'c')
        plt.axis(ymin=0, ymax=yMax, xmin=0, xmax=datLen)
        plt.title(plotTitle)
        plt.ylabel(yLabel)
        plt.xlabel(xLabel)
        plt.savefig(format="png", orientation="landscape", quality="95", fname=imgName)



if __name__ == "__main__":
   v1 = VmStatVisualizer()
   v1.parse(sys.argv[1])
   v1.all("./")
   v1.custom(['cpu_load', 'free', 'buff'], ['b', 'g', 'r'],
            "./img/custom_example.png", "Mixed", "Test", "Time in ms")

Link to the author's twitter Link to the authors ko-fi page

comments

Characters: 0/1000

gravatar portrait

 Pinned by contact@tuxstash.de

Come join the discussion and write something nice. You will have to confirm your comment by mail, so make sure it is legit and not a throwaway. Only the name part of it will be displayed, so don't worry about spam. If it does not show up after confirming it, it may be considered spam, but I curate them manually, so don't worry. Please read the privacy statement for more.