Esempio n. 1
0
class Master(dict):
    """
    task management and scheduling
    """

    def __init__(self, params_obj: ParamsParser):
        super(Master, self).__init__()
        self._params_obj = params_obj
        self.logger = TaskLogger(self._params_obj.out_dir, 'MAIN-APP').get_logger('Master')
        self._work_dir = self._params_obj.out_dir
        self.server = None
        self.endpoint = 'tcp://{}:{:.0f}'.format(SERVER_HOST, SERVER_PORT)
        self.main_process = os.getpid()

    @property
    def work_dir(self):
        return self._work_dir

    def parser_params(self):
        tmp_dic = defaultdict(list)
        with open(self._params_obj.cmd_conf) as in_handler:
            for name, cpu, mem, relys, cmd in csv.reader(in_handler, delimiter='\t'):
                if name in self:
                    self.logger.error('the cmd name must not be repeated [%s is repeated]' % name)
                    raise KeyError('the cmd name must not be repeated [%s is repeated]' % name)
                self[name] = Agent(worker_id=name, cmd=cmd, master=self, cpu=cpu, mem=mem)
                relys = [i.strip() for i in relys.strip().split(',') if i]
                tmp_dic[name].extend(relys)
            for k, vs in tmp_dic.items():
                if len(vs) == 0:
                    continue
                # async_result = event.AsyncResult()
                k_agent = self[k]
                vs_agents = [self[i] for i in vs]
                # k_agent.add_relys(async_result)
                k_agent.add_relys(*vs_agents)
                # for v_agent in vs_agents:
                #     v_agent.add_relied(async_result)

    def stop(self):
        self.server.close()

    def run(self):
        self.logger.info('Main APP start: [PID %s]' % self.main_process)
        self.server = Server(bind_obj=ServerWorker(self))
        self.logger.info('Server start')
        self.server.start()
        self.parser_params()
        agents = self.values()
        # start all agent
        self.logger.info('Worker Agent start')
        _ = [agent.start() for agent in agents]
        self.logger.info('Agent Monitor start')
        monitor = AgentMonitor(self)
        joinall(agents)
        for agent in agents:
            agent.get_end_signal()
        monitor.is_end = True
        self.logger.info('all workers were completed')
        self.logger.info('Main APP stop: [PID %s]' % self.main_process)
    def get_first_served_server(self):
        """
			Return server to be served first
		"""
        served_server = Server(-1, True, False)
        served_server.departure_time = float('inf')
        for server in self.servers:
            if server.is_busy and server.is_deployed and server.departure_time < served_server.departure_time:
                served_server = server
        return served_server
    def get_first_turned_server(self):
        """
			Return server to be turned on first
		"""
        served_server = Server(-1, True, False)
        served_server.turn_on_time = float('inf')
        for server in self.servers:
            if server.to_be_turned_on and server.turn_on_time < served_server.turn_on_time:
                served_server = server
        return served_server
Esempio n. 4
0
 def __init__(self, configPath):
     self.config = config.load(configPath)
     if self.config.operators:
         self.operators = Operator(self.config.operators)
     if self.config.store:
         self.store = store.get_store(self.config.store)
     if self.config.queue:
         # print("---> 1", self.config.queue)
         self.queue = Queue.make(self.config.queue)
     if self.config.server:
         self.server = Server(self.config.server)
Esempio n. 5
0
 def remove_server(self, server):
     """
     Remove a server from the servers database
     """
     if not self._db.remove(Server(server)):
         print '[!] Unknown server'
     return
Esempio n. 6
0
 def run(self):
     self.logger.info('Main APP start: [PID %s]' % self.main_process)
     self.server = Server(bind_obj=ServerWorker(self))
     self.logger.info('Server start')
     self.server.start()
     self.parser_params()
     agents = self.values()
     # start all agent
     self.logger.info('Worker Agent start')
     _ = [agent.start() for agent in agents]
     self.logger.info('Agent Monitor start')
     monitor = AgentMonitor(self)
     joinall(agents)
     for agent in agents:
         agent.get_end_signal()
     monitor.is_end = True
     self.logger.info('all workers were completed')
     self.logger.info('Main APP stop: [PID %s]' % self.main_process)
Esempio n. 7
0
    def __init__(self):
        self.ip = '127.0.0.1'
        self.port = 4444
        self.botnet = []

        Prompt.__init__(self)
        Server.__init__(self)
        Designer.__init__(self)
        Communicate.__init__(self)
        MainController.__init__(self)

        self.wait = False
        self.ping = False
        self.alive = True
        self.debug = True
        self.activeIP = None
        self.activePort = None
        self.default_to_shell = True
        self.prompt = self.getprompt()
