-
Notifications
You must be signed in to change notification settings - Fork 2
/
sss.py
3071 lines (2558 loc) · 130 KB
/
sss.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#Copyright (c) 2015, 2020. All rights reserved.
#
#This program is free software; you can redistribute it and/or modify
#it under the Apache License 2.0 License.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
#Author List
# name email github blog
# deep [email protected] https://github.com/deep011 https://deep011.github.io/
import time
import datetime
import getopt
import sys
import socket
import os
type_linux = "linux"
type_mysql = "mysql"
type_redis = "redis"
type_pika = "pika"
type_memcached = "memcached"
type_twemproxies = "twemproxies"
support_types=[type_linux,type_mysql,type_redis,type_pika,type_memcached,type_twemproxies]
service_type=type_linux
output_type_screen = 0 #Out put the status to the screen.
output_type_file = 1 #Out put the status to the files.
output_type_open_falcon = 2 #Out put the status to the open-falcon.
output_type = output_type_screen #default output is the screen.
output_file_name = ""
output_file = None
output_file_by_day = 0
date_format = "%Y-%m-%d"
time_format = "%H:%M:%S"
current_day = datetime.datetime.now().strftime(date_format)
open_falcon = "http://127.0.0.1:22230/v1/push"
speed_calculate_by_remote_monitor_system = 0
host="127.0.0.1"
port=3306
user="root"
password=""
socket_file=""
service_port_setted_by_human=0
service_port=port
hostname=socket.gethostname()
status_collect_interval=1 #second, default is one second
status_collect_times=-1 #default is forever
#column_format = '%-*s'
column_format = '%*s'
all_section=0
sections_customized=0
segmentation_line_len = 40
####### Util #######
def byte2readable(bytes):
bytes_float = float(bytes)
if bytes_float > -1024.0 and bytes_float < 1024.0:
if (str(bytes).find(".") >= 0):
return "%3.1f"%bytes_float
else:
return str(bytes)
else:
bytes_float /= 1024.0
for count in ['K', 'M', 'G']:
if bytes_float > -1024.0 and bytes_float < 1024.0:
return "%3.1f%s" % (bytes_float, count)
bytes_float /= 1024.0
return "%3.1f%s" % (bytes_float, 'T')
def num2readable(number):
number_float = float(number)
if number_float > -1000.0 and number_float < 1000.0:
if (str(number).find(".") >= 0):
return "%3.2f"%number_float
else:
return str(number)
else:
number_float /= 1000.0
for count in ['k', 'm', 'g']:
if number_float > -1000.0 and number_float < 1000.0:
return "%3.2f%s" % (number_float, count)
number_float /= 1000.0
return "%3.2f%s" % (number_float, 't')
def microsecond_differ_by_datetime(datetime_new, datetime_old):
datetime_differ = datetime_new - datetime_old
return datetime_differ.days*24*3600*1000000 + datetime_differ.seconds*1000000 + datetime_differ.microseconds
def get_proc_pid_from_pid_file(pid_file):
pidfile_fd = open(pid_file, 'r')
process_pid = int(pidfile_fd.read(10))
pidfile_fd.close()
return process_pid
log_level_debug=0
log_level_info=1
log_level_error=2
log_level=log_level_info
if log_level == log_level_debug:
import traceback
def get_exception_message(function_name, line_no, exception):
exception_header = function_name + ":" + str(line_no) + " Exception: "
if log_level == log_level_debug:
exception_header += traceback.format_exc()
elif log_level == log_level_info:
exception_header += repr(exception)
else:
exception_header += str(exception)
return exception_header
def get_falcon_metric_name_header(section_name):
return service_type + "." + section_name
def get_falcon_tags_string(section_type):
tags = ""
if section_type == type_linux:
tags += "linux"
else:
tags += "port=" + str(service_port)
return tags
def append_server_alive_condition_to_falcon_json(server, status_json, server_alive):
tags = get_falcon_tags_string(service_type)
metric_name = get_falcon_metric_name_header("alive")
status_json.append({
"endpoint": hostname,
"metric": metric_name,
"timestamp": int(server.getCurrentTimeStamp()),
"step": status_collect_interval,
"value": float(server_alive),
"counterType": "GAUGE",
"tags": tags,
},)
return
errlog_file_name=""
def errlog(server, errstr, need_check_server_alive):
if need_check_server_alive and server.check_alive != None:
try:
server_alive = server.check_alive(server)
if output_type == output_type_open_falcon:
status_json = []
append_server_alive_condition_to_falcon_json(server, status_json, server_alive)
output(server, json.dumps(status_json))
except Exception, e:
errlog(server, get_exception_message(sys._getframe().f_code.co_name,sys._getframe().f_lineno, e), False)
errstr += " " + "(" + service_type + " alive: " + str(server_alive) + ")"
if len(errlog_file_name) == 0:
print server.getCurrentTimeFormattedString() + " " + errstr
else:
errlog_file = open(errlog_file_name, 'a', 0)
errlog_file.write(server.getCurrentDateTimeFormattedString() + " " + errstr + "\n")
errlog_file.close()
return
def output(server, content):
if output_type == output_type_screen:
print content
elif output_type == output_type_file:
output_file.write(content + '\n')
elif output_type == output_type_open_falcon:
r = requests.post(open_falcon, data=content)
if r.text != "success":
errlog(server, "ERROR: "+r.text, False)
else:
errlog(server, r.text, False)
else:
return
return
def separate_output_file_if_needed(server):
if (output_file_by_day == 1):
today = server.current_time.strftime(date_format)
global current_day
global output_file
if current_day != today:
current_day = today
if (output_file.closed == False):
output_file.close()
output_file = open(output_file_name+'_'+current_day, 'a', 0)
return 1
return 0
####### Class StatusSection #######
class StatusSection:
def __init__(self, name, type, columns, status_get_functions, default_columns_name_show, instructions):
self.name = name
self.type = type
self.columns = columns #This section supported columns. This is a array of column.
self.status_get_functions = status_get_functions
self.default_columns_show = []
self.columns_show = [] #Columns to show that in the self.columns. This is a array of column.
self.instructions = instructions
if default_columns_name_show == None or len(default_columns_name_show) == 0:
self.default_columns_show = self.columns
elif len(default_columns_name_show) == 1 and default_columns_name_show[0] == ALL_COLUMNS:
self.default_columns_show = self.columns
else:
for column_name in default_columns_name_show:
for column in self.columns:
if (column_name == column.getName()):
self.default_columns_show.append(column)
if len(self.default_columns_show) != len(default_columns_name_show):
print "There are not supported columns name in the section initialization"
sys.exit(3)
def getName(self):
return self.name
def getType(self):
return self.type
def getColumns(self):
return self.columns
def getColumnsToShow(self):
return self.columns_show
def getInstructions(self):
return self.instructions
def setType(self, type):
self.type = type
return
def clearColumnsToShow(self):
self.columns_show = []
return
def isColumnAlreadyExistByName(self, column_name):
for column_in in self.columns:
if column_in.getName() == column_name:
return 1
return 0
def isColumnAlreadyExist(self, column):
return self.isColumnAlreadyExistByName(column.getName())
def addColumn(self, column):
if self.isColumnAlreadyExist(column) == 1:
return 0
self.columns.append(column)
return 1
def addColumnToShow(self,column_in):
for column_show in self.columns_show:
if (column_show.getName() == column_in.getName()):
return 0
for column in self.columns:
if (column.getName() == column_in.getName()):
self.columns_show.append(column)
return 1
return -1
def addColumnsToShow(self,columns):
for column_in in columns:
find = 0
for column in self.columns:
if column_in.getName() == column.getName():
find = 1
break
if find == 0:
return -1 #There are not supported columns in the columns_name
count = 0
for column_in in columns:
ret = self.addColumnToShow(column_in)
count += ret
if count == len(columns):
return 2 #All columns in the columns_name are added.
elif count > 0:
return 1 #Some columns are not added.
else:
return 0 #No column was added.
def addColumnToShowByName(self,column_name):
for column in self.columns_show:
if (column_name == column.getName()):
return 0
for column in self.columns:
if (column_name == column.getName()):
self.columns_show.append(column)
return 1
return -1
def addColumnsToShowByName(self,columns_name):
#Check all the columns name are corrent?
for column_name in columns_name:
find = 0
for column in self.columns:
if (column_name == column.getName()):
find = 1
break
if find == 0:
return -1 #There are not supported columns in the columns_name.
count = 0
for column_name in columns_name:
ret = self.addColumnToShowByName(column_name)
count += ret
if count == len(columns_name):
return 2 #All columns in the columns_name are added.
elif count > 0:
return 1 #Some columns are not added.
else:
return 0 #No column was added.
def addColumnsDefaultToShow(self):
return self.addColumnsToShow(self.default_columns_show)
def addColumnsAllToShow(self):
return self.addColumnsToShow(self.columns)
def removeColumnFromShow(self,column_out):
for column_show in self.columns_show:
if (column_show.getName() == column_out.getName()):
self.columns_show.remove(column_show)
return 1
for column in self.columns:
if (column.getName() == column_out.getName()):
return 0
return -1
def removeColumnsFromShow(self,columns):
for column_out in columns:
find = 0
for column in self.columns:
if column_out.getName() == column.getName():
find = 1
break
if find == 0:
return -1 #There are not supported columns in the columns_name
count = 0
for column_out in columns:
ret = self.removeColumnFromShow(column_out)
count += ret
if count == len(columns):
return 2 #All columns in the columns_name are added.
elif count > 0:
return 1 #Some columns are not added.
else:
return 0 #No column was added.
def removeColumnFromShowByName(self,column_name):
find = 0
for column in self.columns:
if (column_name == column.getName()):
find = 1
if find == 0:
return -1
for column in self.columns_show:
if (column_name == column.getName()):
self.columns_show.remove(column)
return 1
return 0
def removeColumnsFromShowByName(self,columns_name):
#Check all the columns name are corrent?
for column_name in columns_name:
find = 0
for column in self.columns:
if (column_name == column.getName()):
find = 1
break
if find == 0:
return -1 #There are not supported columns in the columns_name.
count = 0
for column_name in columns_name:
ret = self.removeColumnFromShowByName(column_name)
count += ret
if count == len(columns_name):
return 2 #All columns in the columns_name are removed.
elif count > 0:
return 1 #Some columns are not removed.
else:
return 0 #No column was removed.
def removeColumnsDefaultFromShow(self):
return self.removeColumnsFromShow(self.default_columns_show)
def removeColumnsAllFromShow(self):
return self.removeColumnsFromShow(self.columns)
def getHeader(self):
len_total = 0
for column in self.columns_show:
len_total += column.getWidth()
if (len(self.name) == 0):
return ' '*len_total
len_half_left = (len_total-len(self.name))/2
len_half_right = len_half_left
if ((len_total-len(self.name))%2 == 1):
len_half_right += 1
return '-'*len_half_left+self.name+'-'*len_half_right
####### Class StatusColumn #######
column_flags_none=int('00000000',2) # None flags. Default the fields are numbers.
column_flags_speed=int('00000001',2) # The column is shown as speed.
column_flags_bytes=int('00000010',2) # The column is shown as bytes.
column_flags_string=int('00000100',2) # The fields are strings, otherwise are numbers; string can't be column_flags_speed.
column_flags_ratio=int('00001000',2) # The column is shown as ratio.
column_flags_speed_then_ratio=int('00010000',2) # The column is calculated by speed and then by ratio. Like (a_time2 - a_time1)/(b_time2 - b_time2)
class StatusColumn:
def __init__(self, name, detail_name, blanks, flags, field_handler, fields, instructions):
self.name = name
self.detail_name = detail_name
self.flags = flags
self.field_handler = field_handler
self.fields = fields
self.instructions = instructions
self.value_old = 0
self.obj_old = None
if (blanks > 0): # Blanks is bigger than zero means we really want the blanks.
self.width = len(name) + blanks
elif (blanks == 0): # Blanks is zero means the default blanks count between the columns, default is 2.
self.width = len(name) + 1
if (self.width < 8):
self.width = 8
else:
self.width = len(name) + 2
def getName(self):
return self.name
def getDetailName(self):
return self.detail_name
def getWidth(self):
return self.width
def getFlags(self):
return self.flags
def getFields(self):
return self.fields
def getInstructions(self):
return self.instructions
def getValueOld(self):
return self.value_old
def getObjOld(self):
return self.obj_old
def getHeader(self):
return column_format % (self.getWidth(), self.getName())
def getValue(self, column, status, server):
value = column.field_handler(column, status, server)
if column.getFlags() & column_flags_speed:
if speed_calculate_by_remote_monitor_system == 1:
return value
interval_time = microsecond_differ_by_datetime(server.current_time, server.last_time)
if (interval_time <= 0):
interval_time = 1
value_num = float(value)
difference_value = value_num - column.getValueOld()
column.setValueOld(value_num)
rate = float(difference_value) * 1000000 / float(interval_time)
value_str = "%3.1f" % rate
return value_str
return value
def setValueOld(self, value):
self.value_old = value
def setObjOld(self, obj):
self.obj_old = obj
## interval_time is microsecond
## The caller need to catch the exception
def field_handler_common(column, status, server):
if (column.getFlags()&column_flags_ratio):
fields = column.getFields()
return "%.3f"%(float(status[fields[0]])*100/float(status[fields[1]]))
value_num = 0
value_str = ''
for field in column.getFields():
if (column.getFlags()&column_flags_string):
if (len(value_str) == 0):
value_str = str(status[field])
else:
value_str += ',' + str(status[field])
else:
value_num += long(status[field])
if (column.getFlags()&column_flags_string == 0):
value_str = str(value_num)
return value_str
def get_status_line(server):
line = ""
for section in server.sections_to_show:
if server.err > 0:
break
for column in section.getColumnsToShow():
if server.err > 0:
break
try:
value = column.getValue(column,server.status,server)
if (column.getFlags()&column_flags_bytes):
value = byte2readable(value)
elif (column.getFlags()&column_flags_string == 0 and column.getFlags()&column_flags_ratio == 0):
value = num2readable(value)
line += column_format % (column.getWidth(),value)
except Exception, e:
server.err = 1
server.errmsg = get_exception_message(sys._getframe().f_code.co_name,sys._getframe().f_lineno, e)
line += '|'
if server.err > 0:
return None
return line
def get_status_falcon_json(server):
status_json = []
for section in server.sections_to_show:
if server.err > 0:
break
tags = get_falcon_tags_string(section.getType())
metric_name_header = get_falcon_metric_name_header(section.getName())
for column in section.getColumnsToShow():
if server.err > 0:
break
try:
if column.getFlags()&column_flags_string:
continue
if speed_calculate_by_remote_monitor_system == 1 and column.getFlags()&column_flags_speed_then_ratio:
continue
counterType = "GAUGE"
if speed_calculate_by_remote_monitor_system == 1 and column.getFlags()&column_flags_speed:
counterType = "COUNTER"
metric_name = metric_name_header
if len(column.getDetailName()) == 0:
metric_name += "." + column.getName()
else:
metric_name += "." + column.getDetailName()
status_json.append({
"endpoint": hostname,
"metric": metric_name,
"timestamp": int(server.getCurrentTimeStamp()),
"step": status_collect_interval,
"value": float(column.getValue(column,server.status,server)),
"counterType": counterType,
"tags": tags,
},)
except Exception, e:
server.err = 1
server.errmsg = get_exception_message(sys._getframe().f_code.co_name,sys._getframe().f_lineno, e)
if (server.err > 0):
return None
# No errors means server is alive.
append_server_alive_condition_to_falcon_json(server, status_json, 1)
return json.dumps(status_json)
####### Common #######
ALL_COLUMNS="all_columns"
def getSupportedServiceTypesName():
names = ''
count = len(support_types)
for type in support_types:
names += type
count -= 1
if (count >= 1):
names += ","
return names
def get_sections_header(sections):
header = ''
for section in sections:
header += section.getHeader()
header += ' '
return header
def get_columns_header(sections):
header = ''
for section in sections:
for column in section.getColumnsToShow():
header += column.getHeader()
header += '|'
return header
def get_section_instructions_old(section):
segmentation_line = "-" * segmentation_line_len
instructions = "Section| " + section.getName() + " : " + section.getInstructions()
instructions += "\n" + segmentation_line
columns = section.getColumns()
for column in columns:
instructions += "\n"
instructions += "Column | " + column.getName() + " : " + column.getInstructions()
return instructions
def divide_one_line_to_multi_lines_by_max_length(line, max_len):
lines = []
if len(line) <= max_len:
lines.append(line)
return lines
line_part = ""
fields = line.split()
count = 0
for field in fields:
if (len(line_part)+1+len(field)) > max_len:
lines.append(line_part)
line_part = ""
if (count >= 1):
line_part += " "
line_part += field
count += 1
if (len(line_part.lstrip()) > 0):
lines.append(line_part)
return lines
def get_one_instructions(header, name, detail_name, instructions, max_line_len):
line = name
if len(detail_name) > 0:
line += "("+detail_name+")"
line += " : " + instructions
lines = divide_one_line_to_multi_lines_by_max_length(line, max_line_len)
one_instructions = header + "|" + lines[0]
for line in lines[1:]:
one_instructions += "\n"
one_instructions += " " * len(header) + "|" + line
return one_instructions
def get_section_instructions(section):
global sections_customized
max_line_len = 60
header_section = "Section"
header_column = "Column "
section_instructions = get_one_instructions(header_section, section.getName(), "", section.getInstructions(), max_line_len)
section_instructions += "\n" + "-"*segmentation_line_len + "\n"
if sections_customized == 0:
columns = section.getColumns()
else:
columns = section.getColumnsToShow()
count = len(columns)
for column in columns:
section_instructions += get_one_instructions(header_column, column.getName(), column.getDetailName(), column.getInstructions(), max_line_len)
count -= 1
if (count >= 1):
section_instructions += "\n" #+ "-"*segmentation_line_len + "\n"
return section_instructions
#section part maybe like "section_name" or "section_name[column1_name,column2_name,column3_name]"
def extract_section_name_and_columns_name_from_section_part(section_part):
if section_part.endswith("]") and section_part.find("[") >= 0:
index = section_part.index("[")
if (index == 0):
return None
columns_name=section_part[(index + 1):-1].split(",")
section_name = section_part[0:index]
return [section_name,columns_name]
else:
return [section_part]
#sections part maybe like "section1_name,section2_name[column1_name,column2_name,column3_name],section3_name[all_columns]"
def split_section_name_from_sections_part(sections_part):
sections_name = []
cursor=len(sections_part)
while cursor > 0:
if sections_part[cursor-1:cursor] == "]":
try:
idx = sections_part.rindex("[", 0, cursor)
except Exception, e:
return None
if sections_part.rfind(",", 0, idx) < 0:
sections_name.append(sections_part[0:cursor])
sections_name.reverse()
return sections_name
idx_sub = sections_part.rindex(",", 0, idx)
sections_name.append(sections_part[idx_sub+1:cursor])
cursor = idx_sub
continue
else:
if sections_part.rfind(",", 0, cursor) < 0:
sections_name.append(sections_part[0:cursor])
sections_name.reverse()
return sections_name
idx = sections_part.rindex(",", 0, cursor)
sections_name.append(sections_part[idx + 1:cursor])
cursor = idx
continue
return None
## The caller need to catch the exception
def field_handler_time(column, status, server):
return server.getCurrentTimeFormattedString()
time_section = StatusSection("time", "other", [
StatusColumn("Time", "", 5, column_flags_string, field_handler_time, [], "Show the time when the status display.")
],[],[ALL_COLUMNS],"os time")
def get_os_cpu_status(server, status):
file = open("/proc/stat", 'r')
line = file.readline()
file.close()
# cpu 1-user 2-nice 3-system 4-idle 5-iowait 6-irq 7-softirq
# cpu 628808 1642 61861 24978051 22640 349 3086 0
os_cpu_status = line.split()
status["os_cpu_usr"] = int(os_cpu_status[1]) + int(os_cpu_status[2])
status["os_cpu_sys"] = int(os_cpu_status[3]) + int(os_cpu_status[6]) + int(os_cpu_status[7])
status["os_cpu_idl"] = int(os_cpu_status[4])
status["os_cpu_iow"] = int(os_cpu_status[5])
status["os_cpu_total"] = status["os_cpu_usr"] + status["os_cpu_sys"] + status["os_cpu_idl"] + status["os_cpu_iow"]
return
## The caller need to catch the exception
def field_handler_os_cpu(column, status, server):
fields = column.getFields()
value = status[fields[0]]
total = status[fields[1]]
obj = column.getObjOld()
if (obj == None):
column.setObjOld([value,total])
return '0'
value_diff = value - obj[0]
total_diff = total - obj[1]
column.setObjOld([value, total])
return "%3.1f"%(float(value_diff)/float(total_diff) * 100)
os_cpu_section = StatusSection("os_cpu",type_linux,[
StatusColumn("usr", "user", 2, column_flags_string, field_handler_os_cpu, ["os_cpu_usr","os_cpu_total"], "Percentage of cpu user+nice time."),
StatusColumn("sys", "system", 2, column_flags_string, field_handler_os_cpu, ["os_cpu_sys","os_cpu_total"], "Percentage of cpu system+irq+softirq time."),
StatusColumn("idl", "idle", 3, column_flags_string, field_handler_os_cpu, ["os_cpu_idl","os_cpu_total"], "Percentage of cpu idle time."),
StatusColumn("iow", "iowait", 2, column_flags_string, field_handler_os_cpu, ["os_cpu_iow","os_cpu_total"], "Percentage of cpu iowait time.")
],[get_os_cpu_status],[ALL_COLUMNS],
"os cpu status, collect from /proc/stat file")
def get_os_load_status(server, status):
file = open("/proc/loadavg", 'r')
line = file.readline()
file.close()
os_load_status = line.split()
status["os_load_one"] = os_load_status[0]
status["os_load_five"] = os_load_status[1]
status["os_load_fifteen"] = os_load_status[2]
return
os_load_section = StatusSection("os_load",type_linux,[
StatusColumn("1m", "1minute", 4, column_flags_string, field_handler_common, ["os_load_one"], "One minute average active tasks."),
StatusColumn("5m", "5minute", 4, column_flags_string, field_handler_common, ["os_load_five"], "Five minute average active tasks."),
StatusColumn("15m", "15minute", 3, column_flags_string, field_handler_common, ["os_load_fifteen"], "Fifteen minute average active tasks.")
],[get_os_load_status],[ALL_COLUMNS],
"os cpu average load status, collect from /proc/loadavg file")
def get_os_swap_status(server, status):
count = 0
file = open("/proc/vmstat", 'r')
line = file.readline()
while line:
if (line.startswith("pswpin")):
swaps = line.split()
status["os_swap_pswpin"] = swaps[1]
count += 1
elif (line.startswith("pswpout")):
swaps = line.split()
status["os_swap_pswpout"] = swaps[1]
count += 1
line = file.readline()
if (count >= 2):
break
file.close()
return
os_swap_section = StatusSection("os_swap",type_linux,[
StatusColumn("si", "swap_in_per_second", 4, column_flags_speed, field_handler_common, ["os_swap_pswpin"], "Counts per second of data moved from memory to swap, related to pswpin."),
StatusColumn("so", "swap_out_per_second", 4, column_flags_speed, field_handler_common, ["os_swap_pswpout"], "Counts per second of data moved from swap to memory, related to pswpout.")
],[get_os_swap_status],[ALL_COLUMNS],
"os swap status, collect from /proc/vmstat file")
net_face_name="lo"
def get_os_net_status(server, status):
file = open("/proc/net/dev", 'r')
line = file.readline().lstrip()
find = 0
while line:
if (line.startswith(net_face_name+':')):
find = 1
fields = line.split()
status["os_net_bytes_in"] = fields[1]
status["os_net_bytes_out"] = fields[9]
status["os_net_packages_in"] = fields[2]
status["os_net_packages_out"] = fields[10]
break
line = file.readline().lstrip()
file.close()
if find == 0:
errmsg = "Net face '" + net_face_name + "' is not exist!"
raise Exception(errmsg)
return
os_net_bytes_section = StatusSection("os_net_bytes",type_linux,[
StatusColumn("in", "incoming_bytes_per_second", 0, column_flags_speed|column_flags_bytes, field_handler_common, ["os_net_bytes_in"], "Bytes per second the network incoming."),
StatusColumn("out", "outgoing_bytes_per_second", 0, column_flags_speed|column_flags_bytes, field_handler_common, ["os_net_bytes_out"], "Bytes per second the network outgoing.")
],[get_os_net_status],[ALL_COLUMNS],
"os network bytes status, collect from /proc/net/dev file, you need to use --net-face option "
"to set the net face name that you want to monitor, the net face name is in the /proc/net/dev file")
os_net_packages_section = StatusSection("os_net_packages",type_linux,[
StatusColumn("in", "incoming_packages_per_second", 0, column_flags_speed, field_handler_common, ["os_net_packages_in"], "Packages per second the network incoming."),
StatusColumn("out", "outgoing_packages_per_second", 0, column_flags_speed, field_handler_common, ["os_net_packages_out"], "Packages per second the network outgoing.")
],[get_os_net_status],[ALL_COLUMNS],
"os network packages status, collect from /proc/net/dev file, you need to use --net-face option "
"to set the net face name that you want to monitor, the net face name is in the /proc/net/dev file")
disk_name = "vda"
os_disk_stats_first_time=1
def get_disk_status(server, status):
file = open("/proc/diskstats", 'r')
os_disk_stats_get_time = datetime.datetime.utcnow()
line = file.readline()
find = 0
while line:
fields = line.split()
if (fields[2] == disk_name):
find = 1
global os_disk_stats_first_time
if (os_disk_stats_first_time == 1):
os_disk_stats_first_time = 0
server.os_disk_stats_fields_old = fields
server.os_disk_stats_get_time_old = os_disk_stats_get_time
status["os_disk_reads"] = "0"
status["os_disk_writes"] = "0"
status["os_disk_read_bytes"] = "0"
status["os_disk_write_bytes"] = "0"
status["os_disk_queue"] = "0"
status["os_disk_wait"] = "0"
status["os_disk_service_time"] = "0"
status["os_disk_busy"] = "0"
break
fields_old = server.os_disk_stats_fields_old
rd_ios = long(fields[3]) - long(fields_old[3]) #/* Read I/O operations */
rd_merges = long(fields[4]) - long(fields_old[4]) #/* Reads merged */
rd_sectors = long(fields[5]) - long(fields_old[5]) #/* Sectors read */
rd_ticks = long(fields[6]) - long(fields_old[6]) #/* Time in queue + service for read */
wr_ios = long(fields[7]) - long(fields_old[7]) # /* Write I/O operations */
wr_merges = long(fields[8]) - long(fields_old[8]) # /* Writes merged */
wr_sectors = long(fields[9]) - long(fields_old[9]) # /* Sectors written */
wr_ticks = long(fields[10]) - long(fields_old[10]) # /* Time in queue + service for write */
ticks = long(fields[12]) - long(fields_old[12]) #/* Time of requests in queue */
aveq = long(fields[13]) - long(fields_old[13]) #/* Average queue length */
deltams = microsecond_differ_by_datetime(os_disk_stats_get_time, server.os_disk_stats_get_time_old)
deltams = float(deltams)/1000
server.os_disk_stats_fields_old = fields
server.os_disk_stats_get_time_old = os_disk_stats_get_time
n_ios = long(rd_ios) + long(wr_ios) #/* Number of requests */
n_ticks = long(rd_ticks) + long(wr_ticks) #/* Total service time */
n_kbytes = (float(rd_sectors) + float(wr_sectors))/2.0 #/* Total kbytes transferred */
queue = float(aveq)/deltams #/* Average queue */
if (n_ios > 0):
size = float(n_kbytes)/n_ios #/* Average request size */
wait = float(n_ticks)/n_ios #/* Average wait */
svc_t = float(ticks)/n_ios #/* Average disk service time */
else:
size = 0
wait = 0
svc_t = 0
busy = 100.0 * float(ticks)/float(deltams) #/* Utilization at disk (percent) */
if (busy > 99.99):
busy = 100
rkbs = 1000.0*float(rd_sectors)/deltams/2
wkbs = 1000.0*float(wr_sectors)/deltams/2
# r/s w/s
rd_ios_s = 1000.0 * float(rd_ios)/deltams
wr_ios_s = 1000.0 * float(wr_ios)/deltams
status["os_disk_reads"] = num2readable(rd_ios_s if rd_ios_s > 0 else 0)
status["os_disk_writes"] = num2readable(wr_ios_s if wr_ios_s > 0 else 0)
status["os_disk_read_bytes"] = byte2readable(rkbs*1024.0 if rkbs > 0 else 0)
status["os_disk_write_bytes"] = byte2readable(wkbs*1024.0 if wkbs > 0 else 0)
status["os_disk_queue"] = num2readable(queue if queue > 0 else 0)
status["os_disk_wait"] = num2readable(wait if wait > 0 else 0)
status["os_disk_service_time"] = num2readable(svc_t if svc_t > 0 else 0)
status["os_disk_busy"] = num2readable(busy if busy > 0 else 0)
break
line = file.readline()
file.close()
if find == 0:
errmsg = "Disk '" + disk_name + "' is not exist!"