예제 #1
0
파일: network.py 프로젝트: jakubfi/cbpx
    def run(self):
        l.debug("Running listener")
        while True:
            l.debug("Awaiting new connection")

            try:
                # wait for new connection
                (n_sock, n_addr) = self.sock.accept()
            except Exception, e:
                l.error("Error accepting connection: " + str(e))
                break

            l.debug("New connection from: %s" % str(n_addr))

            # if there are more queued connections than allowed
            qc = conn_q.qsize()
            if qc >= int(params.max_queued_conns):
                l.warning("Queued %i connections, limit is %i" % (qc, int(params.max_queued_conns)))
                # if we were switching, than sorry, but not anymore
                l.info("Enabling relaying")
                relay.set("connection limit reached")

            try:
                conn_q.put([n_sock, n_addr], False)
                cbpx_stats.c_qc += 1
                l.debug("Enqueued connection: %s" % str(n_addr))

            except Full:
                l.error("Queue is full with %i elements!" % qc)
                l.info("Enabling relaying")
                relay.set("connection queue full")

            except Exception, e:
                l.warning("Exception during connection enqueue: %s" % str(e))
예제 #2
0
async def on_message(message):
    ch = message.channel
    is_private = isinstance(ch, discord.DMChannel) or isinstance(
        ch, discord.GroupChannel)
    l.info(
        f"[#{ch.id if is_private else ch.name}] {message.author.display_name}: {message.content}"
    )
예제 #3
0
 async def shutdown_(self, ctx, noconfirm=False):
     if noconfirm:
         result = "y"
     else:
         m = await ctx.send(embed=make_embed(
             color=colors.EMBED_ASK,
             title="Shutdown?",
             description=
             "This action may be difficult to undo without phsyical or remote access to the host machine. Are you sure?",
         ))
         result = await react_yes_no(ctx, m)
     await (ctx.send if noconfirm else m.edit)(embed=make_embed(
         color={
             "y": colors.EMBED_INFO if noconfirm else colors.EMBED_CONFIRM,
             "n": colors.EMBED_CANCEL,
             "t": colors.EMBED_TIMEOUT,
         }[result],
         title={
             "y": "Shutting down...",
             "n": "Shutdown cancelled.",
             "t": "Shutdown timed out.",
         }[result],
     ))
     if result is "y":
         l.info(
             f"Shutting down at the command of {ctx.message.author.display_name}..."
         )
         await self.bot.logout()
예제 #4
0
    async def load_all_extensions(self, reload=False):
        """Attempt to load all .py files in cogs/ as cog extensions.

        Return a dictionary which maps cog names to a boolean value (True =
        successfully loaded; False = not successfully loaded).
        """
        succeeded = {}
        disabled_extensions = set()
        if not info.DEV:
            disabled_extensions.add('tests')
        for extension in get_extensions(disabled=disabled_extensions):
            try:
                if reload or extension not in self.cogs_loaded:
                    self.load_extension(f'cogs.{extension}')
                    l.info(f"Loaded extension '{extension}'")
                    self.cogs_loaded.add(extension)
                    succeeded[extension] = True
            except Exception as exc:
                l.error(
                    f"Failed to load extension {extension!r} due to {type(exc).__name__}: {exc}"
                )
                if hasattr(exc, 'original'):
                    l.error(
                        f"More details: {type(exc.original).__name__}: {exc.original}"
                    )
                succeeded[extension] = False
        if succeeded:
            l.info(LOG_SEP)
        return succeeded
예제 #5
0
 async def shutdown_(self, ctx, noconfirm=False):
     if noconfirm:
         response = 'y'
     else:
         m, response = await utils.discord.get_confirm_embed(
             ctx,
             title="Shutdown?",
             description=
             "This action may be difficult to undo without phsyical or remote access to the host machine. Are you sure?",
         )
     if response == 'y':
         title = "Shutting down\N{HORIZONTAL ELLIPSIS}"
     else:
         title = f"Shutdown {strings.YESNO[response]}"
     if noconfirm:
         color = colors.INFO
     else:
         color = colors.YESNO[response]
     await (ctx.send if noconfirm else m.edit)(
         embed=discord.Embed(color=color, title=title))
     if response == 'y':
         l.info(
             f"Shutting down at the command of {utils.discord.fake_mention(ctx.author)}..."
         )
         await self.bot.logout()
예제 #6
0
async def load_extensions(extensions):
    for extension in extensions:
        await asyncio.sleep(0)
        try:
            bot.load_extension("cogs." + extension)
        except Exception:
            continue
        bot.loaded_extensions.add(extension)
    l.info("Loaded all extensions")
