1#!/usr/bin/env python3
2#
3# Copyright (c) 2020 Intel Corporation
4# SPDX-License-Identifier: Apache-2.0
5#
6# Listen syslog UDP packets and verify that we received all of them for
7# testing purposes.
8
9import socket
10import sys
11import re
12
13localPort   = 514
14bufferSize  = 1024
15
16def main(localIP):
17    if ":" in localIP:
18        family = socket.AF_INET6
19    else:
20        family = socket.AF_INET
21
22    UDPServerSocket = socket.socket(family=family,
23                                    type=socket.SOCK_DGRAM)
24
25    UDPServerSocket.bind((localIP, localPort))
26
27    if ":" in localIP:
28        local_str = "[" + localIP + "]:" + str(localPort)
29    else:
30        local_str = localIP + ":" + str(localPort)
31
32    print("syslog UDP server up and listening", local_str)
33
34    recv_count_err = 0
35    recv_count_wrn = 0
36    recv_count_inf = 0
37    recv_count_dbg = 0
38    stopped = -1
39
40    while(True):
41        bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
42
43        message = bytesAddressPair[0]
44        address = bytesAddressPair[1]
45
46        # Format of the message
47        #<135>1 1970-01-01T00:01:03.330000Z :: - - - - net_syslog.main: Debug message
48        items = re.split("\<([0-9]*)\>1 ([TZ\:\.\-0-9]*) ([0-9a-fA-F\:\.]*) ([\w-]) ([\w-]) ([\w-]) ([\w-]) net_syslog\S* (.*)'", format(message))
49
50        if (len(items) > 1):
51            #print("Items:{}".format(items))
52
53            msg_type = re.split("(\S*) message \(\d\)", items[8])
54            if len(msg_type) > 1:
55                if msg_type[1] == "Error":
56                    recv_count_err += 1
57                elif msg_type[1] == "Warning":
58                    recv_count_wrn += 1
59                elif msg_type[1] == "Info":
60                    recv_count_inf += 1
61                elif msg_type[1] == "Debug":
62                    recv_count_dbg += 1
63
64                continue
65
66            stopped_values = re.split("Stopped after (\d) msg", items[8])
67            if len(stopped_values) > 1:
68                stopped = int(stopped_values[1])
69                break
70
71    if recv_count_err == stopped and recv_count_wrn == stopped and \
72       recv_count_inf == stopped and recv_count_dbg == stopped:
73        print("OK")
74        return 0
75
76    print("FAIL")
77    return -1
78
79if __name__ == '__main__':
80    if len(sys.argv) > 1:
81        ret = main(sys.argv[1])
82    else:
83        ret = main('::')
84
85    exit(ret)
86