Esempio n. 8
0
class Terminal:
    def __init__(self, url, password):
        self.url = url
        self.password = password
        self.server = Server(url, password)

    def terminal(self, send, cookie):
        command = self.command(send)
        if command == False:
            return self.execute(send, cookie)

    def command(self, send):
        if send == "exit":
            print "\n#> Connection Closet by user."
            sys.exit(2)
        else:
            return False

    def execute(self, cmd, cookie):
        if self.server.beat():
            return json.loads(
                requests.post(self.url,
                              data={
                                  'pass': self.password,
                                  'cmd': cmd
                              },
                              cookies=cookie).text)

    def loop(self):
        server = self.server.connection()
        if server['response']:
            print "#> Conecction Established, Enjoy!\n"
            while True:
                info = self.server.info(server['cookie'])
                send = raw_input(info['server_name'] + "@" + info['user'] +
                                 "[" + info['pwd'].rstrip('\n') + "]" +
                                 info['user_bash'] + ">")
                terminal = self.terminal(send, server['cookie'])
                print terminal['command']
        elif server['response'] == False:
            print "robot@shuffle[~]$> Response: " + server['msg']
        else:
            print "robot@shuffle[~]$> Connection fail."
Esempio n. 9
0
 def process(self, server):
     """
     Process task with a given Vodstok server
     """
     try:
         #print self.alias
         server, alias = self.alias.split('?')
         self.chunk = Server(server).download(alias)
         return (self.chunk is not None)
     except ServerIOError:
         self.chunk = None
         return False
Esempio n. 10
0
def main():
    '''
    The main control flow to run the simulation
    :return: None
    '''

    TOTAL_SERVICE_CHAIN_NUM = 4
    TOTAL_SIM_TIME = 1000
    random.seed(4)

    # step1: create network topology
    t = Topology()
    t.load_network_graph(path='./topology/topology.txt')
    t.create_network_topology()
    for link in t.links.values():
        env.process(link.run())

    paths = cal_shortest_path(t.topology, t.links)

    # step2: initialize servers
    servers = Server.init_servers(t.get_nodes(), t.get_links())

    # step3: create service chains
    service_chains = [
        ServiceChain.random_gen() for _ in range(TOTAL_SERVICE_CHAIN_NUM)
    ]

    # step4: place service chains. single instance... multiple instance...
    for chain in service_chains:
        best_fit(servers, chain)

    # launch server processes
    for server in servers.values():
        server.run()

    # step5: generate a packet pool
    packet_pool = Packet.gen_packet_pool(servers, paths, service_chains)

    # step6 create a packet from the packet pool and  simulate routing process.
    # env.process(flow_generator(packet_pool, servers, t.links))

    # single packet test

    # packet = random.choice(packet_pool)
    # print(packet.routing_path)
    # print(packet.vnf_server_addr)
    # packet.forward()

    # generating traffic flow
    env.process(flow_generator(packet_pool))

    env.run(TOTAL_SIM_TIME)
Esempio n. 11
0
class Feluda:
    def __init__(self, configPath):
        self.config = config.load(configPath)
        if self.config.operators:
            self.operators = Operator(self.config.operators)
        if self.config.store:
            self.store = store.get_store(self.config.store)
        if self.config.queue:
            # print("---> 1", self.config.queue)
            self.queue = Queue.make(self.config.queue)
        if self.config.server:
            self.server = Server(self.config.server)

    def set_endpoints(self, endpoints):
        if self.server:
            for endpoint in endpoints:
                self.server.add_endpoint(endpoint(self))

            self.server.enable_endpoints()
        else:
            raise Exception("Server is not Configured")

    def start(self):
        if self.store:
            self.store.connect()
            self.store.optionally_create_index()

        if self.queue:
            self.queue.connect()

        if self.server:
            self.server.start()

    def start_component(self, component_type: ComponentType):
        if component_type == ComponentType.SERVER and self.server:
            self.server.start()
        elif component_type == ComponentType.STORE and self.store:
            self.store.connect()
            self.store.optionally_create_index()
        elif component_type == ComponentType.QUEUE and self.queue:
            self.queue.connect()
            self.queue.initialize()
        else:
            raise Exception("Unsupported Component Type")

    def get_state(self):
        pass
Esempio n. 12
0
 def add_server(self, server):
     """
     Add a server to the servers database
     """
     _server = Server(server)
     try:
         _version = _server.get_version()
         print '[i] Remote server version is %s' % _version
         _capacity = _server.get_capacity()
         print '[i] Remote server shares %s' % convert_bytes(
             _server.capacity)
         if _server.check():
             _server.set_version(_version)
             _server.set_active(True)
             self._db.add(_server)
             return True
         else:
             return False
     except ServerIOError:
         return False
Esempio n. 13
0
class Terminal:

	def __init__(self,url,password):
		self.url = url
		self.password = password
		self.server = Server(url,password)

	def terminal(self,send,cookie):
		command = self.command(send)
		if command == False:
			return self.execute(send,cookie)

	def command(self,send):
		if send == "exit":
			print "\n#> Connection Closet by user."
			sys.exit(2)
		else:
			return False

	def execute(self,cmd,cookie):
		if self.server.beat():
			return json.loads(requests.post(self.url, data = {'pass': self.password,'cmd': cmd} ,cookies=cookie).text)
		
	def loop(self):
		server = self.server.connection()
		if server['response']:
			print "#> Conecction Established, Enjoy!\n"
			while True:
				info = self.server.info(server['cookie'])
				send = raw_input(info['server_name']+"@"+info['user']+"["+info['pwd'].rstrip('\n')+"]"+info['user_bash']+">")
				terminal = self.terminal(send,server['cookie'])
				print terminal['command']
		elif server['response'] == False:
			print "robot@shuffle[~]$> Response: "+server['msg']
		else:
			print "robot@shuffle[~]$> Connection fail."
