-
Notifications
You must be signed in to change notification settings - Fork 2
/
pm_logconv.py
executable file
·3668 lines (3294 loc) · 115 KB
/
pm_logconv.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
# -*- coding: utf-8 -*-
# pm_logconv : Pacemaker and Heartbeat log converter
#
# support version
# Pacemaker : stable-1.0 (1.0.9 or more)
# Heartbeat : 3.0.3
#
# Copyright (C) 2010 NIPPON TELEGRAPH AND TELEPHONE CORPORATION
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import os, sys, signal, time, datetime, syslog, types, glob, pickle
import ConfigParser, re, commands, operator, string
from optparse import OptionParser
from stat import ST_INO, ST_NLINK, ST_SIZE, S_IRUSR, S_IWUSR
from socket import gethostname
from errno import ESRCH
#
# version number of pm_logconv.
#
VERSION = "1.3"
#
# system's host name.
#
try:
HOSTNAME = gethostname()
except Exception, strerror:
print >> sys.stderr, "Error: gethostname() error occurred.", strerror
sys.exit(1)
#
# default settings.
# (when not specified with configuration file or command line option.)
#
CONFIGFILE = "/etc/pm_logconv.conf"
HA_LOGFILE = "/var/log/ha-log"
OUTPUTFILE = "/var/log/pm_logconv.out"
SYSLOGFORMAT = True
HOSTCACHE = "/var/lib/heartbeat/hostcache"
HACFFILE = "/etc/ha.d/ha.cf"
#
# Timeout(ms) for reset log convert status.
#
RESET_INTERVAL = 60
# A flag of failer status
# resource failer 1(resource error)
# score failer 2(pingd rsclocation)
# node failer 3(split brain)
FAIL_RSC = "1"
FAIL_SCORE = "2"
FAIL_NODE = "3"
# A flag of resource status(for failer)
# resource start 1
# resource move 2
# resource stop 3
# resource stopped 4
FAIL_STR = "1"
FAIL_MOVE = "2"
FAIL_STP = "3"
FAIL_STPD = "4"
#
# A list of [attribute_name, operation, attribute_value],
# The setting is described in CONFIGFILE.
# These are to decide whether some failure occur or not
# when cluster status changes to S_POLICY_ENGINE.
#
attrRuleList = list()
attrRules = list()
# A list of resource-id.
# If the all of specified resources are active,
# it means "F/O succeeded."
# If not, "F/O failed."
# The setting is described in CONFIGFILE.
actRscList = list()
#
# A list of patterns.
# The setting is described in CONFIGFILE.
#
lconvRuleList = list()
#
# shutdown flag, when SIGINT or SIGTERM signal is received, set it True.
#
do_shutdown = False
#
# command name for getting current status of the cluster.
#
CMD_CRM_ATTR = "crm_attribute"
#
# command name for getting DC node status.
#
CMD_CRMADMIN = "crmadmin"
#
# output version number of pm_logconv and exit.
#
def print_version(option, opt, value, parser):
sys.stdout.write("%s\n" % VERSION)
sys.exit(0)
#
# signal handler method. only set True to the shutdown flag.
#
def shutdown_logconv(signum, frame):
global do_shutdown
pm_log.info("shutdown_logconv: received signal [%d], " \
"scheduling shutdown.." % signum)
do_shutdown = True
#
# set the signal handler.
#
signal.signal(signal.SIGINT, shutdown_logconv)
signal.signal(signal.SIGTERM, shutdown_logconv)
class LogconvLog:
LOG_EMERG = 0
LOG_ALERT = 1
LOG_CRIT = 2
LOG_ERR = 3
LOG_WARNING = 4
LOG_NOTICE = 5
LOG_INFO = 6
LOG_DEBUG = 7
syspriority = [ syslog.LOG_EMERG, syslog.LOG_ALERT, syslog.LOG_CRIT,
syslog.LOG_ERR, syslog.LOG_WARNING, syslog.LOG_NOTICE,
syslog.LOG_INFO, syslog.LOG_DEBUG ]
prioritystr = [ "EMERG", "ALERT", "CRIT", "ERROR", "WARN",
"notice", "info", "debug" ]
DEFAULT_LOGOPT = syslog.LOG_CONS
DEFAULT_FACILITY = syslog.LOG_DAEMON
facility_map = {
"kern": syslog.LOG_KERN,
"user": syslog.LOG_USER,
"mail": syslog.LOG_MAIL,
"daemon": syslog.LOG_DAEMON,
"auth": syslog.LOG_AUTH,
"syslog": syslog.LOG_SYSLOG,
"lpr": syslog.LOG_LPR,
"news": syslog.LOG_NEWS,
"uucp": syslog.LOG_UUCP,
"cron": syslog.LOG_CRON,
"authpriv": 10<<3,
"ftp": 11<<3,
"local0": syslog.LOG_LOCAL0,
"local1": syslog.LOG_LOCAL1,
"local2": syslog.LOG_LOCAL2,
"local3": syslog.LOG_LOCAL3,
"local4": syslog.LOG_LOCAL4,
"local5": syslog.LOG_LOCAL5,
"local6": syslog.LOG_LOCAL6,
"local7": syslog.LOG_LOCAL7,
}
facilitystr_map = {
syslog.LOG_KERN: "kern",
syslog.LOG_USER: "user",
syslog.LOG_MAIL: "mail",
syslog.LOG_DAEMON: "daemon",
syslog.LOG_AUTH: "auth",
syslog.LOG_SYSLOG: "syslog",
syslog.LOG_LPR: "lpr",
syslog.LOG_NEWS: "news",
syslog.LOG_UUCP: "uucp",
syslog.LOG_CRON: "cron",
10<<3: "authpriv",
11<<3: "ftp",
syslog.LOG_LOCAL0: "local0",
syslog.LOG_LOCAL1: "local1",
syslog.LOG_LOCAL2: "local2",
syslog.LOG_LOCAL3: "local3",
syslog.LOG_LOCAL4: "local4",
syslog.LOG_LOCAL5: "local5",
syslog.LOG_LOCAL6: "local6",
syslog.LOG_LOCAL7: "local7",
}
facilitystr = facilitystr_map[DEFAULT_FACILITY]
def __init__(self, priority, path):
self.pid = os.getpid()
if not isinstance(priority, int) and not isinstance(priority, long):
self.priority = self.LOG_INFO
else:
self.priority = priority
if not isinstance(path, types.StringTypes):
self.output = None
else:
self.output = path
self.facility = self.DEFAULT_FACILITY
syslog.openlog("pm_logconv", self.DEFAULT_LOGOPT, self.facility)
def __setattr__(self, name, val):
if name != "LOG_EMERG" and name != "LOG_ALERT" and \
name != "LOG_CRIT" and name != "LOG_ERR" and \
name != "LOG_WARNING" and name != "LOG_NOTICE" and \
name != "LOG_INFO" and name != "LOG_DEBUG" and \
name != "DEFAULT_LOGOPT" and name != "DEFAULT_FACILITY":
self.__dict__[name] = val
def set_priority(self, priority):
if not isinstance(priority, int) and not isinstance(priority, long):
return False
if self.LOG_EMERG < priority and self.DEBUG > priority:
return False
self.priority = priority
return True
def set_output(self, path):
if not isinstance(path, types.StringTypes):
return False
self.output = path
return True
def set_facility(self, facility):
# FYI: LOG_AUTHPRIV : 10<<3
# LOG_FTP : 11<<3
if self.facility == facility:
return True
if self.facilitystr_map.has_key(facility):
pm_log.notice("syslog facility changed [%s] to [%s]"
% (self.facilitystr, self.facilitystr_map[facility]))
syslog.closelog()
self.facility = facility
syslog.openlog("pm_logconv", self.DEFAULT_LOGOPT, self.facility)
self.facilitystr = self.facilitystr_map[facility]
return True
return False
def emerg(self, message):
if self.output == None or self.priority >= self.LOG_EMERG:
return self.logging(self.LOG_EMERG, message)
return True
def alert(self, message):
if self.output == None or self.priority >= self.LOG_ALERT:
return self.logging(self.LOG_ALERT, message)
return True
def crit(self, message):
if self.output == None or self.priority >= self.LOG_CRIT:
return self.logging(self.LOG_CRIT, message)
return True
def error(self, message):
if self.output == None or self.priority >= self.LOG_ERR:
return self.logging(self.LOG_ERR, message)
return True
def warn(self, message):
if self.output == None or self.priority >= self.LOG_WARNING:
return self.logging(self.LOG_WARNING, message)
return True
def notice(self, message):
if self.output == None or self.priority >= self.LOG_NOTICE:
return self.logging(self.LOG_NOTICE, message)
return True
def info(self, message):
if self.output == None or self.priority >= self.LOG_INFO:
return self.logging(self.LOG_INFO, message)
return True
def debug(self, message):
if self.output == None or self.priority >= self.LOG_DEBUG:
return self.logging(self.LOG_DEBUG, message)
return True
def logging(self, priority, message):
try:
if not isinstance(priority, int) and not isinstance(priority, long):
return False
if not isinstance(message, types.StringTypes):
return False
if self.output == None:
syslog.syslog(self.syspriority[priority], "[%d]: %-7s %s" %
(self.pid, self.prioritystr[priority] + ':', message.rstrip()))
else:
t = datetime.datetime.today()
tfmt = "%s %2d %s" % \
(t.strftime('%b'), int(t.strftime('%d')), t.strftime('%X'))
f = open(self.output, 'a')
f.write("%s %s [%d]: %-7s %s\n" % (tfmt, HOSTNAME, self.pid,
self.prioritystr[priority] + ':', message.rstrip()))
f.close()
return True
except Exception, strerror:
print >> sys.stderr, "Error: logging() error occurred.", strerror
sys.exit(1)
class PIDFile:
'''
status of the PID file operation.
'''
SYSTEM_ERROR = -1
FILE_NOTEXIST = -2
FILE_INVALID = -3
NOTRUNNING = -4
def __init__(self, path):
self.path = path
'''
status is set as read-only.
'''
def __setattr__(self, name, val):
if name != "SYSTEM_ERROR" and name != "FILE_NOTEXIST" and \
name != "FILE_INVALID" and name != "NOTRUNNING":
self.__dict__[name] = val
'''
check whether the process of the PID file has running.
return 0 > : process is running.
SYSTEM_ERROR : system error occurred.
NOTRUNNING : process is NOT running.
'''
def is_running(self, pid, cmdline):
try:
os.kill(pid, 0)
except Exception, (errNo, strerror):
if errNo == ESRCH:
pm_log.debug("is_running: pm_logconv isn't running.")
return self.NOTRUNNING
else:
pm_log.error("is_running: kill(%d, 0) error occurred." % pid)
pm_log.debug("is_running: kill(%d, 0) error occurred. [%s]"
% (pid, strerror))
return self.SYSTEM_ERROR
# check to make sure pid hasn't been reused by another process.
try:
proc_path = "/proc/%d/cmdline" % pid
f = open(proc_path, 'r')
cmdline_now = f.readline().replace('\0', ' ').strip()
f.close()
pm_log.debug("is_running: tracked[%s], /proc/%d/cmdline[%s]"
% (cmdline, pid, cmdline_now))
if cmdline != cmdline_now:
return self.NOTRUNNING
except Exception, strerror:
pm_log.error("is_running: couldn't read from '%s'." % proc_path)
pm_log.debug("is_running: couldn't read from '%s'. %s"
% (proc_path, strerror))
return self.SYSTEM_ERROR
return pid
'''
read PID file.
return 0 > : process is running. return running process's PID.
SYSTEM_ERROR : system error occurred.
FILE_NOTEXIST : PID file doesn't exist.
FILE_INVALID : PID file is broken...
NOTRUNNING : succeeded. process is NOT running.
'''
def read(self):
try:
if os.path.exists(self.path):
f = open(self.path, 'r')
pid = f.readline().strip()
cmdline = f.readline().strip('\n')
f.close()
if pid.isdigit() and int(pid) != os.getpid():
return self.is_running(int(pid), cmdline)
else:
pm_log.info("PIDFile.read: PID file is screwed up.")
return self.FILE_INVALID
else:
pm_log.info("PIDFile.read: PID file doesn't exist.")
return self.FILE_NOTEXIST
except Exception, strerror:
pm_log.error("PIDFile.read: I/O error occurred.")
pm_log.debug("PIDFile.read: I/O error occurred. [%s]" % strerror)
return self.SYSTEM_ERROR
'''
lock PID file.
return 0 : succeeded.
0 > : return already running process's PID.
SYSTEM_ERROR : system error occurred.
'''
def lock(self):
try:
ret = self.read()
if ret > 0 or ret == self.SYSTEM_ERROR:
return ret
elif ret == self.FILE_NOTEXIST:
pass
elif ret == self.FILE_INVALID or ret == self.NOTRUNNING:
os.remove(self.path)
else:
return self.SYSTEM_ERROR
except Exception, strerror:
pm_log.error("PIDFile.lock: I/O error occurred.")
pm_log.debug("PIDFile.lock: I/O error occurred. [%s]" % strerror)
return self.SYSTEM_ERROR
try:
pid = os.getpid()
f = open("/proc/%d/cmdline" % pid, 'r')
cmdline = f.readline().replace('\0', ' ').strip()
f.close()
tfile = ("%s.%d" % (self.path, pid))
f = open(tfile, 'w')
f.write("%d\n%s\n" % (pid, cmdline))
f.close()
os.link(tfile, self.path)
nlink = os.stat(tfile)[ST_NLINK]
os.remove(tfile)
except Exception, strerror:
pm_log.error("PIDFile.lock: I/O error occurred.")
pm_log.debug("PIDFile.lock: I/O error occurred. [%s]" % strerror)
try:
f.close()
os.remove(tfile)
except:
pass
return self.SYSTEM_ERROR
if nlink < 2:
# somehow, it didn't get through - NFS trouble?
return self.SYSTEM_ERROR
return 0
class ConvertStatus:
def __init__(self):
self.ino = 0
self.offset = 0
self.FAILURE_OCCURRED = False
self.IN_CALC = False
self.ACTRSC_MOVE = False
self.IN_FO_PROCESS = False
self.timedoutRscopSet = set()
self.attrDict = dict()
self.nodeDict = dict()
cstat = ConvertStatus()
class StatusFile:
def __init__(self, path):
self.path = path
self.w_ino = 0
self.w_offset = 0
self.in_calc = False
'''
read from status(read position of ha-log and status of convert) file.
'''
def read(self):
try:
if os.path.exists(self.path):
f = os.open(self.path, os.O_RDONLY)
c = pickle.loads(os.read(f, os.stat(self.path)[ST_SIZE]))
os.close(f)
cstat.ino = self.w_ino = c.ino
cstat.offset = self.w_offset = c.offset
cstat.FAILURE_OCCURRED = c.FAILURE_OCCURRED
cstat.IN_CALC = self.in_calc = c.IN_CALC
cstat.ACTRSC_MOVE = c.ACTRSC_MOVE
cstat.IN_FO_PROCESS = c.IN_FO_PROCESS
cstat.timedoutRscopSet = c.timedoutRscopSet
cstat.attrDict = c.attrDict
cstat.nodeDict = c.nodeDict
else:
pm_log.info("StatusFile.read: status file doesn't exist.")
self.clear_cstat()
pm_log.debug("StatusFile.read: [%d:%d], FAIL[%s], IN_CALC[%s], "\
"RSC_MOVE[%s], IN_FO[%s], Rscop%s, attrDict%s, nodeDict%s" %
(cstat.ino, cstat.offset, cstat.FAILURE_OCCURRED,
cstat.IN_CALC, cstat.ACTRSC_MOVE, cstat.IN_FO_PROCESS,
list(cstat.timedoutRscopSet), dict(cstat.attrDict), dict(cstat.nodeDict)))
return True
except Exception, strerror:
pm_log.error("StatusFile.read: I/O error occurred.")
pm_log.debug("StatusFile.read: I/O error occurred. [%s]" % strerror)
self.clear_cstat()
return False
'''
write to status(reading ha-log's position and status of convert) file.
'''
def write(self):
if cstat.IN_CALC:
if self.in_calc:
return True
self.in_calc = True
else:
self.in_calc = False
self.w_ino = cstat.ino
self.w_offset = cstat.offset
try:
# current implementation writes to the statfile with os.write().
# since between built-in function write() and close(), file becomes empty.
f = os.open(self.path, os.O_WRONLY | os.O_CREAT, S_IRUSR | S_IWUSR)
l = os.write(f, pickle.dumps(cstat, pickle.HIGHEST_PROTOCOL))
os.ftruncate(f, l)
os.close(f)
pm_log.debug("StatusFile.write: [%d:%d], FAIL[%s], IN_CALC[%s], "\
"RSC_MOVE[%s], IN_FO[%s], Rscop%s, attrDict%s, nodeDict%s" %
(cstat.ino, cstat.offset, cstat.FAILURE_OCCURRED,
cstat.IN_CALC, cstat.ACTRSC_MOVE, cstat.IN_FO_PROCESS,
list(cstat.timedoutRscopSet), dict(cstat.attrDict), dict(cstat.nodeDict)))
return True
except Exception, strerror:
pm_log.error("StatusFile.write: I/O error occurred.")
pm_log.debug("StatusFile.write: I/O error occurred. [%s]" % strerror)
return False
def clear_cstat(self):
global cstat
pm_log.debug("clear_cstat: called.")
cstat = ConvertStatus()
self.w_ino = cstat.ino
self.w_offset = cstat.offset
self.in_calc = cstat.IN_CALC
return
statfile = None
class ParseConfigFile:
'''
Initialization to parse config file.
Open the config file. Its fd should be close in __del__().
'''
def __init__(self, config_file):
self.SEC_SETTINGS = "Settings"
self.OPT_HA_LOG_PATH = "ha_log_path"
self.OPT_HACF_PATH = "hacf_path"
self.OPT_OUTPUT_PATH = "output_path"
self.OPT_DATEFORMAT = "syslogformat"
self.OPT_HOSTCACHE = "hostcache_path"
self.OPT_MANAGE_ATTR = "attribute"
self.OPT_PATTERN = "pattern"
self.OPT_RESET_INTERVAL = "reset_interval"
self.OPT_FUNCNAME = "func"
self.OPT_LOGLEVEL = "loglevel"
self.OPT_FOTRIGGER = "fotrigger"
self.OPT_IGNOREMSG = "ignoremsg"
self.OPT_LOGFACILITY = "logconv_logfacility"
self.logfacility = None
self.OPT_ACTRSC = "act_rsc"
self.fp = None
self.cf = ConfigParser.RawConfigParser()
# open the config file to read.
if not os.path.exists(config_file):
pm_log.error("ParseConfigFile.__init__(): " +
"config file [%s] does not exist." % (config_file))
#__init__ should return None...
sys.exit(1)
try:
self.fp = open(config_file)
self.cf.readfp(self.fp)
except Exception, strerror:
pm_log.error("ParseConfigFile.__init__(): " +
"failed to read config file [%s]." % (config_file))
pm_log.debug("ParseConfigFile.__init__(): %s" % (strerror))
#__init__ should return None...
sys.exit(1)
def __del__(self):
if self.fp is not None:
self.fp.close()
def get_optval(self, secname, optname):
optval = None
try:
optval = self.cf.get(secname, optname)
except Exception, strerror:
pm_log.warn("get_optval(): " +
"failed to get value of \"%s\" in [%s] section. " %
(optname, secname))
pm_log.debug("get_optval(): %s" % (strerror))
return None
if optval == "":
pm_log.warn("get_optval(): " +
"the value of \"%s\" in [%s] section is empty. " %
(optname, secname))
return None
return optval
'''
Parse [Settings] section.
return 0 : succeeded.
0 > : error occurs.
'''
def parse_basic_settings(self):
global HA_LOGFILE
global HACFFILE
global OUTPUTFILE
global SYSLOGFORMAT
global HOSTCACHE
global RESET_INTERVAL
global attrRuleList
global attrRules
global actRscList
# Get all options in the section.
try:
setting_opts = self.cf.options(self.SEC_SETTINGS)
except:
pm_log.warn("parse_basic_settings(): " +
"[%s] section does not exist. " % (self.SEC_SETTINGS))
return (-1)
for optname in setting_opts:
optval = self.get_optval(self.SEC_SETTINGS, optname)
if not optval:
pm_log.warn("parse_basic_settings(): " +
"Ignore the setting of \"%s\"." % (optname))
continue # To the next option in [Settings].
if optname == self.OPT_HA_LOG_PATH:
HA_LOGFILE = optval
elif optname == self.OPT_HACF_PATH:
HACFFILE = optval
elif optname == self.OPT_OUTPUT_PATH:
OUTPUTFILE = optval
elif optname == self.OPT_DATEFORMAT:
if optval.lower() == "true":
SYSLOGFORMAT = True
elif optval.lower() == "false":
SYSLOGFORMAT = False
else:
pm_log.warn("parse_basic_settings(): " +
"the value of \"%s\" is invalid. " % (optname) +
"Ignore the setting.")
elif optname == self.OPT_HOSTCACHE:
HOSTCACHE = optval
elif optname == self.OPT_RESET_INTERVAL:
try:
tmpval = int(optval)
# 1 to 32bit integer max value
if tmpval > 0 and tmpval <= 2147483647:
RESET_INTERVAL = tmpval
else:
raise
except:
pm_log.warn("parse_basic_settings(): " +
"the value of \"%s\" is invalid. " % (optname) +
"set an default value(60).")
elif optname.startswith(self.OPT_MANAGE_ATTR) and optval.count(','):
attrRule = optval.split(',')
if len(attrRule) != 3:
pm_log.warn("parse_basic_settings(): " +
"the format of \"%s\" is invalid. " % (optname) +
"Ignore the setting.")
continue # To the next option in [Settings].
(attrname, op, attrval) = tuple(attrRule)
attrname = attrname.strip()
op = op.strip()
attrval = attrval.strip()
if attrname == "" or op == "" or attrval == "":
pm_log.warn("parse_basic_settings(): " +
"the value of \"%s\" is invalid. " % (optname) +
"Ignore the setting.")
continue # To the next option in [Settings].
'''
op string should be [lt|gt|lte|gte|eq|ne] in cib.xml.
However, with operator module of Python,
"lte" is expressed "le", and "gte" is "ge".
Here, replace op string to use it as function name.
'''
opList = ["lt", "gt", "le", "ge", "eq", "ne"]
opmatch = False
for opstr in opList:
if op == opstr:
opmatch = True
if not opmatch:
if op == "lte":
op = "le"
elif op == "gte":
op = "ge"
else:
pm_log.warn("parse_basic_settings(): " +
"operation \"%s\" (in \"%s\") is invalid. " %
(op, optname) +
"Ignore the setting.")
continue # To the next option in [Settings].
attrRule = [attrname, op, attrval]
attrRuleList.append(attrRule)
pm_log.debug("parse_basic_settings(): attrRuleList%s"%(attrRuleList))
elif optname.startswith(self.OPT_MANAGE_ATTR) and not optval.count(','):
optvals = []; rule = []
for x in [x for x in optval.split(' ') if x]:
if x.lower() in ['defined','not_defined']:
optvals.append(None)
optvals.append(x)
if len(optvals) % 4 != 3:
pm_log.warn("parse_basic_settings(): "
"the format of \"%s\" is invalid."
%(optname) + " Ignore the setting.")
continue # To the next option in [Settings].
binops = ['lt','gt','le','ge','eq','ne','defined','not_defined']
for i,x in enumerate(optvals):
if i % 4 == 0:
name = x
elif i % 4 == 1:
y = x.lower().replace('lte','le').replace('gte','ge')
if y in binops:
op = y
else:
pm_log.warn("parse_basic_settings(): "
"binary_op \"%s\" (in \"%s\") is invalid."
%(x,optname) + " Ignore the setting.")
break
elif i % 4 == 2:
rule.append([name, op, x])
elif i % 4 == 3:
if x.lower() in ['and','or']:
rule.append(x.lower())
else:
pm_log.warn("parse_basic_settings(): "
"bool_op \"%s\" (in \"%s\") is invalid."
%(x,optname) + " Ignore the setting.")
break
else:
attrRules.append(rule)
pm_log.debug("parse_basic_settings(): attrRules%s"%(attrRules))
continue # To the next option in [Settings].
elif optname == self.OPT_LOGFACILITY:
if LogconvLog.facility_map.has_key(optval.lower()):
self.logfacility = LogconvLog.facility_map[optval.lower()]
else:
pm_log.warn("parse_basic_settings(): " +
"the value of \"%s\" is invalid. " % (optname) +
"Ignore the setting.")
elif optname == self.OPT_ACTRSC:
for rstr in optval.split(','):
rstr = rstr.strip()
if rstr != "":
if rstr in actRscList:
pm_log.warn("parse_basic_settings(): " +
"resource id \"%s\" is written redundantly. " %
(rstr) +
"Ignore the redundancy.")
else:
actRscList.append(rstr)
# __if optname == xxx:
# __for optname in setting_opts:
return 0
'''
Parse sections for log-convertion.
return 0 : succeeded.
0 > : error occurs.
'''
def parse_logconv_settings(self):
logconv_sections = self.cf.sections()
try:
logconv_sections.remove(self.SEC_SETTINGS)
except:
pm_log.warn("parse_logconv_settings(): " +
"[%s] section does not exist. " % (self.SEC_SETTINGS))
#
# Parse each section.
#
for secname in logconv_sections:
# Get all options in the section.
try:
logconv_opts = self.cf.options(secname)
except:
pm_log.warn("parse_logconv_settings(): " +
"[%s] section does not exist. " % (secname) +
"Ignore this section.")
continue #To the next section.
lconvfrm = LogconvFrame()
lconvfrm.rulename = secname
for optname in logconv_opts:
optval = self.get_optval(secname, optname)
if not optval:
pm_log.warn("parse_logconv_settings(): " +
"Ignore the setting of \"%s\"." % (optname))
continue # To the next option.
if optname == self.OPT_FUNCNAME:
defined = hasattr(LogConvertFuncs, optval)
if defined == False:
pm_log.error("parse_logconv_settings(): " +
"function %s() specified in " % (optval) +
"[%s] section is not defined." % (secname))
break # Break off parsing this section.
lconvfrm.func = optval
elif optname == self.OPT_LOGLEVEL:
lconvfrm.loglevel = optval
elif optname == self.OPT_FOTRIGGER:
lconvfrm.fotrigger = optval
elif optname == self.OPT_IGNOREMSG:
if optval.lower() == "true":
lconvfrm.ignoremsg = True
elif optval.lower() == "false":
lconvfrm.ignoremsg = False
else:
pm_log.warn("parse_logconv_settings(): " +
"the value of \"%s\" is invalid. " % (optname) +
"Ignore the setting.")
elif optname.startswith(self.OPT_PATTERN):
pstrList = list()
tmpList = list()
pstrList = self.parse_ptn_strings(optval)
if len(pstrList) <= 0:
pm_log.error("parse_logconv_settings(): " +
"match pattern string of \"%s\" is empty." %
(optname))
break # Break off parsing this section.
tmpList = self.compile_ptn_strings(pstrList)
if tmpList is None:
pm_log.error("parse_logconv_settings(): " +
"failed to compile the pattern string in \"%s\"." %
(optname))
break # Break off parsing this section.
lconvfrm.ptnList.append(tmpList)
else:
pm_log.debug("parse_logconv_settings(): " +
"\"%s\" is not valid option string." % (optname) +
"Ignore the setting.")
# __for optname in logconv_opts:
if len(lconvfrm.ptnList) == 0 or lconvfrm.func == None:
pm_log.warn("parse_logconv_settings(): " +
"\"%s\" and \"%s*\" setting is required in section [%s]. " %
(self.OPT_FUNCNAME, self.OPT_PATTERN, secname) +
"Ignore the section.")
del lconvfrm
else:
lconvRuleList.append(lconvfrm)
#To the next section.
#__for secname in logconv_sections:
return 0
'''
Parse match pattern strings (written in a line) and
make a list of them.
Strings are set apart by ','.
arg1 : match pattern strings.
return: a list of pattern strings.
'''
def parse_ptn_strings(self, pstrings):
pstrList = list()
for pstr in pstrings.split(','):
pstr = pstr.strip()
if pstr != "":
pstrList.append(pstr)
return pstrList
'''
Compile each pattern string.
arg1 : a list of pattern strings (made with parse_ptn_strings()).
return: a list of compiled objects.
'''
def compile_ptn_strings(self, pstrList):
compiledList = list()
for pstr in pstrList:
#If it is a negative pattern, compile is as so.
if pstr.startswith('!'):
pstr = ur"^(?!.*" + pstr.lstrip('!') + ur").*$"
compiledList.append(re.compile(pstr))
return compiledList
'''
Class to hold rules to convert log message.
'''
class LogconvFrame:
'''
rulename : convert rule name. set section name.
ptnList : list of compiled object list of match patterns
(list of lists).
func : function name to convert log message which matches the rule.
loglevel : log level of converted log.
fotrigger: the log message is trigger of F/O or not. [True|False]
ignoremsg: wheter set the time of output log message for auto reset
function. [True|False]
'''
def __init__(self, rulename=None, ptnList=None, func=None, loglevel=None,
fotrigger=False, ignoremsg=False):
self.rulename = rulename
self.ptnList = ptnList
self.ptnList = list()
self.func = func
self.loglevel = loglevel
self.fotrigger = fotrigger
self.ignoremsg = ignoremsg
'''
Only for debug.
'''
def print_frmval(self):
print self.rulename
print self.ptnList
print self.func
print self.loglevel
print self.fotrigger
print self.ignoremsg
class LogConvert:
PIDFILE = "/var/run/pm_logconv.pid"
STATFILE = "/var/run/pm_logconv.stat"
def __init__(self):
self.daemonize = False
self.stop_logconv = False
self.ask_status = False
self.is_continue = False
self.is_present = False
self.configfile = CONFIGFILE
now = datetime.datetime.now()
self.last_logoutput_t = now
self.last_reset_t = now
# Get obj of functions to convert log.
self.funcs = LogConvertFuncs()
signal.signal(signal.SIGUSR1, self.check_dc_and_reset)
if not self.parse_args():
sys.exit(1)
pm_log.debug("option: daemon[%d], stop[%d], status[%d], continue[%d], " \
"present[%d], config[%s], facility[%s]" % (self.daemonize, self.stop_logconv,
self.ask_status, self.is_continue, self.is_present, self.configfile, pm_log.facilitystr))
if not self.stop_logconv and not self.ask_status:
pm_log.debug("option: target[%s], output[%s], syslogfmt[%s], ha.cf[%s], hcache[%s], reset_interval[%d], actrsc%s" % (HA_LOGFILE, OUTPUTFILE, SYSLOGFORMAT, HACFFILE, HOSTCACHE, RESET_INTERVAL, actRscList))
'''
PID and status(read position of ha-log and status of convert) file path
is set as read-only.
'''
def __setattr__(self, name, val):
if name != "PIDFILE" and name != "STATFILE":
self.__dict__[name] = val
'''
parse options - command line option and configure file.
'''
def parse_args(self):
myusage = "\n%prog [options]"
psr = OptionParser(usage=myusage)
psr.add_option("-d", action="store_true", dest="daemonize",
default=False, help="make the program a daemon")
psr.add_option("-k", action="store_true", dest="stop_logconv",
default=False, help="stop the pm_logconv if it is already running")
psr.add_option("-s", action="store_true", dest="ask_status",
default=False, help="return pm_logconv status")
psr.add_option("-c", action="store_true", dest="is_continue",
default=False, help="start with a continuous mode (\"-p\" option is mutually exclusive)")
psr.add_option("-p", action="store_true", dest="is_present",
default=False, help="start with a present mode (\"-c\" option is mutually exclusive)")
psr.add_option("-f", dest="config_file", default=CONFIGFILE,
help="the specified configuration file is used")
psr.add_option("-v", "--version", action="callback", callback=print_version,
help="print out this program's version and exit")