forked from NUT-RogerPrice/UPSmon
-
Notifications
You must be signed in to change notification settings - Fork 1
/
UPSmon.py
executable file
·3698 lines (3445 loc) · 181 KB
/
UPSmon.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/python3 -u
# UPSmon Manage local and remote NUT installations
# Called by systemctl start nut-py-monitor.service
# Copyright (C) 2019-2021 Roger Price. GPL v3 or later at your choice.
'''UPSmon Manage local and remote NUT installations'''
Version='1.3'
# Version 1.1 changes:
# 2020-10-26 RP Added built-in timer 'start'
# 2020-11-01 RP Redefine fd_log after logrotate
# 2020-11-08 RP Default port is IANA ups/401
# 2020-11-09 RP Ensure email and wall send 7-bit ascii
# 2020-11-11 RP Added statuses LB1, LB2 and LB3
# 2020-11-11 RP Test for m = None in data_time
# 2020-11-27 RP OS ID improvement
# Version 1.2 changes:
# 2021-05-30 RP primary/secondary are permissable alternatives to master/slave
# 2021-05-30 RP Added status LS
# 2021-08-19 RP Debian 11 uses /usr/bin/python3 v3.9
# Version 1.3 changes:
# 2022-09-05 RP Use Debian 11 as primary examplle
# 2022-09-06 RP Removed characters : and @ from NAME
# We need some library stuff
import argparse, ast, datetime, getpass, inspect, logging, io, os, pathlib, pwd
import re, signal, shlex, smtplib, socket, ssl, string, subprocess, sys, syslog, time
from threading import Timer
#from pyasn1_modules import pem, rfc2459
#from pyasn1.codec.der import decoder
try :
from ply import lex, yacc
except ImportError as err :
msg = ('Error 200: Unable to import lex and yacc from ply.\n'\
'\t Reason: {}\n'\
'\t This program uses PLY (Python Lex-Yacc).\n'\
'\t Please install PLY. It may be available to you as a package.\n'\
'\t Use command "python3 -m pip install ply"\n'\
'\t or you can download it from http://www.dabeaz.com/ply/ and\n'\
'\t then install lex.py and yacc.py with your other Python modules.')\
.format(err.args)
print(msg, file=sys.stderr, flush=True)
exit(1)
if sys.version_info[0] >= 4 : pass
elif sys.version_info[0] == 3 and sys.version_info[1] >= 6 : pass
else :
msg = ('Message 210: This program requires Python version 3.6 or later.\n'\
'\t You are using version {}.')\
.format(sys.version.replace('\n',' '))
print(msg, file=sys.stderr, flush=True)
exit(1)
#############################################################################################
# Functions Functions Functions Functions Functions Functions Functions Functions Functions #
#############################################################################################
# Function isempty returns True if a string, list or dictionary is empty. None = empty.
# Makes use of Python wierdness.
def isempty (enumerable) :
if enumerable : return False
else : return True
def isnotempty (enumerable) :
if enumerable : return True
else : return False
def boolean (b) :
if b : return True
else : return False
#############################################################################################
# Function printer calls print to send string to stdout
# If stdout has been disconnected, do nothing
def printer (line) :
if stderr_redirect : return 0
print(line)
#############################################################################################
# Function eprinter calls print to send string to stderr
# If stderr has been disconnected, do nothing
def eprinter (line) :
if stderr_redirect : return 0
print(line, file=sys.stderr, flush=True)
#############################################################################################
#############################################################################################
# Try to find an identifier for the Linux OS
# Returns opensuse, fedora, debian, ... or None
# See http://0pointer.de/blog/projects/os-release for background
def get_OS_id () :
stdout_list, stderr_list = do_command(['uname', '-a']) # -a needed for synology
if stdout_list == None : return None # uname failed
if stderr_list == None : return None
if stderr_list != [] : return None
line = stdout_list[0].lower()
if re.match(r'(?i).*aix.*', line) : return 'aix'
if re.match(r'(?i).*darwin.*', line) : return 'darwin'
if re.match(r'(?i).*freebsd.*', line) : return 'freebsd'
if re.match(r'(?i).*hp-ux.*', line) : return 'hpux'
if re.match(r'(?i).*ipfire.*', line) : return 'ipfire'
if re.match(r'(?i).*mac.*', line) : return 'mac'
if re.match(r'(?i).*netbsd.*', line) : return 'netbsd'
if re.match(r'(?i).*openbsd.*', line) : return 'openbsd'
if re.match(r'(?i).*openindiana.*', line) : return 'openindiana'
if re.match(r'(?i).*synology.*', line) : return 'synology'
if re.match(r'(?i).*linux.*', line) :
try :
with open('/etc/os-release', 'r') as fd :
lines = fd.readlines() # A list of lines, each ending with \n
for line in lines :
m = re.match(r'ID=(.*)$', line)
if m : return m.group(1).lower() # E.g. debian
return None # No ID in os-release
except Exception :
try :
with open('/etc/gentoo-release', 'r') as fd :
return 'gentoo'
except Exception : return None # No *-release
msg = ('Error 620: get_OS_id error: I do not recognize uname result {}\n'\
'\t Continuing ...').format(stdout_list[0])
eprinter(msg) ; logger(msg)
return None # Unknown uname
# Try to find out which non-root user runs the upsd daemon, and
# where the NUT configuration files are placed.
# Returns (user, directory)
def get_NUT_install_params () :
OS_id = get_OS_id() # E.g. debian or None
try :
ud = {'aix': ('nut', '/etc/nut/'), # IBM AIX
'amzn': ('nut', '/etc/ups/'), # Amazon Linux
'arch': ('nut', '/etc/nut/'),
'centos': ('nut', '/etc/ups/'),
'darwin': ('nut', '/etc/nut/'),
'debian': ('nut', '/etc/nut/'),
'fedora': ('nut', '/etc/ups/'), # Includes Scientific Linux
'freebsd': ('uucp', '/usr/local/etc/nut/'), # Includes FreeNAS
'gentoo': ('nut', '/etc/nut/'),
'hpux': ('nut', '/etc/nut/'), # HP-UX ? ?
'ipfire': ('nutmon','/etc/nut/'), # IPFire
'kali': ('nut', '/etc/nut/'), # Similar to Debian
'linuxmint': ('nut', '/etc/nut/'), # Close to Ubuntu
'mac': ('nut', '/etc/nut/'),
'mageia': ('nut', '/etc/nut/'), # Similar to Fedora
'manjaro': ('nut', '/etc/nut/'),
'netbsd': ('nut', '/etc/nut/'),
'ol': ('nut', '/etc/ups/'), # Oracle Linux
'openbsd': ('ups', '/etc/nut/'),
'openindiana': ('nut', '/etc/nut/'),
'opensuse': ('upsd', '/etc/ups/'),
'raspbian': ('nut', '/etc/nut/'),
'rhel': ('nut', '/etc/ups/'),
'slackware': ('nut', '/etc/nut/'),
'sles': ('upsd', '/etc/ups/'), # SuSE Enterprise Linux
'sles_sap': ('upsd', '/etc/ups/'), # SuSE Enterprise Linux
'synology': ('root', '/usr/syno/etc/ups/'),
'ubuntu': ('nut', '/etc/nut/'),
None: ('nut', '/etc/nut/')}[OS_id]
return ud
except Exception : return ('nut', '/etc/nut/') # Most likely configuration
#############################################################################################
# Function ensure_fqups(raw_ups) Given a string which might or might not include
# the group, domain and port, return a string with
# group:name@domain:port completed.
# Intended for use in function read_conf which maintains variable current_group internally
def ensure_fqups (raw_ups) :
host = group_host[current_group] # Save some typing
port = str(group_port[current_group]) # Save some typing
DDlogger(('{}\n'\
+tab+'ensure_fqups ({}) ... type(raw_ups)={}')\
.format(fnl(), raw_ups, type(raw_ups)))
if current_group == None :
msg=("{} Error 220: ensure_fqups ({}): internal error.\n"\
+tab+"Variable current_group has not been defined\n"\
+tab+"Exiting ...").format(blob, raw_ups)
logger(msg); eprinter(msg)
cleanup(); exit(1) # This causes exceptions in PLY
m = re.split("@", raw_ups) # Extract group:name and domain:port
if len(m) == 1 : # We have group:name, domain:port is implied
ml = re.split(":", m[0])
if len(ml) == 1 : # We have name
fq = current_group+':'+ml[0]+'@'+host+':'+port # LOCAL:name@localhost:3493
else :
# Check that ml[0] is the current group
if ml[0] == current_group : pass
else :
msg = ('{} Warning 221: UPS naming inconsistency\n'\
+tab+'Declared name is {} but the currrent group is {}\n'\
+tab+'Continuing ...').format(blob, raw_ups, current_group)
eprinter(msg); logger(msg)
fq = ml[0]+ml[1]+'@'+host+':'+port # group:name@localhost:3493
else : # We have x@y, look at x and y in m[0] and m[1]
ml = re.split(":", m[0])
if len(ml) == 1 : # We have name
fql = current_group+':'+ml[0] # Prefix the group
else :
# Check that ml[0] is the current group
if ml[0] == current_group : pass
else :
msg = ('{} Warning 222: UPS naming inconsistency\n'\
+tab+'Declared name is {} but the currrent group is {}\n'\
+tab+'Continuing ...').format(blob, raw_ups, current_group)
eprinter(msg); logger(msg)
fql = ml[0]+ml[1] # group:name
mr = re.split(":", m[1])
if len(mr) == 1 : # We have domain
# Check that mr[0] is the group's host
if mr[0] == host : pass
else :
msg = ('{} Warning 223: UPS naming inconsistency\n'\
+tab+'Declared name is {} but the currrent host is {}\n'\
+tab+'Continuing ...').format(blob, raw_ups, host)
eprinter(msg); logger(msg)
fqr = mr[0]+port # domain:3493
else :
# Check that mr[0] is the current group's host
if mr[0] == host : pass
else :
msg = ('{} Warning 224: UPS naming inconsistency\n'\
+tab+'Declared name is {} but the currrent host is {}\n'\
+tab+'Continuing ...').format(blob, raw_ups, host)
eprinter(msg); logger(msg)
# Check that mr[1] is the current group's port
if mr[1] == port : pass
else :
msg = ('{} Warning 225: UPS naming inconsistency\n'\
+tab+'Declared name is {} but the currrent port is {}\n'\
+tab+'Continuing ...').format(blob, raw_ups, port)
eprinter(msg); logger(msg)
fqr = mr[0]+mr[1] # domain:port
fq = fql+fqr # group:name@domain:port
DDlogger(('{}\n'\
+tab+'ensure_fqups ({}) => {}')\
.format(fnl(), raw_ups, fq))
return fq
#############################################################################################
# Function pp_ups simplifies the display of a fully qualified UPS if the name is of
# form LOCAL:UPS@localhost:3493
def pp_ups (fqups) :
m = re.split("@|:", fqups) # [group, ups, domain, port]
if len(m) == 4 :
if m[0] == 'LOCAL' : g = ''
else : g = m[0]+':'
if m[2] == 'localhost' : d = ''
else : d = '@'+m[0]
if m[3] == '3493' : dp = d+''
else : dp = '@'+m[2]+':'+m[3]
return g+m[1]+dp
else :
msg=("{} Error 230: pp_ups internal error.\n"\
+tab+"Unable to parse {}\n"\
+tab+"Exiting ...").format(blob, fqups)
logger(msg); eprinter(msg)
cleanup(); exit(1)
#############################################################################################
# Pretty print a socket object. Returns a string.
# Socket may be class socket.socket or ssl.SSLSocket
def pp_sock (s, long=False) :
try : fd = s.fileno() # User gives us a non-exitant socket
except Exception : fd = -1
if s.__class__==ssl.SSLSocket :
lb = lob+lsb; rb = rsb+rob
else :
lb = lsb; rb = rsb
if long == True :
try : IP, port = s.getsockname() # ('127.0.0.1', 401)
except Exception : IP, port = (None, None)
try : peer_IP, peer_port = s.getpeername() # ('127.0.0.1', 38700)
except Exception : peer_IP=None; peer_port = None
try : blocking = s.getblocking() # True
except Exception : blocking = None
try : timeout = s.gettimeout() # 3.0
except Exception : timeout = None
# pp = 'fd={} {}:{}->{}:{} bl={} to={}'\
# .format(fd, IP, port, peer_IP, peer_port, blocking, timeout)
pp = 'fd={} {}:{}->{}:{}'\
.format(fd, IP, port, peer_IP, peer_port)
else :
pp = 'fd={}'.format(fd)
return lb + pp + rb
# Pretty print a string or byte code message.
# max is maximum size of displayd message
# Returns a string. with no trailing newlines
def pp_msg (msg, max=60) :
if isinstance(msg, str) : smsg = msg
else : smsg = msg.decode('utf-8')
s = no_trailing_newlines(smsg)
ellipsis = '...'
u = max - len(ellipsis)
if len(s) > max :
first = s[:u//2] # Use integers for indexing
last = s[-u//2:]
return first + ellipsis + last
else : return s
#############################################################################################
# Read certificate and return as a pretty printed string.
# https://stackoverflow.com/questions/16899247/how-can-i-decode-a-ssl-certificate-using-python
# from pyasn1_modules import pem, rfc2459
# from pyasn1.codec.der import decoder
def pp_PEM (file, long=False) :
regexp = r'^\s*[0-9a-f][0-9a-f]:'
try :
cert_txt = subprocess.check_output(["openssl", "x509", "-text", "-noout", "-in", file])
pp_full = cert_txt.decode('utf-8') # Result is a string
if long : return pp_full # Customer sees everything
else : # Only the first line of the octets gets presented
pp = []; first_octet_line = True
for l in pp_full.split('\n') :
if re.match(regexp,l) : # True if octet line
if first_octet_line : pp.append(l+' ...') ; first_octet_line = False
else : first_octet_line = False
else : pp.append(l) ; first_octet_line = True
return '\n'.join(pp)
except Exception as ex :
msg = ('{} Error 240: pp_PEM unable to pretty print {}\n'\
+tab+'Reason: {}')\
.format(blob, file, ex)
logger(msg); eprinter(msg)
return None
#############################################################################################
# pp_timer returns a pretty printed threading.Timer
def pp_timer (t) :
return '<Timer {} {}s {}>'.format(t.args[0], t.interval, t.name)
def pp_active_timers (dict) :
return [pp_timer(dict[n]) for n in dict]
def pp_timer_list (list) :
if len(list) == 0 : return '[]'
elif len(list) == 1 : return '['+pp_timer(list[0])+']'
else :
timer_list = [pp_timer(t) for t in list]
return '[' + ', '.join(timer_list) + ']'
#############################################################################################
# Function fnl () returns a string with a list of file names and line
# numbers of the point in the main program where it was called.
def fnl () :
line_nums = []
# https://docs.python.org/3/library/inspect.html
current_frame = inspect.currentframe()
all_frames = inspect.getouterframes(current_frame)
for f in all_frames[1:] :
dir_file_name, lineno = f[1], f[2]
file_name = re.split('/',dir_file_name)[-1] # Remove directory. Not used
line_nums.append('{}'.format(lineno))
del f # GC needs help with frames
del current_frame, all_frames # more help for GC
nums = line_nums[1:][::-1] # Avoid tracing fnl, reverse list
return prog_name + '[' + DownArrow.join(nums) + ']'
# Function fnl () returns a string with the file name and line
# number of the point in the main program where it was called.
def fnl_short () :
# https://docs.python.org/3/library/inspect.html
current_frame = inspect.currentframe()
all_frames = inspect.getouterframes(current_frame)
top_frame = all_frames[-1]
dir_file_name, lineno = top_frame[1], top_frame[2]
del current_frame, all_frames, top_frame # GC needs help with frames
file_name = re.split('/',dir_file_name)[-1] # Remove directory
return '{}[{}]'.format(file_name, lineno)
#############################################################################################
# See https://stackoverflow.com/questions/2150739/iso-time-iso-8601-in-python
# date_time_µsec Local time in ISO format 2019-09-09 17:35:53.968428
# Experience shows that one must test m. I don't know what causes this.
# Pythonism: m True means non-empty
def date_time_µsec () :
m = re.match(r'([0-9-]+)[A-Z]([0-9:]+)\.([0-9][0-9][0-9]).*',datetime.datetime.now().isoformat())
if m : return '{} {}.{}'.format(m.group(1), m.group(2), m.group(3))
else : return '{} {}.{}'.format(None, None, None)
# date_time Local date and time in ISO format 2019-09-09 17:35:53
def date_time () :
m = re.match(r'([0-9-]+)[A-Z]([0-9:]+)\..*',datetime.datetime.now().isoformat())
if m : return '{} {}'.format(m.group(1), m.group(2))
else : return '{} {}'.format(None, None)
# date Local day in ISO format 2019-09-09
def date () :
m = re.match(r'([0-9-]+)[A-Z]([0-9:]+)\..*',datetime.datetime.now().isoformat())
if m : return '{}'.format(m.group(1))
else : return '{}'.format(None)
# tod Local time in ISO format 17:35:53
def tod () :
m = re.match(r'([0-9-]+)[A-Z]([0-9:]+)\..*',datetime.datetime.now().isoformat())
if m : return '{}'.format(m.group(2))
else : return '{}'.format(None)
# System time including microseconds 2019-09-09.968428
def time_µsec () :
m = re.match(r'([0-9-]+)[A-Z]([0-9:]+)\.([0-9][0-9][0-9]).*',datetime.datetime.now().isoformat())
if m : return '{}.{}'.format(m.group(2), m.group(3))
else : return '{}.{}'.format(None, None)
# System time in microseconds 968428
def µsec () :
m = re.match(r'([0-9-]+)[A-Z]([0-9:]+)\.([0-9][0-9][0-9]).*',datetime.datetime.now().isoformat())
if m : return '{}'.format(m.group(3))
else : return '{}'.format(None)
#############################################################################################
# Function open_log_file opens a file for logging
# The file owner will be uid, with group gid, e.g. upsd:daemon
# returns tuple (log, log_inode) where
# log_file is the name of the file, e,g, /var/log/NUT.log
# log is a Python class providing log.write(...)
# log_inode is the inode of the log file
def open_log_file (log_file, uid, gid) :
global log_file_open # pylint: disable=global-statement
try :
log = open(log_file, 'a') # Opened for current user, re-open if user change
log_file_open = True
os.chmod(log_file, 0o664)
os.chown(log_file, uid, gid)
return (log, os.stat(log_file).st_ino) # File class and inode number
except FileNotFoundError :
eprinter(('{} Error 250: I cannot find log file {}\n'\
+tab+'Exiting ...').format(blob,log_file))
cleanup(); exit(3)
except PermissionError :
eprinter(('{} Error 260: I cannot open log file {}, permissions error.\n'\
+tab+'Exiting ...').format(blob,log_file))
cleanup(); exit(3)
#############################################################################################
# Utility function logger appends line l to the log file
# provided that the current debug level is greater than or equal
# to d. If d is omitted everything is logged.
# Function logger behaves like function print and automatically adds a \n
# at the end of the line.
# Log file log is kept permanently open in append mode.
# Messages are instantly flushed so log is safely written to disk
# even if we use kill to stop the daemon.
def logger (l, d=0) :
global log, log_inode # pylint: disable=global-statement
if isinstance(d, int) : pass
else:
msg = ('{} Error 270: Internal error\n'\
+tab+'Type error in call to function logger("{}",{})\n'\
+tab+'type({}) = {}\n'\
+tab+'This may be due to writing ",format" instead of ".format"\n'\
+tab+'Exiting ...').format(blob, l, d, d, type(d))
eprinter(msg); cleanup(); exit(1)
# Is the log file available?
if not log_file_open : return 0
# Has logrotate changed the inode of the log file ?
if os.stat(log_file).st_ino == log_inode : new_inode_flag = '' # Marker for new file handle
else :
log.close() # Old file handle dead
# Reopen a file for logging as the user who will run the server
log, log_inode = open_log_file(log_file, os.getuid(), os.getgid()) # Re-opened for current user
new_inode_flag = 'New inode {}. '.format(os.stat(log_file).st_ino)
# And now, the logging action
if debug >= d :
# Friendly prefix for messages to the log file
msg = '{} {} {}\n'.format(tod(), fnl(), new_inode_flag+l)
try :
rc = log.write(msg) # Ensure data recorded on disk in case we use kill
log.flush() # to stop the daemon.
except Exception : rc = -1 # File may have been closed by unexpected exit
return rc # Returns number of characters written
else : return 0
# As logger but for Lex and Yacc
def ylogger (l, y=0) :
global log, log_inode # pylint: disable=global-statement
if debugYacc >= y :
# Is the log file available?
if not log_file_open : return 0
# Has logrotate changed the inode of the log file ?
if os.stat(log_file).st_ino == log_inode : pass
else :
log.close() # Old file handle dead
log, log_inode = open_log_file(log_file, os.getuid(), os.getgid()) # Re-opened for current user
# Friendly prefix for messages to the log file
msg = '{} {} {}\n'.format(tod(), fnl(), l)
try :
rc = log.write(msg) # Ensure data recorded on disk in case we use kill
log.flush() # to stop the daemon.
except Exception : rc = -1 # File may have been closed by unexpected exit
return rc # Returns number of characters written
else : return 0
def Dlogger (l, d=1) : logger(l,d)
def DDlogger (l, d=2) : logger(l,d)
def Ylogger (l, y=1) : ylogger(l,y)
def YYlogger (l, y=2) : ylogger(l,y)
#############################################################################################
# A dictionary indexed by the user's name for the event, giving the corresponding
# table and required value. dict, key = events_decode_dict()[event]
# Add TRIM and TEST
def events_decode_dict () :
return {\
(None,'ALARM') :('ALARMNone', 'ALARM'), ('ALARM',None) :('ALARMNone', None),
(None,'BOOST') :('BOOSTNone', 'BOOST'), ('BOOST',None) :('BOOSTNone', None),
(None,'BYPASS') :('BYPASSNone', 'BYPASS'), ('BYPASS',None) :('BYPASSNone', None),
(None,'CAL') :('CALNone', 'CAL'), ('CAL',None) :('CALNone', None),
(None,'CHRG') :('CHRGNone', 'CHRG'), ('CHRG',None) :('CHRGNone', None),
(None,'DISCHRG') :('DISCHRGNone','DISCHRG'), ('DISCHRG',None) :('DISCHRGNone',None),
(None,'FSD') :('FSDNone', 'FSD'), ('FSD',None) :('FSDNone', None),
(None,'LB') :('LBNone', 'LB'), ('LB',None) :('LBNone', None),
(None,'LB1') :('LB1one', 'LB1'), ('LB1',None) :('LB1None', None),
(None,'LB2') :('LB2None', 'LB2'), ('LB2',None) :('LB2None', None),
(None,'LB3') :('LB3None', 'LB3'), ('LB3',None) :('LB3None', None),
(None,'LS') :('LSNone', 'LS'), ('LS',None) :('LSNone', None),
('COMM','NOCOMM') :('COMMNOCOMM', 'NOCOMM'), ('NOCOMM','COMM') :('COMMNOCOMM', 'COMM'),
(None,'OFF') :('OFFNone', 'OFF'), ('OFF',None) :('OFFNone', None),
('OB','OL') :('OLOB', 'OL'), ('OL','OB') :('OLOB', 'OB'),
(None,'OVER') :('OVERNone', 'OVER'), ('OVER',None) :('OVERNone', None),
(None,'RB') :('RBNone', 'RB'), ('RB',None) :('RBNone', None),
(None,'TEST') :('TESTNone', 'TEST'), ('TEST',None) :('TESTNone', None),
(None,'TICK') :('TICKNone', 'TICK'), ('TICK',None) :('TICKNone', None),
(None,'TOCK') :('TOCKNone', 'TOCK'), ('TOCK',None) :('TOCKNone', None),
(None,'TRIM') :('TRIMNone', 'TRIM'), ('TRIM',None) :('TRIMNone', None)}
# What actions are possible when an event occurs?
def action_keyword_dict () :
return {'cancel_timer':cancel_timer, 'debug_level':set_debug,
'email':emailer, 'email2':printer,
'EPRINT':eprinter, 'NOTIFY':notifier,
'NUTLOG':logger, 'PRINT':printer,
'SETFSD':set_FSD, 'SHELLCMD':do_shellcmd,
'SHUTDOWNCMD':do_shutdown, 'start_timer':start_timer,
'SYSLOG':syslogger, 'WALL':waller}
# A list of all the UPS statuses known
def statuses () :
candidates = [x[1] for x in events_decode_dict()] # Allows duplicates
return list(dict.fromkeys(candidates)) # The python way of removing duplicates
#############################################################################################
# Read configuration file. Returns 0 succeeds, 1 otherwise.
# Places result in global variables
def read_conf(conffile) :
global current_ups, current_group, read_conf_rc # pylint: disable=global-statement
confname = re.split(r'/',conffile)[-1] # E.g. /here/there/ups-mgr.conf => ups-mgr.conf
logger('Reading configuration file from {} ...'.format(confname))
LN = 10000 # Pack lineno and col pos into single integer with this lineno multiplier
current_group = None # GROUP declaration will provide value
current_ups = None # MONITOR declaration will provide value
# Useful regular expressions
# Extract gr, name, domain and port from fqups such as HD:heartbeat@localhost:3493
re_fqups = r'([^:\s]+):([^@\s]+)@([^:\s]+):(\d+)'
# Set up a PLY logging object
logging.basicConfig(
level = logging.DEBUG,
filename = "UPSmon-PLY.log",
filemode = "w",
format = "%(filename)10s:%(lineno)4d:%(message)s"
)
PLYlog = logging.getLogger()
# Helper functions simplify writing of lexer rules
# DD_t assumes t.lineno is of form L*LN + C, L = line number, C = col number
def DD_t (t) :
YYlogger('{}[{},{}] {}'.format(confname,t.lineno//LN,t.lineno%LN, t))
# Attribute lexer.linepos provides lexer position of first character in line
def help (t) : # Single parameter a
ln = t.lineno*LN + (t.lexpos-t.lexer.linepos)
va = lexer.lexmatch.group('a') # Ensure result is always a string
return (ln,va)
def help2 (t) : # Two parameters a and b
ln = t.lineno*LN + (t.lexpos-t.lexer.linepos)
va1 = lexer.lexmatch.group('a') # Ensure result is always a string
va2 = lexer.lexmatch.group('b') # Ensure result is always a string
return (ln,(va1,va2))
# Combined line and column number
def ln (t) : p = t.lineno*LN + (t.lexpos-t.lexer.linepos); return p
# Lexer for the configuration file
# List of token names. This is always required
tokens = ['WHEN', 'WALL', 'USER', 'UPSDUSER', 'TYPE', 'TO', 'TIMEOUT',
'SYSLOG', 'SUBJECT', 'STATUS', 'STARTTIMER', 'SMTPSERVER',
'SHUTDOWNCMD', 'SHELLCMD', 'SETFSD',
'REPORTS', 'RARR', 'QUOTETEXT5', 'QUOTETEXT4',
'QUOTETEXT3', 'QUOTETEXT2','QUOTETEXT1', 'PRINT', 'POWERVAL',
'PORT', 'POLLFREQALERT', 'POLLFREQ', 'PASSWORD', 'NUTLOG',
'NUMBER', 'NOTIFY', 'NAME', 'MONITOR',
'MINSUPPLIES', 'MESSAGE', 'LET', 'IF',
'HOST', 'GROUP', 'FROM', 'EQ', 'EPRINT', 'EMAIL', 'DEBUG',
'COLON', 'CERTFILE', 'CANCELTIMER', 'APCUPSDUSER']
###########################################################################################
# Token specifications
# Token t has attributes t.type, t.value, t.lineno, and t.lexpos.
# A string containing ignored characters (spaces and tabs)
t_ignore = ' \t'
# Track the line numbers. The column number are given by t.lexpos - t.lexer.linepos
def t_newline (t) :
r'\n'
colpos = (t.lexpos - t.lexer.linepos)
t.lexer.linepos = t.lexpos + 1 # Lexer position of first character in next line
t.lexer.lineno += 1
# Functions are matched in order of definition
def t_ignore_COMMENT (t) : r'\#[^\n]*' ; t.lineno = ln (t)
def t_WHEN (t) : r'WHEN' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_WALL (t) : r'WALL' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_USER (t) : r'USER' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_UPSDUSER (t) : r'UPSDUSER' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_TYPE (t) : r'TYPE' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_TIMEOUT (t) : r'TIMEOUT' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_SYSLOG (t) : r'SYSLOG' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_SUBJECT (t) : r'SUBJECT' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_STARTTIMER (t) : r'STARTTIMER' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_SMTPSERVER (t) : r'SMTPSERVER' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_SHUTDOWNCMD (t) : r'SHUTDOWNCMD' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_SHELLCMD (t) : r'SHELLCMD' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_SETFSD (t) : r'SETFSD' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_REPORTS (t) : r'REPORTS' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_RARR (t) : r'->' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_QUOTETEXT5 (t) :
r'⸢(?P<a>[^⸥\r\n]*)⸥'
t.lineno, t.value = help (t) ; DD_t (t) ; return t
def t_QUOTETEXT4 (t) :
r'⎡(?P<a>[^⎦\r\n]*)⎦'
t.lineno, t.value = help (t) ; DD_t (t) ; return t
def t_QUOTETEXT3 (t) :
r'«(?P<a>[^»\r\n]*)»'
t.lineno, t.value = help (t) ; DD_t (t) ; return t
def t_QUOTETEXT2 (t) :
r'"(?P<a>[^\"\r\n]*)"'
t.lineno, t.value = help (t) ; DD_t (t) ; return t
def t_QUOTETEXT1 (t) :
r'\'(?P<a>[^\'\r\n]*)\''
t.lineno, t.value = help (t) ; DD_t (t) ; return t
def t_PRINT (t) : r'PRINT' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_POWERVAL (t) : r'POWERVAL' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_PORT (t) : r'PORT' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_POLLFREQALERT (t) : r'POLLFREQALERT' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_POLLFREQ (t) : r'POLLFREQ' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_PASSWORD (t) : r'PASSWORD' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_NUTLOG (t) : r'NUTLOG' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_NUMBER (t) :
r'(?P<a>[0-9.]+)'
t.lineno, t.value = help (t) ; DD_t (t) ; return t
def t_NOTIFY (t) : r'NOTIFY'; t.lineno = ln (t) ; DD_t (t) ; return t
def t_MONITOR (t) : r'MONITOR'; t.lineno = ln (t) ; DD_t (t) ; return t
def t_MINSUPPLIES (t) : r'MINSUPPLIES'; t.lineno = ln (t) ; DD_t (t) ; return t
def t_MESSAGE (t) : r'MESSAGE' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_LET (t) : r'LET' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_IF (t) : r'IF' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_HOST (t) : r'HOST' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_GROUP (t) : r'GROUP' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_FROM (t) : r'FROM' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_EQ (t) : r'=' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_EPRINT (t) : r'EPRINT' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_EMAIL (t) : r'EMAIL' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_DEBUG (t) : r'DEBUG' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_COLON (t) : r'\:' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_CERTFILE (t) : r'CERTFILE' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_CANCELTIMER (t) : r'CANCELTIMER' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_APCUPSDUSER (t) : r'APCUPSDUSER' ; t.lineno = ln (t) ; DD_t (t) ; return t
# The following tokens are placed low in the list so that keywords will be detected
# as such and not seen as just names.
def t_STATUS (t) : # Created with sorted(list(dict.fromkeys([x[0] for x in D])))
r'None|ALARM|BOOST|BYPASS|CAL|CHRG|NOCOMM|DISCHRG|FSD|LB1|LB2|LB3|LB|LS|COMM|OB|OFF|OL|OVER|RB|TEST|TICK|TOCK|TRIM'
if t.value == 'None' : t.value = None
t.lineno = ln (t) ; DD_t (t) ; return t
def t_TO (t) : r'TO' ; t.lineno = ln (t) ; DD_t (t) ; return t
def t_NAME (t) : # Names for humans, groups, timers, UPS's, messages
# r'(?P<a>[a-zA-Z_][a-zA-Z0-9._%+-:@]*)' Removed : and @
r'(?P<a>[a-zA-Z_][a-zA-Z0-9._%+-]*)'
t.lineno, t.value = help (t) ; DD_t (t) ; return t
# Error handling rule
def t_error(t):
global read_conf_rc # pylint: disable=global-statement
colpos = (t.lexpos - t.lexer.linepos)
msg = "{}[{},{}] Error 280: I have no way of parsing this character: {}"\
.format(confname, t.lineno, colpos, t.value[0])
eprinter(msg); logger(msg)
t.lexer.skip(1)
read_conf_rc = 1 # This configuration not acceptable
###########################################################################################
# Parse rules for the configuration file.
# Constructs an abstract syntax tree to be interpreted later.
def p_configuration (p) :
'configuration : intros groups'
global AST # pylint: disable=global-statement
tag = ('configuration', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
AST = (tag, p[1], p[2])
#YYlogger(('{}\n'\
# +tab+'p_configuration dir(p)=\n'\
# +tab+'{}')\
# .format(fnl(), dir(p)))
def p_intros (p) : # Tuple of introductory declarations
'''intros : intro
| intros intro'''
tag = ('intros', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
if len(p) == 2 : p[0] = (tag, p[1])
else : p[0] = (p[1][:] + (p[2],))
def p_intro (p) : # Returns e.g. [('intro', ('pollfreq', '5')), ('pollfreq', '5'))]
'''intro : smtp
| let
| pollfreqalert
| pollfreq'''
tag = ('intro', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[1])
def p_smtp (p) :
'smtp : SMTPSERVER quotetext PORT number USER quotetext PASSWORD quotetext'
tag = ('smtp', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2], p[4], p[6], p[8])
def p_let (p) :
'let : LET name EQ quotetexts'
tag = ('let', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2], p[4])
def p_number (p) :
'number : NUMBER'
tag = ('number', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[1]) # Returns a string such as '10.5'
def p_pollfreqalert (p) :
'pollfreqalert : POLLFREQALERT number'
tag = ('pollfreqalert', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
def p_pollfreq (p) :
'pollfreq : POLLFREQ number'
tag = ('pollfreq', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
def p_groups (p) :
'''groups : group_element
| groups group_element'''
tag = ('groups', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
if len(p) == 2 : p[0] = (tag, p[1])
else : p[0] = (p[1][:] + (p[2],))
def p_group_element (p) :
'''group_element : group_name
| group_host
| group_port
| certfile
| let
| monitors
| minsupplies
| action_declarations'''
tag = ('group_element', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[1])
def p_group_name (p) :
'group_name : GROUP name'
tag = ('group_name', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
def p_name (p) :
'name : NAME'
tag = ('name', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[1])
def p_group_host (p) :
'group_host : HOST name'
tag = ('group_host', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
def p_group_port (p) :
'group_port : PORT number'
tag = ('group_port', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
def p_certfile (p) :
'''certfile : CERTFILE quotetext
| CERTFILE name'''
tag = ('certfile', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
YYlogger(('{}\n'\
+tab+'p_certfile returns\n'\
+tab+'==> p[0]={}').format(fnl(), p[0]))
def p_monitors (p) :
'''monitors : monitor
| monitors monitor'''
tag = ('monitors', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
if len(p) == 2 : p[0] = (tag, p[1])
else : p[0] = (p[1][:] + (p[2],))
def p_monitor (p) :
'monitor : MONITOR name POWERVAL number user PASSWORD quotetext TYPE name'
tag = ('monitor', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2], p[4], p[5][1], p[7], p[9])
YYlogger(('{}\n'\
+tab+'p_monitor returns\n'\
+tab+'==> p[0]={}').format(fnl(), p[0]))
def p_user (p) :
'''user : UPSDUSER name
| APCUPSDUSER name'''
tag = ('user', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
def p_minsupplies (p) :
'minsupplies : MINSUPPLIES number'
tag = ('minsupplies', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
def p_action_declarations (p) :
'''action_declarations : action_declaration
| action_declarations action_declaration'''
tag = ('action_declarations', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
if len(p) == 2 : p[0] = (tag, p[1])
else : p[0] = (p[1][:] + (p[2],))
def p_action_declaration (p) : # E.g. LOCAL:Eaton@localhost:3493(OL,OB) [(K,T), actions, ...]
'action_declaration : event_key actions'
tag = ('action_declaration', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[1], p[2]) # p[1] is a tuple, p[2] is a list of strings
YYlogger(('{}\n'\
+tab+'p_action_declaration returns\n'\
+tab+'p[0]={}').format(fnl(), p[0]))
def p_event_key (p) :
'''event_key : WHEN name TIMEOUT name COLON
| WHEN name TO name COLON
| WHEN name REPORTS STATUS RARR STATUS COLON'''
tag = ('event_key', p.lineno(2)//LN, p.lineno(2)%LN)
if len(p) == 6 : p[0] = (tag, p[2], 'TO', p[4])
else : p[0] = (tag, p[2], p[4], p[6])
YYlogger(('{}\n'\
+tab+'p_event_key returns\n'\
+tab+'p[0]={}').format(fnl(), p[0]))
YYlogger(('{}\n'\
+tab+'p_event_key p.lineno(3)={} p.lexpos(3)={}')\
.format(fnl(), p.lineno(3), p.lexpos(3)))
def p_actions (p) :
'''actions : action_element
| actions action_element'''
tag = ('actions', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
if len(p) == 2 : p[0] = (tag, p[1])
else : p[0] = (p[1][:] + (p[2],))
def p_action_element (p) :
# Returns :
# ('action_element',c,'start_timer','(\'HB-timer\',30)') where c is the condition
# ('action_element',c,'SETFSD',('quotetexts', ('my-ups1, 'my-ups2',...)
# ('action_element',c,'PRINT',('quotetexts', ('Hello',...))
'''action_element : condition cancel_timer
| condition debug_level
| condition email
| condition start_timer
| condition EPRINT quotetexts
| condition NOTIFY quotetexts
| condition NUTLOG quotetexts
| condition PRINT quotetexts
| condition SETFSD name
| condition SHELLCMD quotetexts
| condition SHUTDOWNCMD quotetexts
| condition SYSLOG quotetexts
| condition WALL quotetexts'''
YYlogger(('{}\n'\
+tab+'p_action_element receives... len(p[:])={} len(p[1])={}\n'\
+tab+'==> p={}').format(fnl(), len(p[:]), len(p[1]), p[:]))
tag = ('action_element', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
# Pick out the quotetexters
if len(p) == 3 : condition = (p[1][1],p[1][2]) ; action_keyword = p[2][0][0] ; action_text = p[2][1]
else : condition = (p[1][1],p[1][2]) ; action_keyword = p[2] ; action_text = p[3]
p[0] = (tag, (condition, action_keyword, action_text))
YYlogger(('{}\n'\
+tab+'p_action_element returns\n'\
+tab+'==> p[0]={}').format(fnl(), p[0]))
def p_condition (p) :
'''condition : IF STATUS RARR STATUS
| empty'''
tag = ('condition', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
if len(p) == 5 : p[0] = (tag, p[2], p[4])
else : p[0] = (tag, None, None)
YYlogger(('{}\n'\
+tab+'p_condition returns\n'\
+tab+'p[0]={}').format(fnl(), p[0]))
def p_quotetexts (p) :
# Reads text strings "bla bla ..." ' more bla ...' ⸢... etcetera ...⸥
# Returns single Python string in tuple ('quotetexts', ('bla bla ...', ' more bla ...', '... etcetera ...'))
# MSGS substitution is done in funtion e
'''quotetexts : quotetext
| name
| quotetexts quotetext
| quotetexts name'''
tag = ('quotetexts', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
if len(p) == 2 : p[0] = (tag, (p[1][1],))
else : p[0] = (tag, p[1][1] + (p[2][1],)) # Tuple concatenation
YYlogger(('{}\n'\
+tab+'p_quotetexts returns\n'\
+tab+'p[0]={}').format(fnl(), p[0]))
def p_quotetext (p) :
# MSGS substitution is done in funtion e
'''quotetext : QUOTETEXT1
| QUOTETEXT2
| QUOTETEXT3
| QUOTETEXT4
| QUOTETEXT5'''
tag = ('quotetext', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[1])
YYlogger(('{}\n'\
+tab+'p_quotetext returns\n'\
+tab+'p[0]={}').format(fnl(), p[0]))
def p_cancel_timer (p) :
'cancel_timer : CANCELTIMER name'
tag = ('cancel_timer', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
def p_debug_level (p) :
'debug_level : DEBUG number'
tag = ('debug_level', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
# Receives p[2] = 'HB-timer, p[3] = 20, returns e.g. ('start_timer',("HB-timer",30))
def p_start_timer (p) :
'start_timer : STARTTIMER name number'
tag = ('start_timer', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, (p[2], p[3]))
def p_email (p) :
'email : EMAIL from to subject content'
tag = ('email', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, (p[2][1], p[3][1], p[4][1], p[5][1]))
YYlogger(('{}\n'\
+tab+'p_email returns\n'\
+tab+'p[0]={}').format(fnl(), p[0]))
def p_from (p) :
'from : FROM quotetext'
tag = ('from', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
YYlogger(('{}\n'\
+tab+'p_from returns\n'\
+tab+'p[0]={}').format(fnl(), p[0]))
def p_to (p) :
'to : TO quotetext'
tag = ('to', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
YYlogger(('{}\n'\
+tab+'p_to returns\n'\
+tab+'p[0]={}').format(fnl(), p[0]))
def p_subject (p) :
'subject : SUBJECT quotetext'
tag = ('subject', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
YYlogger(('{}\n'\
+tab+'p_subject returns\n'\
+tab+'p[0]={}').format(fnl(), p[0]))
def p_content (p) :
'content : MESSAGE quotetexts'
tag = ('content', p.lineno(len(p)-1)//LN, p.lineno(len(p)-1)%LN)
p[0] = (tag, p[2])
YYlogger(('{}\n'\
+tab+'p_content returns\n'\
+tab+'p[0]={}').format(fnl(), p[0]))
def p_empty(p) : # The empty production
'empty :'
pass
def p_error (t) :
global read_conf_rc # pylint: disable=global-statement
# Note: t is a LexToken
# E.g. t.lexpos=377, t.lineno=130000, t.type=POLLFREQALERT, t.value= 5,
# t.lexer.lineno=13, t.lexer.lexpos=392, t.lexer.linepos=377
#print(('\n'\
# +tab+'p_error({}) called ... dir(t.lexer)=\n'\
# +tab+'{}\n'\
# +tab+'t.lexer.lineno={}, t.lexer.lexpos={}, t.glexer.linepos={},'\
# +tab+'t.lexpos={}, t.lineno={}, t.type={}, t.value={}')\
# .format(t, t.lexer, t.lexer.lineno, t.lexer.lexpos, t.lexer.linepos,
# t.lexpos, t.lineno, t.type, t.value))
read_conf_rc = 1 # This configuration not acceptable
if t == None :
msg = '{} Message 290: This configuration file is incomplete or empty. Nothing to do.'\
.format(confname)
logger(msg); eprinter(msg)
else :
msg = ('{}[{},{}] Error 300: Configuration file error\n'\