Esempio n. 14
0
 def add_server(self, server):
     """
     Add a server to the servers database
     """
     _server = Server(server)
     try:
         _version = _server.get_version()
         print '[i] Remote server version is %s' % _version
         _capacity = _server.get_capacity()
         print '[i] Remote server shares %s' % convert_bytes(_server.capacity)
         if _server.check():
             _server.set_version(_version)
             _server.set_active(True)
             self._db.add(_server)
             return True
         else:
             return False
     except ServerIOError:
         return False
Esempio n. 15
0
    def on_download_file_completed(self, task):
        """
        Called when the target file is fully downloaded.

        This method retrieve the stored data and loop while all the metadata
        have not been retrieved. That means that a file's matadata can be stored
        in many chunks, the same way files are stored in vodstok.
        """
        if self.__state == DownTask.SUMMARY:
            file_content = self.__file.read()
            # Is it an old version of chunk ?
            if (file_content.count('|') == 1):
                filename, self.__chunks = file_content.split('|')
            elif (file_content.count('|') == 2):
                filename, version, self.__chunks = self.__file.read().split(
                    '|')
                # Check version
                # If version is greater than our version, raise an error.
                if VersionStr(version) > Settings.version:
                    raise VersionError()
                if filename == 'metadata':
                    self.__file = MemoryStream('', key=self.__key)
                    self.__task = DownloadFileTask(self,
                                                   self.__chunks.split(','),
                                                   self.__file)
                else:
                    self.__state = DownTask.RECVING
                    self.filename = clean_filename(
                        os.path.join(self.__dst_prefix, filename))
                    self.__file = FileStream(open(self.filename, 'wb'),
                                             key=self.__key)
                    self.__task = DownloadFileTask(self,
                                                   self.__chunks.split(','),
                                                   self.__file)
                if self.__manager is not None:
                    self.__manager.queue_task(self.__task)
        elif self.__state == DownTask.RECVING:
            self.__state = DownTask.DONE
            self.__file.close()
            if self.__manager is not None:
                # notify manager of new servers
                for chunk in self.__chunks.split(','):
                    server, alias = chunk.split('?')
                    self.__manager.on_server_discovered(Server(server))
                self.__manager.on_task_done(self)
    def __init__(self, mode, lambd, mu, theta, servers_count,
                 core_servers_count, L, H, simulation_time, max_queue_size,
                 is_debug):
        self.lambd = lambd
        self.mu = mu
        self.theta = theta
        self.servers_count = int(servers_count)
        self.core_servers_count = int(core_servers_count)
        self.L = int(L)
        self.H = int(H)
        self.simulation_time = simulation_time
        self.is_debug = is_debug
        self.auto_continue = not self.is_debug
        self.mode = mode

        self.flow = Flow(lambd, mu, is_debug)
        self.queue = Queue(int(max_queue_size), is_debug)

        self.generated_request = Request(-1, 0, 0, 0)

        self.system_state = States.IDLE
        self.prev_system_state = States.IDLE

        self.served_count = 0
        self.served_sum_w = 0
        self.served_sum_wq = 0

        self.servers = []
        self.generated_requests = []

        self.time = 0
        self.prev_time = 0
        self.up_down_time = 0
        self.prev_up_down_time = 0

        self.up_down_count = 0
        self.up_down_mean = 0

        self.state_time = dict.fromkeys(States.get_States_list(States), 0)
        self.state_count = dict.fromkeys(States.get_States_list(States), 0)

        for i in range(int(servers_count)):
            self.servers.append(
                Server(i, True if i < int(core_servers_count) else False,
                       is_debug))
Esempio n. 17
0
 def __init__(self, homedir):
     # try to load our database
     self._db = os.path.join(homedir, 'servers')
     self.version = Settings.version
     if os.path.isdir(homedir):
         if os.path.isfile(self._db):
             database = open(self._db, 'rb')
             try:
                 version, servers = pickle.load(database)
                 self.servers = []
                 for server in servers:
                     self.servers.append(Server.unserialize(server))
                 database.close()
             except:
                 self.servers = []
                 self.sync()
         else:
             self.servers = []
             self.sync()
     else:
         os.mkdir(homedir)
         self.servers = []
         self.sync()