예제 #7
0
 async def on_ready(self):
     self.app_info = await self.application_info()
     l.info(LOG_SEP)
     l.info(f"Logged in as: {self.user.name}")
     l.info(f"discord.py:   {discord.__version__}")
     l.info(f"Owner:        {self.app_info.owner}")
     l.info(LOG_SEP)
     await self.load_all_extensions()
     await self.ready_status()
예제 #8
0
파일: main.py 프로젝트: LyricLy/Esobot
async def load_extensions(extensions):
    for extension in extensions:
        await asyncio.sleep(0)
        try:
            bot.load_extension("cogs." + extension)
        except Exception as e:
            print(f"Failed to load {extension}: {type(e).__name__}: {e}")
            continue
        bot.loaded_extensions.add(extension)
    l.info("Loaded all extensions")
예제 #9
0
파일: ui.py 프로젝트: jakubfi/cbpx
 def __init__(self):
     l.debug("Starting readline user interface")
     self.__print_logo()
     try:
         readline.read_history_file(params.history_file)
     except IOError:
         file(params.history_file, "w")
         l.info("Create history file. File path: %s" % 
             (params.history_file))
     print " Ready for your commands, my master.\n"
예제 #10
0
def main():
	l.info("Starting IP Rotator version %s" % (__version__))

	odl = opendaylight()

	while True:
		ip_address = ip()		

		for switch in params.switch:
			flow = {
				'name_in': '%s_in_%s' % (params.flow_prefix, ip_address.replace('.','_')),
				'name_out': '%s_out_%s' % (params.flow_prefix, ip_address.replace('.','_')),
				'priority': params.flow_priority
			}
			current_flows = odl.get_flow(node={'id': switch})
			
			#Check priority of current flows
			for name, value in current_flows.items():
				if re.search(params.flow_prefix, name):
					if int(flow['priority']) == int(value['priority']):
						flow['priority'] = str(int(value['priority'])+1)
						
			l.debug("Priority for flows: %s" % (flow['priority']))
			#Add new flows
			try:
				for port in params.flow_port:
					odl.add_flow(name=flow['name_in']+'_'+port,
						installInHw='true',
						node={"id":switch, "type": "OF"},
						priority=flow['priority'],
						etherType='0x800',
						protocol='tcp',
						nwDst=ip_address,
						tpSrc=port,
						actions=['SET_NW_DST='+params.outgoing_ip, 'HW_PATH']
					)

					odl.add_flow(name=flow['name_out']+'_'+port,
						installInHw='true',
						node={"id":switch, "type": "OF"},
						priority=flow['priority'],
						etherType='0x800',
						protocol='tcp',
						tpDst=port,
						tosBits=params.flow_tos_bits,
						actions=['SET_NW_SRC='+ip_address, 'HW_PATH']
					)
			finally:
				l.info("I've set IP %s" % (ip_address))
				for name, value in current_flows.items():
					if re.search(params.flow_prefix, name):
						odl.delete_flow(node={"id":switch}, name=name)
			
		time.sleep(params.rotate_time)
예제 #11
0
파일: admin.py 프로젝트: LyricLy/Esobot
    async def shutdown(self, ctx):
        """Shuts down the bot without asking for confirmation.

        See `shutdown` for more details.
        """
        await ctx.send(
            embed=make_embed(color=colors.EMBED_INFO, title="Shutting down...")
        )
        l.info(
            f"Shutting down at the command of {ctx.message.author.display_name}..."
        )
        await self.bot.close()
예제 #12
0
def load_data(filename):
    try:
        with open(path.join(DATA_DIR, filename), 'r', encoding='utf-8') as f:
            data = json.load(f)
        l.info(f"Loaded data file {filename}")
        return data
    except:
        l.warning(
            f"There was an error loading {filename}; backing up file and assuming empty dictionary"
        )
        rename(filename, f'{filename}.{int(datetime.now().timestamp())}.bak')
        return {}
예제 #13
0
	def delete_flow(self,**kwargs):
		api_url=("%s/controller/nb/v2/flowprogrammer/default/node/OF/%s/staticFlow/%s" %
			(params.odl_server, kwargs['node']['id'], kwargs['name']))

		self.__auth(api_url)

		request = urllib2.Request(api_url)
		request.get_method = lambda: 'DELETE'
		connection = urllib2.urlopen(request)

		if connection.code == 204:
			l.info("Flow has been deleted, name: %s" % kwargs['name'])
		else:
			l.error("Error during deleting flow entry, name: %s, http error: %s" % (kwargs['name'], connection.code))
