# Path: vespa/node.py
# class Node(PThread):
#     # Overrides threading.Thread.run()
#     def run(self):
#         profiler = cProfile.Profile()
#         try:
#             return profiler.runcall(PThread.run, self)
#         finally:
#             profiler.dump_stats('myprofile-%s.profile' % (self.name))
# 
# Path: vespa/agent.py
# class Agent(Node):
#     def __init__(self, name, host, port, master, run=True):
#         super(Agent, self,).__init__(name, host, port, master, run)
# 
# Path: vespa/agent_connections.py
# class Agent_Connections(Agent):
#     """An agent gathering network links through psutil python module or
#     system lsof command
# 
#     :return: The wrapper
#     :rtype: Node
#     """
# 
#     def __init__(self, name, host, port, master, run=True):
#         # self.proc = None
#         super(Agent_Connections, self,).__init__(name, host, port, master, run)
#         self.backend = self.desc()
#         self.daemonname = "vlc"
# 
#     def launch(self):
#         """Return network connections to orchestrator layer every second using
#         either psutil or lsof
#         """
#         import time
# 
#         while not self.quitting:
#             infos = self.__get_conns()
#             addresses = {}
#             intruders = []
# 
#             for conn in infos:
#                 if conn.remote_address:
#                     addresses[
#                         conn.remote_address[0].replace(
#                             ":",
#                             "").replace(
#                             "f",
#                             "")] = 0
# 
#             for conn in infos:
#                 if conn.remote_address:
#                     addresses[
#                         conn.remote_address[0].replace(
#                             ":",
#                             "").replace(
#                             "f",
#                             "")] += 1
# 
#             for item in addresses:
#                 intruders.append({'ip': item, 'value': addresses[item]})
# 
#             self.sendAlert("ip_connections#%s" % intruders)
#             # debug_info("Intruders: %s" % intruders)
# 
#             time.sleep(1)
# 
#     def _get_conns(self):
#         """Gather psutil connections
# 
#         :return: List of network links
#         :rtype: list
#         """
#         res = []
#         for p in psutil.process_iter():
#             try:
#                 res += p.get_connections(kind='inet')
#             except:
#                 continue
#         return res
# 
#     def _get_conns_lsof(self):
#         """Gather network connections with lsof
# 
#         :return: Dict of network links
#         :rtype: dict
#         """
#         lines = os.popen('lsof -ni').readlines()
# 
#         from subprocess import Popen, PIPE
#         p1 = Popen(['lsof', '-ni'], stdout=PIPE)
#         p2 = Popen(["grep", "LISTEN"], stdin=p1.stdout, stdout=PIPE)
#         output = p2.communicate()[0]
#         cols = ("COMMAND     PID USER   FD   TYPE DEVICE SIZE/OFF"
#                 "NODE NAME").split()
#         res = {}
# 
#         for l in output.split("\n"):
#             d = dict(zip(cols, l.split()))
#             if not d:
#                 continue
#             if d['COMMAND'] not in res:
#                 res[d['COMMAND']] = []
#             res[d['COMMAND']].append(d)
# 
#         return res


import pytest
import unittest
import sys
import os
import SocketServer
import threading
import time
from vespa.node import Node
from vespa.agent import Agent
from vespa.agent_connections import Agent_Connections

class SimpleRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        data = self.request.recv(102400) # token receive
        self.request.send("'%s'EndOfTransmission" % TEST_STRING)
        time.sleep(0.1) # make sure it finishes receiving request before closing
        self.request.close()


def serve_data():
    SocketServer.TCPServer.allow_reuse_address = True
    server = SocketServer.TCPServer(('127.0.0.1', 18081), SimpleRequestHandler)
    http_server_thread = threading.Thread(target=server.handle_request)
    #http_server_thread.setDaemon(True)
    http_server_thread.start()
    return server


@pytest.fixture(scope='module')
def agent_instance(request):
    a = Agent_Connections('testnode', "127.0.0.1", 1340, None, run=False)
    def fin():
        pass
        a.destroy()
    return a


@pytest.fixture(scope='function')
def serve_http(request):
    s = serve_data()