Esempio n. 18
0
 def __init__(self, homedir):
     # try to load our database
     self._db = os.path.join(homedir, 'servers')
     self.version = Settings.version
     if os.path.isdir(homedir):
         if os.path.isfile(self._db):
             database = open(self._db, 'rb')
             try:
                 version, servers = pickle.load(database)
                 self.servers = []
                 for server in servers:
                     self.servers.append(Server.unserialize(server))
                 database.close()
             except:
                 self.servers = []
                 self.sync()
         else:
             self.servers = []
             self.sync()
     else:
         os.mkdir(homedir)
         self.servers = []
         self.sync()
def test_failed_greedy_resource_allocation():
    # Exception: Resource allocation for a task is infeasible, model solution is Infeasible.
    # The task setting is {'name': 'Foreknowledge Task 10',
    # 'storage': 30, 'computation': 20, 'results data': 9, 'deadline': 17.0, 'value': 17.62}
    # and the server setting has available bandwidth of 34 and available computation of 16 (storage: 40)

    task = ElasticTask('test task',
                       required_storage=30,
                       required_computation=20,
                       required_results_data=9,
                       deadline=17,
                       value=17.62)
    server = Server('test server',
                    storage_capacity=50,
                    computation_capacity=50,
                    bandwidth_capacity=50)
    server.available_storage = 40
    server.available_computation = 16
    server.available_bandwidth = 34

    print(server.can_run(task))

    resource_allocation = SumPercentage()
    _, _, _ = resource_allocation.allocate(task, server)
Esempio n. 20
0
 def test_server(self, url):
     """
     Test a remote server to check if it is a valid vodstok storage server
     """
     return Server(url).check()
Esempio n. 21
0
import webbrowser
from core.server import Server

HOST = "localhost"
PORT = 8081
server = Server(HOST, PORT)
webbrowser.open("http://{}:{}".format(HOST, PORT))
server.start()
Esempio n. 22
0
  \__\___| .__/ |_|    \__, |\_____|_| |_|\__,_|\__|
         | |______      __/ |                       
         |_|______|    |___/  

 %s%s
