-
Notifications
You must be signed in to change notification settings - Fork 0
/
oswdata.py
executable file
·402 lines (327 loc) · 13.7 KB
/
oswdata.py
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
400
401
402
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = "1.0.0.170928"
"""
NAME
oswdata.py
DESCRIPTION
OSW data related methods.
NOTES
MODIFIED (MM/DD/YY)
luhwang 09/28/17 - created the initial OSWData class template
"""
import os
import sys
import re
import pandas as pd
"""Global Variables"""
"""Runtime Attributes"""
# -----------------------------------------------------------------------
# OSWData class
class OSWData(object):
"""OSWData related methods
Parameters
----------
path : string file path, default None
path of the osw archive file
category : string, default None
type of the osw data, e.g. meminfo
Examples
--------
>>> path='/crash/cores/26855880/cffar13120402/domu/1506166186/var/log/ops/oswatcher/archive/oswmeminfo/cffar13120402.usdc2.oraclecloud.com_meminfo_17.09.23.0600.dat'
>>> osw= OSWData(path=path,category='meminfo')
>>> osw.df
>>> osw.oswmem_free_memory(min=100,category='meminfo')
>>> False
index, timestamp, category, sub_category, key, value
0, Sat Sep 23 06:01:00 UTC 2017, meminfo, '', MemFree, 127332
See also
--------
"""
def __init__(self,path=None,category=None):
"""OSWData class, init"""
if path is None:
raise ValueError("The 'path' arg is invalid!")
if category is None:
raise ValueError("The 'category' arg is invalid!")
self.path = path
self.category = category
if self.category == "top":
do_topfile(path=self.path,category=self.category)
else:
osw_dict = _split_by_block(path=self.path,category=self.category)
osw_dict = _split_by_line(osw_dict)
osw_dict = _split_by_keypair(osw_dict)
self.df = _listofdict_to_df(osw_dict)
def __del__(self):
pass
def _split_by_block(self, path=None,category='meminfo'):
"""split by block
extract 1st level data (timestamp, and raw data of block) to dict
Parameters
----------
path : string file path, default None
path of the osw archive file
Returns
-------
block_dict : list of dict
format:
[{'timestamp':timestamp , 'category': category, 'sub_category': sub_category,'key': key,'value': value,'key_value2': key_value2,}
{'timestamp':timestamp , 'category': category, 'sub_category': sub_category,'key': key,'value': value,}]
more: key_value1,key_value2
Icmp:
222595 ICMP messages received
6 input ICMP message failed.
ICMP input histogram:
destination unreachable: 9191
timeout in transit: 7
echo requests: 213378
echo replies: 19
--> category -> netstat
sub_category: Icmp
key_value1: ICMP input histogram:
key_value2:
key: destination unreachable:
value: 9191
Example of the output:
[{ 'category': '',
'sub_category': '',
'timestamp': Sat Sep 23 06:00:30 UTC 2017',
'key': 'raw_block',
'value': '\nMemTotal: 1486148 kB\nMemFree: 78376 kB\nBuffers: 2376 kB\n
},
{ 'category': '',
'sub_category': '',
'timestamp': 'Sat Sep 23 06:01:00 UTC 2017',
'key': 'raw_block',
'value': '\nMemTotal: 1486148 kB\nMemFree: 127332 kB\nBuffers: 2500 kB\n
}
]
"""
with open(path, "r") as f:
text = f.read()
lst = re.split('zzz', text, flags=re.DOTALL) # to list based on time
lst = [x for x in lst if x] # remove empty strings
"""
Python 2.x
lst = map(lambda v: re.split('(\s\W{1,}\w{3}\s\w{3}\s\w{2,3}\s\d{2}:\d{2}:\d{2}\s\w{3}\s\d{4})', v), lst)
"""
lst = [re.split('(\s\W{1,}\w{3}\s\w{3}\s\w{2,3}\s\d{2}:\d{2}:\d{2}\s\w{3}\s\d{4})', v) for v in lst]
block_dict = []
for v in lst:
timestamp=v[1]
value=v[2]
_d = [{'timestamp':timestamp,
'category': category,
'sub_category': '',
'key': 'raw_block',
'value': value}]
block_dict.extend(_d)
return block_dict
def _split_by_line(self, osw_dict={}):
"""split by line
extract 2nd level data to dict as key:value pair
Parameters
----------
osw_dict : dict, default {}
the output from _split_by_block. value is multiline contents from osw data file.
Returns
-------
line_dict : list of dict
format:
[{'timestamp':timestamp , 'category': category, 'sub_category': sub_category,'key': key,'value': value,}
{'timestamp':timestamp , 'category': category, 'sub_category': sub_category,'key': key,'value': value,}]
Example of the output:
[{ 'category': '',
'sub_category': '',
'timestamp': 'Sat Sep 23 06:00:30 UTC 2017',
'key': 'raw_line',
'value': 'MemTotal: 1486148 kB'
}
{' category': '',
'sub_category': '',
'timestamp': 'Sat Sep 23 06:00:30 UTC 2017',
'key': 'raw_line',
'value': 'MemFree: 78376 kB'
}
]
"""
lst = osw_dict
line_dict = []
for d in lst:
if d['key'] == 'raw_block':
line_lst = re.split(r'\n',d['value'])
for liner in line_lst:
_d = [{'timestamp':d['timestamp'] ,
'category': d['category'],
'sub_category': d['sub_category'],
'key': 'raw_line',
'value': liner}]
line_dict.extend(_d)
return line_dict
def _split_by_keypair(self, osw_dict={}):
"""split by keypair element within a line
extract line level data to dict as key:value pair
Parameters
----------
osw_dict : dict, default {}
the output from _split_by_block. value is multiline contents from osw data file.
Returns
-------
keypair_dict : list of dict
format:
[{'timestamp':timestamp , 'category': category, 'sub_category': sub_category,'key': key,'value': value,}
{'timestamp':timestamp , 'category': category, 'sub_category': sub_category,'key': key,'value': value,}]
Example of the output:
[{ 'category': '',
'sub_category': '',
'timestamp': 'Sat Sep 23 06:00:30 UTC 2017',
'key': 'MemTotal_kB',
'value': '1486148'
}
{ 'category': '',
'sub_category': '',
'timestamp': 'Sat Sep 23 06:00:30 UTC 2017',
'key': 'MemFree_kB',
'value': '78376'
}
]
"""
lst = osw_dict
keypair_dict = []
for d in lst:
if d['key'] == 'raw_line':
keypair_lst = re.split(r',',d['value'])
for k,v in keypair_lst:
_d = [{'timestamp':d['timestamp'] ,
'category': d['category'],
'sub_category': d['sub_category'],
'key': k,
'value': v}]
keypair_dict.extend(_d)
return keypair_dict
def _listofdict_to_df(self, osw_dict=None):
"""Read dict into a DataFrame.
Parameters
----------
osw_dict : dict, default None
the output from _split_by_keypair.
Returns
-------
frame : DataFrame
"""
if type(osw_dict) is not dict:
raise ValueError("The 'osw_dict' arg is invalid!")
frame = pd.DataFrame.from_dict(osw_dict, orient='columns')
return frame
def string_to_keypair(self, data):
"""Read dict into a DataFrame.
Parameters
----------
data : string
e.g. 'Quick ack mode was activated 39377 time'
'TCPHystartDelayDetect: 157'
Returns
-------
keypair_lst : list
[[k,v],[k,v],[k,v],[k,v],[k,v]]
e.g.
[[Quick ack mode was activated time,39377],[TCPHystartDelayDetect,157]]
"""
return keypair_lst
def oswmem_free_memory(self,min=0):
"""analyze oswmem free memory
check if free mmemory <= min memory
Parameters
----------
min : num, default 0
free memeory
Returns
-------
result : boolean. False means free mmemory <= min memory.
"""
result = self.df[self.df['free mmemory'] > min].all
return result
def do_topfile(self, path=None,category='top'):
"""Output oswtop file as a Data Frame
Parameters
----------
path : string file path, default None
path of the oswtop file
Returns
-------
data: DataFrame
"""
s = StringIO()
with open(self.path) as f:
for line in f:
if line.startswith('top') or line.startswith('Cpu') or \
line.startswith('Tasks') or line.startswith('Mem') or \
line.startswith('Swap'):
s.write(line)
s.seek(0)
oswdata=pd.read_csv(file, comment="L", sep="\n", names='a')
raw=oswdata[oswdata.iloc[:,0].str.startswith("top")].dropna(axis=1)
raw['a']=raw['a'].str.replace('days, ','days ')
raw['a']=raw['a'].str.replace('top - ','')
raw['a']=raw['a'].str.replace(' up ',',')
raw['a']=raw['a'].str.replace('users','')
raw['a']=raw['a'].str.replace('load average: ','')
top=raw['a'].str.split(',', 5, expand=True).rename(columns={0:'ts', 1:'uptime', 2:'users', 3:'load1', 4:'load10', 5:'load15'})
top=top.reset_index().rename(columns={'index': 'pos'})
data=top.copy()
#print top
raw=oswdata[oswdata.iloc[:,0].str.startswith("Tasks")].dropna(axis=1)
raw['a']=raw['a'].str.replace('Tasks:','')
raw['a']=raw['a'].str.replace(' total,',',')
raw['a']=raw['a'].str.replace(' running,',',')
raw['a']=raw['a'].str.replace(' sleeping,',',')
raw['a']=raw['a'].str.replace(' stopped,',',')
raw['a']=raw['a'].str.replace(' zombie','')
task=raw['a'].str.split(',', 4, expand=True).rename(columns={0:'tot', 1:'run', 2:'sleep', 3:'stop', 4:'zom'})
task=task.reset_index().rename(columns={'index': 'pos'})
task['pos']=task['pos'].apply(lambda d: int(d)-1)
data=pd.merge(data,task,how='outer',on='pos')
#print task
raw=oswdata[oswdata.iloc[:,0].str.startswith("Cpu")].dropna(axis=1)
raw['a']=raw['a'].str.replace('Cpu\(s\):','')
raw['a']=raw['a'].str.replace('us,',',')
raw['a']=raw['a'].str.replace('sy,',',')
raw['a']=raw['a'].str.replace('ni,',',')
raw['a']=raw['a'].str.replace('id,',',')
raw['a']=raw['a'].str.replace('wa,',',')
raw['a']=raw['a'].str.replace('hi,',',')
raw['a']=raw['a'].str.replace('si,',',')
raw['a']=raw['a'].str.replace('st','')
cpu=raw['a'].str.split(',', 7, expand=True).rename(columns={0:'us', 1:'sy', 2:'ni', 3:'id', 4:'wa', 5:'hi', 6:'si', 7:'st'})
cpu=cpu.reset_index().rename(columns={'index': 'pos'})
cpu['pos']=cpu['pos'].apply(lambda d: int(d)-2)
data=pd.merge(data,cpu,how='outer',on='pos')
#print cpu
raw=oswdata[oswdata.iloc[:,0].str.startswith("Mem:")].dropna(axis=1)
raw['a']=raw['a'].str.replace('Mem:','')
raw['a']=raw['a'].str.replace('k total,',',')
raw['a']=raw['a'].str.replace('k used,',',')
raw['a']=raw['a'].str.replace('k free,',',')
raw['a']=raw['a'].str.replace('k buffers','')
mem=raw['a'].str.split(',', 3, expand=True).rename(columns={0:'Memtot', 1:'Memused', 2:'Memfree', 3:'Membuf'})
mem=mem.reset_index().rename(columns={'index': 'pos'})
mem['pos']=mem['pos'].apply(lambda d: int(d)-3)
data=pd.merge(data,mem,how='outer',on='pos')
#print mem
raw=oswdata[oswdata.iloc[:,0].str.startswith("Swap:")].dropna(axis=1)
raw['a']=raw['a'].str.replace('Swap:','')
raw['a']=raw['a'].str.replace('k total,',',')
raw['a']=raw['a'].str.replace('k used,',',')
raw['a']=raw['a'].str.replace('k free,',',')
raw['a']=raw['a'].str.replace('k cached','')
swap=raw['a'].str.split(',', 3, expand=True).rename(columns={0:'Swaptot', 1:'Swapused', 2:'Swapfree', 3:'cache'})
swap=swap.reset_index().rename(columns={'index': 'pos'})
swap['pos']=swap['pos'].apply(lambda d: int(d)-4)
#print swap
data=pd.merge(data,swap,how='outer',on='pos')
print(data)
return data
#
# ----------------------------------------------------------------------
# Add plotting methods to OSWData