How Syslog can lose data

From Rainer’s Blog. It looks syslog assumes data sent whenTCP send() was successful by design.

Simulated the behavior and confirmed by running below one in client mode & the other in server mode. When you kill the server process & run it again while client process is running, you’ll see a message lost.

import sys
import SocketServer
import socket
import time

def usage():
    print "%s [client | server]" % sys.argv[0]
    
def server(HOST, PORT):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((HOST, PORT))
    sock.listen(1)
    (conn, sa) = sock.accept()
    try:
        while True:
            msg = conn.recv(8192)
            print "* received '%s'" % msg
            if len(msg) == 0:
                break;
    except socket.error, e:
        print 'Error: %s' % e
    
    conn.close()

def client_connect(HOST, PORT):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect((HOST, PORT))
    except socket.error, e:
        print "Error: %s" % e
        return None
    
    return sock

def client(HOST, PORT):
    sock = None
    i = 0
    while i< 10:
        if sock == None:
            print "connecting..."
            sock = client_connect(HOST, PORT)
        if sock == None:
            print "no connection. sleeping..."
            time.sleep(3)
            continue
        
        data = "* hoge %d" % i
        print "sending %s" % data
        
        try:
            ret = sock.send(data)
            
            print "Sent:     %s, return: %d" % (data, ret)
            i = i + 1
        except socket.error, e:
            print 'Error: %s' % e
            sock.close()
            sock = None
        print "sleeping..."
        time.sleep(1)

    sock.shutdown(socket.SHUT_RDWR)
    sock.close()

def main():
    if len(sys.argv) != 2:
        usage()
        return

    HOST, PORT = "localhost", 9999

    if sys.argv[1].lower() == "server":
        print "running server..."
        server(HOST, PORT)
    else:
        print "running client..."
        client(HOST, PORT)

if __name__ == "__main__":
    main()

Leave a Reply

Your email address will not be published. Required fields are marked *