%s''' % (red, green, config['version'], end))

parser = argparse.ArgumentParser()
parser.add_argument('-ip',
                    '--ip_address',
                    help='IP address to set the connection',
                    dest='ip')
parser.add_argument('-p',
                    '--port',
                    help='Port to set the connection',
                    dest='port')
args = parser.parse_args()

ip_address = args.ip
port = args.port

if ip_address and port:
    try:
        server = Server(str(ip_address), int(port))
        server.server_connection()

    except Exception as identifier:
        print(''' %s %s''' % (error, identifier))
else:
    print(''' %s Error: Set ip address server and a port   ''' % (error))
Esempio n. 23
0
                        default=8080,
                        help="server port",
                        dest="port")

    return parser.parse_args()


if __name__ == "__main__":
    type, port = attrgetter("type", "port")(parse_args())
    host = "localhost"

    def close_after_sigint(resource):
        def signal_handler(sig, frame):
            print("You pressed Ctrl+C!")
            resource.terminate()
            os.kill(os.getpid(), signal.SIGKILL)

        signal.signal(signal.SIGINT, signal_handler)

    if type == ApplicationType.SERVER:
        server = Server()
        server.serve(host, port)
        close_after_sigint(server)
        server.wait()
    elif type == ApplicationType.CLIENT_CLI:
        client = CliClient(Client(), host, port)
        client.start()
    elif type == ApplicationType.CLIENT_GUI:
        client = GuiClient(Client(), host, port)
        client.start()
Esempio n. 24
0
from core.server import Server

if __name__ == "__main__":
    s = Server()
    s.play_a_game()
Esempio n. 25
0
        print("ERROR: Missing path to config file.")
        sys.exit(1)


    config = ProjectConfig(args.config)
    config.parse()

    print("=" * 33 + " CONFIGURATION " + "=" * 32)
    print("REPOSITORY: " + config.get_repository())
    print("BRANCH: " + config.get_repository_branch())
    print("PROJECT ROOT: " + config.get_project_root_path())
    print("WWW DIRECTORY: " + config.get_project_www_path())
    print("COMPOSE PATH: " + config.get_project_compose_path())

    project = Project(config)
    server = Server(config)
    print()

    print("=" * 31 + " STOPPING PROJECT " + "=" * 31)
    server.stop()
    print()

    print("=" * 31 + " CREATING PROJECT " + "=" * 31)
    project.create_project()
    print()

    print("=" * 31 + " CLONING PROJECT " + "=" * 32)
    project.clone_repository()
    print()

    print("=" * 30 + " CREATING .ENV FILE " + "=" * 30)
Esempio n. 26
0
                        help="run as server")
    parser.add_argument("-u",
                        "--udp",
                        action="store_true",
                        help="use UDP socket (default is TCP)")
    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        help="set verbosity mode")
    args = parser.parse_args()

    if args.udp:
        protocol = 'udp'
    else:
        protocol = 'tcp'

    if args.server:

        server = Server(hostname=args.hostname,
                        protocol=protocol,
                        port=args.port,
                        max_conn=args.maxconn)

        server.start()

    else:
        screen = curses.initscr()

        client = Client(args.hostname, protocol, args.port)
        client.connect()
Esempio n. 27
0
	def start_server(self):
		#self.__load_ssl__()	
		server = Server();
		server.start();
Esempio n. 28
0
from sys import argv

from core.server import Server

if __name__ == '__main__':
    serv = Server(argv[1]) if len(argv) > 1 else Server()
    serv.run()
Esempio n. 29
0
class ServerWin(wx.Frame):
    def __init__(self,
                 parent=None,
                 id=-1,
                 title='PypMsg: Main Window',
                 show=False):
        self.clients = []
        #self.server = Server(self.reloadMessages)
        self.server = Server()
        self.scanner = Scanner(Scanner.SERVER)
        self.scanner.listen()
        self.atchQueue = Queue.Queue()

        wx.Frame.__init__(self, parent, id, title, size=(600, 400))
        wx.EVT_CLOSE(self, self.OnClose)

        #panel = wx.Panel(self, -1)
        splitter = wx.SplitterWindow(self)
        leftPanel = wx.Panel(splitter)
        rightPanel = wx.Panel(splitter)

        self.msgList = lists.PListCtrl(leftPanel)
        self.msgList.InsertColumn(0, 'User Name', width=100)
        self.msgList.InsertColumn(2, 'Message')
        self.msgList.InsertColumn(1, 'Address', width=80)
        self.msgList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.showFileList)
        self.msgList.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.showMessage)

        #ipAddrCtrl = wx.StaticText(leftPanel, label='My IP Address: ')

        msgVbox = wx.BoxSizer(wx.VERTICAL)
        #msgVbox.Add(ipAddrCtrl, 0, wx.EXPAND)
        msgVbox.Add(self.msgList, 1, wx.EXPAND | wx.TOP, 10)

        self.filList = wx.ListCtrl(rightPanel, style=wx.LC_LIST)
        self.filList.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.downloadAttachment)
        msgBtn = wx.Button(rightPanel, label='&New Message')
        msgBtn.Bind(wx.EVT_BUTTON, self.newMessageWin)
        relBtn = wx.Button(rightPanel, label="&Refresh")
        relBtn.Bind(wx.EVT_BUTTON, self.reloadMessages)
        clrBtn = wx.Button(rightPanel, label="&Clear")
        clrBtn.Bind(wx.EVT_BUTTON, self.clearMessages)

        btnVbox = wx.BoxSizer(wx.VERTICAL)
        btnVbox.Add(
            wx.StaticText(rightPanel,
                          label='Attachments:\n(Double-Click to download)'), 0,
            wx.TOP)
        btnVbox.Add(self.filList, 1, wx.EXPAND)
        btnVbox.Add(msgBtn, 0, wx.EXPAND | wx.TOP, 10)
        btnVbox.Add(relBtn, 0, wx.EXPAND | wx.TOP, 10)
        btnVbox.Add(clrBtn, 0, wx.EXPAND | wx.TOP, 10)

        leftPanel.SetSizer(msgVbox)
        rightPanel.SetSizer(btnVbox)

        splitter.SplitVertically(leftPanel, rightPanel, -150)

        if not self.server.startServing():
            wx.MessageDialog(
                None,
                'An Instance of PypMsg is already running. Please close that before opening a new one. \
The current version of PypMsg does not support multiple-instances. Thank you.',
                'Already Running',
                wx.OK | wx.ICON_ERROR | wx.CENTRE).ShowModal()
            raise SystemExit(1)

        self.reloadMessages()

        if show:
            self.Show()

    def addAttachment(self, atch):
        self.server.sentAttachments[atch[0]] = atch[1]

    def downloadAttachment(self, event):
        loc = wx.DirSelector(message='Select location to save attachment',
                             parent=self)
        if not loc:
            return
        downloadStatus = self.server.downloadAttachment(
            self.msgList.GetNextSelected(-1), event.GetIndex(), loc,
            self.downloadComplete)

    def downloadComplete(self, atch, downloadStatus):
        if downloadStatus[:5] != 'ERROR':
            wx.MessageDialog(None, atch + ': ' + downloadStatus, 'Download',
                             wx.OK | wx.ICON_INFORMATION
                             | wx.CENTRE).ShowModal()
        else:
            self.server
            wx.MessageDialog(None, atch + ': ' + downloadStatus, 'Attachment',
                             wx.OK | wx.ICON_ERROR | wx.CENTRE).ShowModal()

    def OnClose(self, event):
        self.server.stopServing()
        self.Destroy()

    def clearMessages(self, evt=None):
        self.msgList.DeleteAllItems()
        self.filList.DeleteAllItems()
        self.server.clearMessageQueue()

    def reloadMessages(self, evt=None):
        '''Currently removing all the messages in the list and repopulating it.
        This method gets really slow with large nos of messages.
        Remedy:
            1. Limit the no. of messages to may be 100?
            2. Handle large no. of messages through some kind of optimisations
            3. Eliminate this system, everytime reload is called, only the new
            messages shoule be appended to the list.
        '''
        self.filList.DeleteAllItems()
        self.msgList.DeleteAllItems()
        for (uname, addr, msg) in [(rec['USER'], rec['host'], rec['MSG'])
                                   for rec in self.server.msgQue]:
            self.msgList.Append([uname, addr, msg])
        #arch = self.server.msgQue[-1]
        #self.msgList.Append([arch['host'], arch['MSG']])
        print 'reloading messages done'

    def newMessageWin(self, event=None):
        self.clients.append(
            ClientWin(reportAttachment=self.addAttachment,
                      parent=self,
                      show=True))

    def showFileList(self, event=None):
        self.filList.DeleteAllItems()
        for uid, atch in self.server.msgQue[event.GetIndex()]['atchs']:
            self.filList.Append([atch])

    def showMessage(self, event=None):
        message = self.server.msgQue[event.GetIndex()]['MSG']
        display = '''From: %(USER)s