예제 #14
0
def load_data(filename: str) -> dict:
    fullpath = path.join(DATA_DIR, filename)
    try:
        with open(fullpath, 'r', encoding='utf-8') as f:
            data = json.load(f)
        l.info(f"Loaded data file {path.relpath(filename)!r}")
        return data
    except Exception:
        msg = f"Error loading {path.relpath(filename)!r};"
        try:
            rename(fullpath, f'{fullpath}.{int(datetime.now().timestamp())}.bak')
            msg += f" backing up existing file and"
        except Exception:
            pass
        msg += " assuming empty dictionary"
        l.warning(msg)
        return {}
예제 #15
0
def save_data(filename: str, data: dict) -> None:
    # Use a temporary file so that the original one doesn't get corrupted in the
    # case of an error.
    fullpath = path.join(DATA_DIR, filename)
    try:
        if not path.isdir(path.dirname(fullpath)):
            makedirs(path.dirname(fullpath))
        tempfile, tempfile_path = mkstemp(dir=DATA_DIR)
        with open(tempfile, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent='\t')
        rename(tempfile_path, path.join(DATA_DIR, filename))
        l.info(f"Saved data file {path.relpath(filename)!r}")
    except Exception:
        l.warning(f"Error saving {path.relpath(filename)!r}")
    finally:
        try:
            remove(tempfile_path)
        except Exception:
            pass
예제 #16
0
파일: main.py 프로젝트: Quonauts/Quobot
 async def load_all_extensions(self, reload=False):
     """
     Attempts to load all .py files in cogs/ as cog extensions. Returns a
     dictionary which maps cog names to a boolean value (True = successfully
     loaded; False = not successfully loaded).
     """
     succeeded = {}
     for extension in get_extensions():
         try:
             if reload or extension not in self.cogs_loaded:
                 self.load_extension(f'cogs.{extension}')
                 l.info(f"Loaded extension '{extension}'")
                 self.cogs_loaded.add(extension)
                 succeeded[extension] = True
         except Exception as e:
             error = f"{extension}\n {type(e).__name__} : {e}"
             l.error(f"Failed to load extension '{error}'")
             succeeded[extension] = False
     if succeeded:
         l.info(LOG_SEP)
     return succeeded
예제 #17
0
파일: cmd.py 프로젝트: jakubfi/cbpx
 def process_command(self):
     try:
         line = self.ui.read()
         if not line:
             return
         l.info("Got command: '%s'" % line)
         l_cmd = line.split(" ")[0]
         l_args = line.split(" ")[1:]
         if l_cmd and (l_cmd not in self.commands.keys()):
             self.ui.write(" Unknown command: '%s'" % l_cmd)
             self.ui.finish()
         else:
             res = self.commands[l_cmd][0](l_args)
             self.ui.finish()
             return res
     except KeyboardInterrupt:
         l.debug("Got KeyboardInterrupt, ignoring")
         self.ui.write("")
     except EOFError:
         self.ui.write("")
     except Exception, e:
         l.warning("Exception %s: %s" % (type(e), str(e)))
예제 #18
0
파일: cmd.py 프로젝트: jakubfi/cbpx
    def cmd_switch(self, args):
        active = relay.get_active()
        (ai, ap) = active
        (si, sp) = relay.get_standby()

        self.ui.write(" Starting switch: %s:%i -> %s:%i, timeout: %2.2f s, %i connections buffer\n" % (ai, ap, si, sp, float(params.switch_max_time), int(params.max_queued_conns)))
        l.info("Starting switch: %s:%i -> %s:%i, timeout: %2.2f s, %i connections buffer" % (ai, ap, si, sp, float(params.switch_max_time), int(params.max_queued_conns)))

        # stop relaying connections now
        relay.clear("switch started")

        # set the timer for max switch time
        switch_timer = SwitchTimer(float(params.switch_max_time))
        switch_timer.start()
        switch_start = time.time()

        # print initial stats
        self.print_stats(True, 0)

        l.debug("About to enter switch loop")

        while not relay.isSet():
            try:
                l.debug("Switch loop wait")
                threading.Event().wait(float(params.switch_loop_wait))

                # print stats
                waited = time.time() - switch_start
                self.print_stats(False, waited)
                l.debug("Switch active, waited: %2.2f" % waited)

            except Exception, e:
                l.info("Exception in 'switch' loop: %s" % str(e))

            except KeyboardInterrupt:
                l.warning("Ctrl-c in switch loop, break")
                self.ui.write(" Ctrl-c")
                relay.set("ctrl-c")
