socket.py 4.75 KB
Newer Older
1 2 3 4 5
# -*- coding: utf-8 -*-

import time
import socket
from ipaddress import ip_address
6
from collections import deque
7 8 9 10 11 12 13 14 15 16

from .input_base import InputBase

# to remove --> use optioms
DEFAULT_SOCKETSERVER_PORT = 11337
DEFAULT_SOCKETSERVER_LOCATION = 'localhost:' + str(DEFAULT_SOCKETSERVER_PORT)
LOG_FORMAT = ['time', 'srcIp', 'srcPort', 'dstIp', 'dstPort', 'cwnd', 'rwnd', 'sst', 'rtt', 'bw', 'loss']
#at least time & dstPort required
NUMBER_OF_VALUES = len(LOG_FORMAT)

17 18
LOGSERVER_CONNECT_RETRY_TIME = 1 #in s
LOGSERVER_ERROR_TIMEOUT = 0.5 #in s
19 20 21 22 23

class SocketInput(InputBase):
    def __init__(self, options, infoRegistry):
        self.options = options
        self.infoRegistry = infoRegistry
24 25 26 27
        self.__incomeBuffer = deque()
        self.incomeBuffer = deque()
        self.connectionUp = False
        self.socketUp = False
28

29 30 31 32 33 34 35 36 37
        ip, separator, port = self.options.logServer.rpartition(':')
        if(':' not in self.options.logServer or port is ''):
            self.logServerPort = DEFAULT_SOCKETSERVER_PORT
            self.logServerIp = ip_address(socket.gethostbyname(self.options.logServer.strip("[]")))
        else:
            self.logServerPort = int(port)
            self.logServerIp = ip_address(socket.gethostbyname(ip.strip("[]")))
        self.dst = str(self.logServerIp) + ":" + str(self.logServerPort)

38 39 40 41
    def startupCheck(self):
        pass

    def startUp(self):
42
        #TODO: eprint + debug..
43 44 45 46 47 48
        self.createSocket()

        while not self.connectToServer():
            pass

    def createSocket(self):
49 50 51 52 53
        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error:
            print("Failed to create socket")
        else:
54 55 56
            self.socketUp = True
            if(self.options.debug):
                print("Socket created.")
57

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    def connectToServer(self):
        try:
            self.socket.connect((str(self.logServerIp), self.logServerPort))
            self.connectionUp = True
            print("Successfully connected to " + self.dst + "")
            return True
        except socket.error:
            print("Error: Could not connect to " + self.dst + ". Retrying in " + str(LOGSERVER_CONNECT_RETRY_TIME) + "s ...")
            time.sleep(LOGSERVER_CONNECT_RETRY_TIME)
            return False
        else:
            time.sleep(LOGSERVER_CONNECT_RETRY_TIME)
            return False

    def reconnectToServer(self):
        if not self.socketUp:
            self.socket.close()
            self.createSocket()

        while not self.connectToServer():
            pass
79 80

    def tearDown(self):
81
        self.socket.close()
82 83 84
        pass

    def retrieveNewSamples(self):
85 86 87
        """
        Reads data (in blocks) from a socket and adds the received data to an temporaray income buffer.
        """
88

89 90 91 92 93 94 95 96 97 98 99 100 101 102
        self.retrieveDataFromSocket();
        self.processDataFromSocket();

        data = []
        while(True):
            try:
                dataLine = self.incomeBuffer.popleft()
            except IndexError:
                return data
            else:
                data.append(dataLine)


    def retrieveDataFromSocket(self):
103 104 105 106 107 108 109 110 111 112 113
        if(self.connectionUp):
            try:
                data = self.socket.recv(4096)
            except socket.timeout:
                print("Connection timeout.")
                self.socket.close()
                self.socketUp = False
                self.connectionUp = False
                return ""
            except IOError:
                print("Error: Could not retrieve data from " + self.dst)
114
                self.socket.close()
115 116 117
                self.socketUp = False
                self.connectionUp = False
                return ""
118
            else:
119 120 121 122 123 124 125 126 127
                if(len(data) == 0):
                    print("Connection closed by foreign host.")
                    self.socket.close()
                    self.socketUp = False
                    self.connectionUp = False
                else:
                    self.__incomeBuffer.append(data)
        else:
            self.reconnectToServer()
128 129


130
    def processDataFromSocket(self):
131 132
        """Reads data from the income buffer and tries to reassemble splitted data."""
        tmpBuffer = ""
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        try:
            line = self.__incomeBuffer.popleft()
            line = line.decode("UTF-8")
            lines = line.split("\n")
        except IndexError:
            time.sleep(0.00001)
        else:
            for i in lines:
                data = i.split(" ")
                if(tmpBuffer != ""):
                    tmpBuffer += i
                    self.incomeBuffer.append(tmpBuffer)
                    tmpBuffer = ""
                    continue

                if(len(data) < NUMBER_OF_VALUES):
                    tmpBuffer += i
                else:
                    self.incomeBuffer.append(i)