pythonsocketsgraphite-carbon

Publishing data via socket after connection is aborted


I have a Python (2.7) script which is reading realtime data from a file and publishing it (via network) to a server living on a different computer. This server, in particular, is a Carbon server part of graphite.

The relevant part of the code is as follows:

import socket

CARBON_HOST = 'COMPUTER-NAME'
CARBON-PORT = 2003
CARBON_PATH = 'folder.name.meaurement'

s = socket.socket()
s.connect((CARBON_HOST, CARBON_PORT))

while True:
 if s:
  s.send('%s %s %s\n'%(CARBON_PATH, str(data), int(time.time())))
    time.sleep(WAIT)

where data is the latest entry imported from my file, and time is the usual.

When I switch off the computer COMPUTER-NAME where the Carbon server lives, this error appears:

s.send('%s %s %s\n'%(CARBON_PATH, str(data), int(time.time())))
socket.error: [Errno 10053] An established connection was aborted by the software in your host machine

When I restart the host machine (COMPUTER-NAME), I have to restart the Python script for data to be sent over again.

Is there a way I can tell the socket to pause if it sees it's disconnected, or to keep trying until the connection is open again?


Solution

  • You can't use the same socket after a socket.error exception, the connection is broken. However, you can catch the exception, create a new connection, and use that to send the data.

    About your last question, you can tell your program to keep trying until the data is sent with a while loop. A basic example,

    import socket
    import time
    
    CARBON_HOST = 'COMPUTER-NAME'
    CARBON_PORT = 2003
    CARBON_PATH = 'folder.name.meaurement'
    WAIT = 10
    
    s = socket.socket()
    s.connect((CARBON_HOST, CARBON_PORT))
    data = 'my data'
    
    while True:
        packet = '%s %s %s'%(CARBON_PATH, str(data), int(time.time()))
        while True:
            try:
                s.send(packet)
                break
            except socket.error as e:
                print(e)
                s.close()
                s = socket.socket()
                s.connect_ex((CARBON_HOST, CARBON_PORT))
        time.sleep(WAIT)
    
    s.close()