예제 #19
0
파일: network.py 프로젝트: jakubfi/cbpx
def switch_finalize():

    if not params.switch_script:
        l.info("No switch finalize script to run, finishing switch immediately")
        relay.switch_backend("all connections closed")
        return

    try:
        global script

        devnull = open(os.devnull, "rw")

        (ai, ap) = relay.get_active()
        (si, sp) = relay.get_standby()

        l.info("Running script: '%s' with arguments: %s %i %s %i" % (params.switch_script, ai, ap, si, sp))

        script = subprocess.Popen([params.switch_script, ai, str(ap), si, str(sp)], stdin=devnull, stdout=devnull, stderr=devnull, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
        r = script.wait()
    except Exception, e:
        l.error("Exception while executing switch finalize script (%s): %s" % (params.switch_script, str(e)))
        relay.set("script exec failed: %s" % str(e))
        return
예제 #20
0
파일: main.py 프로젝트: Quonauts/Quobot
 async def on_ready(self):
     self.app_info = await self.application_info()
     l.info(LOG_SEP)
     l.info(f"Logged in as: {self.user.name}")
     l.info(f"Using discord.py version: {discord.__version__}")
     l.info(f"Owner: {self.app_info.owner}")
     l.info(f"Template Maker: SourSpoon / Spoon#7805")
     l.info(LOG_SEP)
     await self.load_all_extensions()
     await self.ready_status()
예제 #21
0
파일: main.py 프로젝트: HactarCE/Esobot
async def on_ready():
    l.info(f"Logged in as {bot.user.name}#{bot.user.discriminator}")
예제 #22
0
파일: main.py 프로젝트: HactarCE/Esobot
async def on_resume():
    l.info("Resumed session")
예제 #23
0
파일: main.py 프로젝트: LyricLy/Esobot
async def on_ready():
    bot.owner_id = (await bot.application_info()).owner.id
    l.info(f"Ready")
    await wait_until_loaded()
    await bot.change_presence(status=discord.Status.online)
예제 #24
0
 async def on_connect(self):
     l.info(f"Connected as {self.user}")
     await self.change_presence(status=discord.Status.idle)
예제 #25
0
 async def on_resumed(self):
     l.info("Resumed session.")
     await self.ready_status()
예제 #26
0
 async def on_guild_join(self, guild):
     """This event triggers when the bot joins a guild."""
     l.info(f"Joined {guild.name} with {guild.member_count} users!")
예제 #27
0
파일: network.py 프로젝트: jakubfi/cbpx
        devnull = open(os.devnull, "rw")

        (ai, ap) = relay.get_active()
        (si, sp) = relay.get_standby()

        l.info("Running script: '%s' with arguments: %s %i %s %i" % (params.switch_script, ai, ap, si, sp))

        script = subprocess.Popen([params.switch_script, ai, str(ap), si, str(sp)], stdin=devnull, stdout=devnull, stderr=devnull, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
        r = script.wait()
    except Exception, e:
        l.error("Exception while executing switch finalize script (%s): %s" % (params.switch_script, str(e)))
        relay.set("script exec failed: %s" % str(e))
        return

    l.info("Script exit: %i" % r)
    if r is None:
        # shouldn't happen
        relay.set("unexpected script finish with no return code")
    if r < 0:
        # terminated
        relay.set("script terminated by signal: %i" % -r)
    elif r > 0:
        # exited with error
        relay.set("script exited with code: %i" % r)
    else:
        # switch is done, change backend
        relay.switch_backend("all connections closed, script returned: %i" % r)

    l.info("Switch finalize script done.")
예제 #28
0
async def on_resumed():
    await wait_until_loaded()
    await bot.change_presence(status=discord.Status.online)
    l.info("Resumed session")
예제 #29
0
async def on_connect():
    l.info(f"Connected as {bot.user}")
    await wait_until_loaded()
    await bot.change_presence(status=discord.Status.idle)
예제 #30
0
async def on_ready():
    l.info(f"Ready")
    await wait_until_loaded()
    await bot.change_presence(status=discord.Status.online)
예제 #31
0
파일: cmd.py 프로젝트: jakubfi/cbpx
            except KeyboardInterrupt:
                l.warning("Ctrl-c in switch loop, break")
                self.ui.write(" Ctrl-c")
                relay.set("ctrl-c")

        switch_timer.cancel()

        l.debug("Loop done, checking conditions")

        # check what happened and report to user
        reason = relay.get_reason()
        if relay.get_active() == active:
            l.warning("Backend not switched: %s" % reason)
            self.ui.write("\n Switch failed: %s" % reason)
        else:
            l.info("Backend switched: %s" % reason)
            self.ui.write("\n Switch OK!: %s " % reason)


    # --------------------------------------------------------------------
    def print_stats(self, header, switch):
        sw = "[n/a] "
        if switch != -1:
            try:
                sw = "%2.2f" % float(switch)
            except:
                pass
        if header:
            self.ui.write(" SWtime Current backend       active in queue ->cps cps-> q total")
            self.ui.write(" ------ --------------------- ------ -------- ----- ----- -------")
        (ai, ap) = relay.get_active()