Address: %(host)s
Message:
%(MSG)s''' % self.server.msgQue[event.GetIndex()]
        wx.MessageDialog(None, display, "Details",
                         wx.OK | wx.ICON_INFORMATION | wx.CENTRE).ShowModal()
        return
import os
import signal
from core.server import Server
import sqlite3
import settings


def setup_db():
    if not os.path.isfile(settings.db_name):
        conn = sqlite3.connect(settings.db_name)
        with open('createdb.sql', 'r') as f:
            conn.executescript(f.read())
        conn.commit()
        conn.close()


if __name__ == "__main__":
    try:
        port = int(sys.argv[1])
        assert port >= 1 and port <= 65536, 'port number can only between 1 and 65536'
    except (ValueError, IndexError):
        print('Usage: {} [Port]'.format(sys.argv[0]), file=sys.stderr)
        exit(1)

    setup_db()

    server = Server('localhost', port)
    signal.signal(signal.SIGINT, lambda signal, frame: server.stop())
    signal.signal(signal.SIGTERM, lambda signal, frame: server.stop())
    server.run()
Esempio n. 31
0
    def __init__(self, parent=None, id=-1, title="PypMsg: Main Window", show=False):
        self.clients = []
        # self.server = Server(self.reloadMessages)
        self.server = Server()
        self.scanner = Scanner(Scanner.SERVER)
        self.scanner.listen()
        self.atchQueue = Queue.Queue()

        wx.Frame.__init__(self, parent, id, title, size=(600, 400))
        wx.EVT_CLOSE(self, self.OnClose)

        # panel = wx.Panel(self, -1)
        splitter = wx.SplitterWindow(self)
        leftPanel = wx.Panel(splitter)
        rightPanel = wx.Panel(splitter)

        self.msgList = lists.PListCtrl(leftPanel)
        self.msgList.InsertColumn(0, "User Name", width=100)
        self.msgList.InsertColumn(2, "Message")
        self.msgList.InsertColumn(1, "Address", width=80)
        self.msgList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.showFileList)
        self.msgList.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.showMessage)

        # ipAddrCtrl = wx.StaticText(leftPanel, label='My IP Address: ')

        msgVbox = wx.BoxSizer(wx.VERTICAL)
        # msgVbox.Add(ipAddrCtrl, 0, wx.EXPAND)
        msgVbox.Add(self.msgList, 1, wx.EXPAND | wx.TOP, 10)

        self.filList = wx.ListCtrl(rightPanel, style=wx.LC_LIST)
        self.filList.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.downloadAttachment)
        msgBtn = wx.Button(rightPanel, label="&New Message")
        msgBtn.Bind(wx.EVT_BUTTON, self.newMessageWin)
        relBtn = wx.Button(rightPanel, label="&Refresh")
        relBtn.Bind(wx.EVT_BUTTON, self.reloadMessages)
        clrBtn = wx.Button(rightPanel, label="&Clear")
        clrBtn.Bind(wx.EVT_BUTTON, self.clearMessages)

        btnVbox = wx.BoxSizer(wx.VERTICAL)
        btnVbox.Add(wx.StaticText(rightPanel, label="Attachments:\n(Double-Click to download)"), 0, wx.TOP)
        btnVbox.Add(self.filList, 1, wx.EXPAND)
        btnVbox.Add(msgBtn, 0, wx.EXPAND | wx.TOP, 10)
        btnVbox.Add(relBtn, 0, wx.EXPAND | wx.TOP, 10)
        btnVbox.Add(clrBtn, 0, wx.EXPAND | wx.TOP, 10)

        leftPanel.SetSizer(msgVbox)
        rightPanel.SetSizer(btnVbox)

        splitter.SplitVertically(leftPanel, rightPanel, -150)

        if not self.server.startServing():
            wx.MessageDialog(
                None,
                "An Instance of PypMsg is already running. Please close that before opening a new one. \
The current version of PypMsg does not support multiple-instances. Thank you.",
                "Already Running",
                wx.OK | wx.ICON_ERROR | wx.CENTRE,
            ).ShowModal()
            raise SystemExit(1)

        self.reloadMessages()

        if show:
            self.Show()
Esempio n. 32
0
	def __init__(self,url,password):
		self.url = url
		self.password = password
		self.server = Server(url,password)
Esempio n. 33
0
    def __init__(self,
                 parent=None,
                 id=-1,
                 title='PypMsg: Main Window',
                 show=False):
        self.clients = []
        #self.server = Server(self.reloadMessages)
        self.server = Server()
        self.scanner = Scanner(Scanner.SERVER)
        self.scanner.listen()
        self.atchQueue = Queue.Queue()

        wx.Frame.__init__(self, parent, id, title, size=(600, 400))
        wx.EVT_CLOSE(self, self.OnClose)

        #panel = wx.Panel(self, -1)
        splitter = wx.SplitterWindow(self)
        leftPanel = wx.Panel(splitter)
        rightPanel = wx.Panel(splitter)

        self.msgList = lists.PListCtrl(leftPanel)
        self.msgList.InsertColumn(0, 'User Name', width=100)
        self.msgList.InsertColumn(2, 'Message')
        self.msgList.InsertColumn(1, 'Address', width=80)
        self.msgList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.showFileList)
        self.msgList.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.showMessage)

        #ipAddrCtrl = wx.StaticText(leftPanel, label='My IP Address: ')

        msgVbox = wx.BoxSizer(wx.VERTICAL)
        #msgVbox.Add(ipAddrCtrl, 0, wx.EXPAND)
        msgVbox.Add(self.msgList, 1, wx.EXPAND | wx.TOP, 10)

        self.filList = wx.ListCtrl(rightPanel, style=wx.LC_LIST)
        self.filList.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.downloadAttachment)
        msgBtn = wx.Button(rightPanel, label='&New Message')
        msgBtn.Bind(wx.EVT_BUTTON, self.newMessageWin)
        relBtn = wx.Button(rightPanel, label="&Refresh")
        relBtn.Bind(wx.EVT_BUTTON, self.reloadMessages)
        clrBtn = wx.Button(rightPanel, label="&Clear")
        clrBtn.Bind(wx.EVT_BUTTON, self.clearMessages)

        btnVbox = wx.BoxSizer(wx.VERTICAL)
        btnVbox.Add(
            wx.StaticText(rightPanel,
                          label='Attachments:\n(Double-Click to download)'), 0,
            wx.TOP)
        btnVbox.Add(self.filList, 1, wx.EXPAND)
        btnVbox.Add(msgBtn, 0, wx.EXPAND | wx.TOP, 10)
        btnVbox.Add(relBtn, 0, wx.EXPAND | wx.TOP, 10)
        btnVbox.Add(clrBtn, 0, wx.EXPAND | wx.TOP, 10)

        leftPanel.SetSizer(msgVbox)
        rightPanel.SetSizer(btnVbox)

        splitter.SplitVertically(leftPanel, rightPanel, -150)

        if not self.server.startServing():
            wx.MessageDialog(
                None,
                'An Instance of PypMsg is already running. Please close that before opening a new one. \
The current version of PypMsg does not support multiple-instances. Thank you.',
                'Already Running',
                wx.OK | wx.ICON_ERROR | wx.CENTRE).ShowModal()
            raise SystemExit(1)

        self.reloadMessages()

        if show:
            self.Show()
Esempio n. 34
0
#!/usr/bin/python

import sys

HOSTNAME = '127.0.0.1'
PORT = 8080

def check_python_version():
  if sys.version_info < (2, 6, 0):
    print 'Error: Python 2.6 or higher is required!'
    sys.exit(1)

if __name__ == '__main__':
  check_python_version()

  from core.handler import Handler
  from core.server import Server

  server = Server((HOSTNAME, PORT), Handler)
  print 'Server is running - open your web browser to http://{0}:{1}'.format(HOSTNAME, PORT)

  try:
    server.serve_forever()
  except KeyboardInterrupt:
    pass

  server.server_close()
Esempio n. 35
0
 def __init__(self, url, password):
     self.url = url
     self.password = password
     self.server = Server(url, password)
Esempio n. 36
0
import sys

from core.server import Server
from core.channel import Channel

server = Server()
channel = Channel(server)
if sys.argv[1] == "server":
    server.start_server()
elif sys.argv[1] == "channel":
    channel.setup_channel()
Esempio n. 37
0
class ServerWin(wx.Frame):
    def __init__(self, parent=None, id=-1, title="PypMsg: Main Window", show=False):
        self.clients = []
        # self.server = Server(self.reloadMessages)
        self.server = Server()
        self.scanner = Scanner(Scanner.SERVER)
        self.scanner.listen()
        self.atchQueue = Queue.Queue()

        wx.Frame.__init__(self, parent, id, title, size=(600, 400))
        wx.EVT_CLOSE(self, self.OnClose)

        # panel = wx.Panel(self, -1)
        splitter = wx.SplitterWindow(self)
        leftPanel = wx.Panel(splitter)
        rightPanel = wx.Panel(splitter)

        self.msgList = lists.PListCtrl(leftPanel)
        self.msgList.InsertColumn(0, "User Name", width=100)
        self.msgList.InsertColumn(2, "Message")
        self.msgList.InsertColumn(1, "Address", width=80)
        self.msgList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.showFileList)
        self.msgList.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.showMessage)

        # ipAddrCtrl = wx.StaticText(leftPanel, label='My IP Address: ')

        msgVbox = wx.BoxSizer(wx.VERTICAL)
        # msgVbox.Add(ipAddrCtrl, 0, wx.EXPAND)
        msgVbox.Add(self.msgList, 1, wx.EXPAND | wx.TOP, 10)

        self.filList = wx.ListCtrl(rightPanel, style=wx.LC_LIST)
        self.filList.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.downloadAttachment)
        msgBtn = wx.Button(rightPanel, label="&New Message")
        msgBtn.Bind(wx.EVT_BUTTON, self.newMessageWin)
        relBtn = wx.Button(rightPanel, label="&Refresh")
        relBtn.Bind(wx.EVT_BUTTON, self.reloadMessages)
        clrBtn = wx.Button(rightPanel, label="&Clear")
        clrBtn.Bind(wx.EVT_BUTTON, self.clearMessages)

        btnVbox = wx.BoxSizer(wx.VERTICAL)
        btnVbox.Add(wx.StaticText(rightPanel, label="Attachments:\n(Double-Click to download)"), 0, wx.TOP)
        btnVbox.Add(self.filList, 1, wx.EXPAND)
        btnVbox.Add(msgBtn, 0, wx.EXPAND | wx.TOP, 10)
        btnVbox.Add(relBtn, 0, wx.EXPAND | wx.TOP, 10)
        btnVbox.Add(clrBtn, 0, wx.EXPAND | wx.TOP, 10)

        leftPanel.SetSizer(msgVbox)
        rightPanel.SetSizer(btnVbox)

        splitter.SplitVertically(leftPanel, rightPanel, -150)

        if not self.server.startServing():
            wx.MessageDialog(
                None,
                "An Instance of PypMsg is already running. Please close that before opening a new one. \
The current version of PypMsg does not support multiple-instances. Thank you.",
                "Already Running",
                wx.OK | wx.ICON_ERROR | wx.CENTRE,
            ).ShowModal()
            raise SystemExit(1)

        self.reloadMessages()

        if show:
            self.Show()

    def addAttachment(self, atch):
        self.server.sentAttachments[atch[0]] = atch[1]

    def downloadAttachment(self, event):
        loc = wx.DirSelector(message="Select location to save attachment", parent=self)
        if not loc:
            return
        downloadStatus = self.server.downloadAttachment(
            self.msgList.GetNextSelected(-1), event.GetIndex(), loc, self.downloadComplete
        )

    def downloadComplete(self, atch, downloadStatus):
        if downloadStatus[:5] != "ERROR":
            wx.MessageDialog(
                None, atch + ": " + downloadStatus, "Download", wx.OK | wx.ICON_INFORMATION | wx.CENTRE
            ).ShowModal()
        else:
            self.server
            wx.MessageDialog(
                None, atch + ": " + downloadStatus, "Attachment", wx.OK | wx.ICON_ERROR | wx.CENTRE
            ).ShowModal()

    def OnClose(self, event):
        self.server.stopServing()
        self.Destroy()

    def clearMessages(self, evt=None):
        self.msgList.DeleteAllItems()
        self.filList.DeleteAllItems()
        self.server.clearMessageQueue()

    def reloadMessages(self, evt=None):
        """Currently removing all the messages in the list and repopulating it.
        This method gets really slow with large nos of messages.
        Remedy:
            1. Limit the no. of messages to may be 100?
            2. Handle large no. of messages through some kind of optimisations
            3. Eliminate this system, everytime reload is called, only the new
            messages shoule be appended to the list.
        """
        self.filList.DeleteAllItems()
        self.msgList.DeleteAllItems()
        for (uname, addr, msg) in [(rec["USER"], rec["host"], rec["MSG"]) for rec in self.server.msgQue]:
            self.msgList.Append([uname, addr, msg])
        # arch = self.server.msgQue[-1]
        # self.msgList.Append([arch['host'], arch['MSG']])
        print "reloading messages done"

    def newMessageWin(self, event=None):
        self.clients.append(ClientWin(reportAttachment=self.addAttachment, parent=self, show=True))

    def showFileList(self, event=None):
        self.filList.DeleteAllItems()
        for uid, atch in self.server.msgQue[event.GetIndex()]["atchs"]:
            self.filList.Append([atch])

    def showMessage(self, event=None):
        message = self.server.msgQue[event.GetIndex()]["MSG"]
        display = (
            """From: %(USER)s
Address: %(host)s
Message:
%(MSG)s"""
            % self.server.msgQue[event.GetIndex()]
        )
        wx.MessageDialog(None, display, "Details", wx.OK | wx.ICON_INFORMATION | wx.CENTRE).ShowModal()
        return