from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.exc import OperationalError
from sqlalchemy import Column, Integer, String
from sqlalchemy import Sequence
from PluginManager import PluginManager
import os
import sys
import logging
import datetime
import signal


engine = create_engine('sqlite:///test.db', echo=False)
Base = declarative_base()
Session = sessionmaker(bind=engine)

plugin_directory = '../honeypot/plugins/'
threads = []
plugins = []

my_date_time = datetime.datetime
logging.basicConfig(filename='honey.log', level=logging.DEBUG)


class Plugin(Base):
        __tablename__ = 'plugin'

        id = Column(Integer, Sequence('plugin_id_seq'), primary_key=True, nullable=False)
        name = Column(String,nullable=False )
        orm = Column(String, nullable=False)
        description = Column(String, nullable=False)


def _load_plugins():
    #print (sys.executable)
    #print(os.getcwd())
    #print (sys.path)

    try:
        sys.path.insert(0, plugin_directory)
        os.listdir(plugin_directory)

    except OSError:
        print("Plugin folder not found.")
        raise SystemExit(1)

    else:
        for i in os.listdir(plugin_directory):
            filename, ext = os.path.splitext(i)
            if filename == '__init__' or ext != '.py':
                continue
            print "Attempting to load " + filename + ext
            try:
                mod = __import__(filename)
                plugin = mod.Plugin()
                if _port_already_used(plugin):
                    logging.exception(filename + " couldn't be loaded :Time: " + str(my_date_time.now()))
                    print (filename + " not loaded. Port " + plugin.get_port+ " already in use.")
                else:
                    plugins.append(plugin)
                    print ("Plugin loaded: " + filename + ext)
            except Exception:
                logging.exception(filename + " couldn't be loaded " ":Time: " + str(my_date_time.now()))
                print ("Plugin could not be loaded: " + filename + ext)
        sys.path.pop(0)


def _port_already_used(plugin):
    for i in plugins:
        if i.get_port() == plugin.get_port():
            return True
    return False


def _start_manager_threads():
    for plugin in plugins:
        thread = PluginManager(plugin, Session)
        thread.start()
        threads.append(thread)


def _signal_handler(signal, frame):
    for thread in threads:
        thread.stop()
    raise SystemExit(0)


def _add_plugin_table():
    session = Session()
    #for i in plugins:
        #record = Plugin(name = i.)
        #session.add(record)
    #session.commit()
    session.close()


def _create_plugin_tables():
    try:
        Base.metadata.create_all(engine)
    except OperationalError:
        print"Db directory doesn't exist."
        raise SystemExit(1)


def run():

    _load_plugins()

    _add_plugin_table()

    _create_plugin_tables()

    _start_manager_threads()

    # wait for program to be killed
    signal.signal(signal.SIGINT, _signal_handler)
    signal.signal(signal.SIGTERM, _signal_handler)
    signal.pause()


run()

@@ -500,20 +500,8 @@
  = '
-../honeypot/
 plug
@@ -525,17 +525,21 @@
 %5D%0Aplugin
-s
+_list
  = %5B%5D%0A%0Am
@@ -950,83 +950,8 @@
 ():%0A
-    #print (sys.executable)%0A    #print(os.getcwd())%0A    #print (sys.path)%0A%0A
     
@@ -1096,24 +1096,48 @@
 ot found.%22)%0A
+        print(sys.path)%0A
         rais
@@ -1360,46 +1360,37 @@
 int 
-%22Attempting to load %22 + filename + ext
+filename + ext+ %22 loading...%22
 %0A   
@@ -1578,35 +1578,27 @@
 ilename + %22 
-couldn't be
+not
  loaded :Tim
@@ -1775,17 +1775,21 @@
   plugin
-s
+_list
 .append(
@@ -1827,42 +1827,46 @@
 nt (
-%22Plugin loaded: %22 + filename + ext
+filename + ext + %22 successfuly loaded%22
 )%0A  
@@ -1944,19 +1944,11 @@
 + %22 
-couldn't be
+not
  loa
@@ -2017,55 +2017,38 @@
 nt (
-%22Plugin could
+filename + ext + %22
  not 
-be 
 loaded
-: %22 + filename + ext
+%22
 )%0A  
@@ -2114,33 +2114,37 @@
  for i in plugin
-s
+_list
 :%0A        if i.g
@@ -2244,24 +2244,76 @@
 _threads():%0A
+    # start a plugin manager thread for each plugin%0A
     for plug
@@ -2316,33 +2316,37 @@
 plugin in plugin
-s
+_list
 :%0A        thread
@@ -2467,24 +2467,77 @@
 al, frame):%0A
+    # called on ctrl c or kill pid%0A    print(signal)%0A
     for thre
@@ -2581,27 +2581,32 @@
     
-raise SystemExit(0)
+print 'Exiting honeypot'
 %0A%0A%0Ad
@@ -2625,24 +2625,53 @@
 in_table():%0A
+    # add plugin table to db%0A
     session 
@@ -2839,24 +2839,63 @@
 n_tables():%0A
+    # add table to db for each plugin%0A%0A
     try:%0A   
@@ -3313,10 +3313,40 @@
 )%0A%0A%0A
+if __name__ == %22__main__%22:%0A    
 run()
-%0A

Fix tests