Skip to content

Commit

Permalink
Merge pull request #5271 from OrangeDog/patch-1
Browse files Browse the repository at this point in the history
New fac-sever-rewrite.py for Python 3
  • Loading branch information
rgerhards committed Jan 10, 2024
2 parents ea86c9d + f0e5695 commit 4c11c58
Showing 1 changed file with 109 additions and 80 deletions.
189 changes: 109 additions & 80 deletions plugins/external/messagemod/fac-sever-rewrite/fac-sever-rewrite.py
Original file line number Diff line number Diff line change
@@ -1,91 +1,120 @@
#!/usr/bin/env python
#!/usr/bin/env python3

"""A message modification plugin to rewrite message facility and severity.
"""
A message modification plugin to rewrite message facility and severity.
Note: this script must be customized according to your needs. It would
probably be a good idea to add command line options for the most
common cases. Anyone up for that?
Example usage:
Copyright (C) 2014 by Adiscon GmbH
module(load="mmexternal")
action(type="mmexternal"
binary="fac-sever-rewrite.py -s notice"
interface.input="fulljson")
This file is part of rsyslog.
Note: this script should be customized according to your needs.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Copyright (c) 2014-2023 by Adiscon GmbH and James Howe
http://www.apache.org/licenses/LICENSE-2.0
-or-
see COPYING.ASL20 in the source distribution
This file is part of rsyslog.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
import sys
import re
import json
http://www.apache.org/licenses/LICENSE-2.0
-or-
see COPYING.ASL20 in the source distribution
# skeleton config parameters
# currently none

# App logic global variables

def onInit():
""" Do everything that is needed to initialize processing (e.g.
open files, create handles, connect to systems...)
"""


def onReceive(msg):
"""This is the entry point where actual work needs to be done. It receives
the messge from rsyslog and now needs to examine it, do any processing
necessary. The to-be-modified properties (one or many) need to be pushed
back to stdout, in JSON format, with no interim line breaks and a line
break at the end of the JSON. If no field is to be modified, empty
json ("{}") needs to be emitted.
Note that no batching takes place (contrary to the output module skeleton)
and so each message needs to be fully processed (rsyslog will wait for the
reply before the next message is pushed to this module).
"""
#print msg
data = json.loads(msg)
newseverity = int(data["syslogseverity"]) + 1
print json.dumps({'syslogseverity': newseverity})

def onExit():
""" Do everything that is needed to finish processing (e.g.
close files, handles, disconnect from systems...). This is
being called immediately before exiting.
"""
# most often, nothing to do here
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import argparse
import json
import sys
import syslog

args = argparse.Namespace()


def _facility(value) -> int:
try:
return int(value)
except ValueError:
name = 'LOG_' + value.upper()
const = getattr(syslog, name)
# Python's constants are for direct masking,
# shift back to raw syslog value
return const >> 3


def _severity(value) -> int:
try:
return int(value)
except ValueError:
name = 'LOG_' + value.upper()
const = getattr(syslog, name)
return const


def on_init():
"""
Do everything that is needed to initialize processing
(e.g. open files, create handles, connect to systems...)
"""
parser = argparse.ArgumentParser(prog='fac-sever-rewrite.py')
parser.add_argument('-f', '--facility', required=False, type=_facility,
help='Alias or integer of new facility to set')
parser.add_argument('-s', '--severity', required=False, type=_severity,
help='Alias or integer of new severity to set')
parser.parse_args(namespace=args)


def on_receive(msg: dict) -> dict:
"""
This is the entry point where actual work needs to be done. It receives
the message from rsyslog and now needs to examine it, do any processing
necessary. The to-be-modified properties (one or many) need to be pushed
back to stdout, in JSON format, with no interim line breaks and a line
break at the end of the JSON. If no field is to be modified, empty
json ("{}") needs to be emitted.
Note that no batching takes place (contrary to the output module skeleton)
and so each message needs to be fully processed (rsyslog will wait for the
reply before the next message is pushed to this module).
"""
changes = {}
if args.facility is not None:
changes['syslogfacility'] = args.facility
if args.severity is not None:
changes['syslogseverity'] = args.severity
return changes


def on_exit():
"""
Do everything that is needed to finish processing
(e.g. close files, handles, disconnect from systems...).
This is being called immediately before exiting.
"""
pass


def main():
"""
-------------------------------------------------------
This is plumbing that DOES NOT need to be CHANGED
-------------------------------------------------------
"""
on_init()
for line in sys.stdin:
msg = json.loads(line)
changes = on_receive(msg)
print(json.dumps(changes), flush=True)
on_exit()


if __name__ == '__main__':
main()

"""
-------------------------------------------------------
This is plumbing that DOES NOT need to be CHANGED
-------------------------------------------------------
Implementor's note: Python seems to very agressively
buffer stdouot. The end result was that rsyslog does not
receive the script's messages in a timely manner (sometimes
even never, probably due to races). To prevent this, we
flush stdout after we have done processing. This is especially
important once we get to the point where the plugin does
two-way conversations with rsyslog. Do NOT change this!
See also: https://github.com/rsyslog/rsyslog/issues/22
"""
onInit()
keepRunning = 1
while keepRunning == 1:
msg = sys.stdin.readline()
if msg:
msg = msg[:-1] # remove LF
onReceive(msg)
sys.stdout.flush() # very important, Python buffers far too much!
else: # an empty line means stdin has been closed
keepRunning = 0
onExit()
sys.stdout.flush() # very important, Python buffers far too much!

0 comments on commit 4c11c58

Please sign in to comment.