# Path: vespa/node.py
# class Node(PThread):
#     # Overrides threading.Thread.run()
#     def run(self):
#         profiler = cProfile.Profile()
#         try:
#             return profiler.runcall(PThread.run, self)
#         finally:
#             profiler.dump_stats('myprofile-%s.profile' % (self.name))
# 
# Path: vespa/agent.py
# class Agent(Node):
#     def __init__(self, name, host, port, master, run=True):
#         super(Agent, self,).__init__(name, host, port, master, run)
# 
# Path: vespa/agent_connections.py
# class Agent_Connections(Agent):
#     """An agent gathering network links through psutil python module or
#     system lsof command
# 
#     :return: The wrapper
#     :rtype: Node
#     """
# 
#     def __init__(self, name, host, port, master, run=True):
#         # self.proc = None
#         super(Agent_Connections, self,).__init__(name, host, port, master, run)
#         self.backend = self.desc()
#         self.daemonname = "vlc"
# 
#     def launch(self):
#         """Return network connections to orchestrator layer every second using
#         either psutil or lsof
#         """
#         import time
# 
#         while not self.quitting:
#             infos = self.__get_conns()
#             addresses = {}
#             intruders = []
# 
#             for conn in infos:
#                 if conn.remote_address:
#                     addresses[
#                         conn.remote_address[0].replace(
#                             ":",
#                             "").replace(
#                             "f",
#                             "")] = 0
# 
#             for conn in infos:
#                 if conn.remote_address:
#                     addresses[
#                         conn.remote_address[0].replace(
#                             ":",
#                             "").replace(
#                             "f",
#                             "")] += 1
# 
#             for item in addresses:
#                 intruders.append({'ip': item, 'value': addresses[item]})
# 
#             self.sendAlert("ip_connections#%s" % intruders)
#             # debug_info("Intruders: %s" % intruders)
# 
#             time.sleep(1)
# 
#     def _get_conns(self):
#         """Gather psutil connections
# 
#         :return: List of network links
#         :rtype: list
#         """
#         res = []
#         for p in psutil.process_iter():
#             try:
#                 res += p.get_connections(kind='inet')
#             except:
#                 continue
#         return res
# 
#     def _get_conns_lsof(self):
#         """Gather network connections with lsof
# 
#         :return: Dict of network links
#         :rtype: dict
#         """
#         lines = os.popen('lsof -ni').readlines()
# 
#         from subprocess import Popen, PIPE
#         p1 = Popen(['lsof', '-ni'], stdout=PIPE)
#         p2 = Popen(["grep", "LISTEN"], stdin=p1.stdout, stdout=PIPE)
#         output = p2.communicate()[0]
#         cols = ("COMMAND     PID USER   FD   TYPE DEVICE SIZE/OFF"
#                 "NODE NAME").split()
#         res = {}
# 
#         for l in output.split("\n"):
#             d = dict(zip(cols, l.split()))
#             if not d:
#                 continue
#             if d['COMMAND'] not in res:
#                 res[d['COMMAND']] = []
#             res[d['COMMAND']].append(d)
# 
#         return res


# Path: tests/test_agent_connections.py
import pytest
import unittest
import sys
import os
import SocketServer
import threading
import time
from vespa.node import Node
from vespa.agent import Agent
from vespa.agent_connections import Agent_Connections


class SimpleRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        data = self.request.recv(102400) # token receive
        self.request.send("'%s'EndOfTransmission" % TEST_STRING)
        time.sleep(0.1) # make sure it finishes receiving request before closing
        self.request.close()


def serve_data():
    SocketServer.TCPServer.allow_reuse_address = True
    server = SocketServer.TCPServer(('127.0.0.1', 18081), SimpleRequestHandler)
    http_server_thread = threading.Thread(target=server.handle_request)
    #http_server_thread.setDaemon(True)
    http_server_thread.start()
    return server


@pytest.fixture(scope='module')
def agent_instance(request):
    a = Agent_Connections('testnode', "127.0.0.1", 1340, None, run=False)
    def fin():
        pass
        a.destroy()
    return a


@pytest.fixture(scope='function')
def serve_http(request):
    s = serve_data()

    def fin():