コード例 #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
 def __init__(self, db_name):
     self.filename = path.join(DATA_DIR, db_name + '.json')
     try:
         self.reload()
     except:
         l.warning(
             f"There was an error loading {self.filename}; silently ignoring"
         )
コード例 #3
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 {}
コード例 #4
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 {}
コード例 #5
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
コード例 #6
0
ファイル: cmd.py プロジェクト: jakubfi/cbpx
    def cmd_set(self, args):
        # no arguments = prit current settings
        if len(args) == 0:
            self.print_cfg()
            return

        # wrong number of arguments
        if len(args) != 2:
            self.ui.write("Use: 'set PARAMETER VALUE' to change setting")
            return

        # check if parameter is available in configuration
        if not hasattr(params, args[0]):
            self.ui.write(" No such parameter: %s" % args[0])
            return

        # check if parameter can be set
        if args[0] not in params.settable:
            self.ui.write(" Paremeter is not settable: %s" % args[0])
            return

        # check if value type is correct
        try:
            v_test = params.settable[args[0]][0] (args[1])
        except:
            self.ui.write(" VALUE for '%s' must be of %s" % (args[0], params.settable[args[0]][0]))
            return

        # check if value range is correct
        if v_test < params.settable[args[0]][1] or v_test > params.settable[args[0]][2]:
            self.ui.write(" %s must be between %s and %s" % (args[0], str(params.settable[args[0]][1]), str(params.settable[args[0]][2])))
            return

        # everything looks fine, set the parameter
        l.debug("Setting '%s' to '%s'" % (args[0], args[1]))
        try:
            params.__dict__[args[0]] = args[1]
        except Exception, e:
            self.ui.write(" Could not set parameter '%s' to '%s', error: %s" % (args[0], args[1], str(e)))
            l.warning("Could not set parameter '%s' to '%s', error: %s" % (args[0], args[1], str(e)))
            return
コード例 #7
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)))
コード例 #8
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")
コード例 #9
0
ファイル: network.py プロジェクト: jakubfi/cbpx
    def run(self):

        rd = []

        l.debug("Running transporter loop")
        while not self.quit:

            # wait for events on all tracked fds
            try:
                rd = self.poller.poll(0.2)
            except Exception, e:
                l.warning("Exception while poll(): %s" % str(e))

            # iterate over all events returned by epoll():
            for f, event in rd:

                # if wata is waiting to be read
                if event & self.DATA_READY:

                    # read the data
                    data = ""
                    try:
                        data = self.fd[f][0].recv(int(params.net_buffer_size))
                    except Exception, e:
                        l.warning("Exception %s while reading data: %s" % (type(e), str(e)))
                        self.dead.add(f)
                        self.dead.add(self.fd[f][2])
                        continue

                    # no data means connection closed
                    if not data:
                        self.dead.add(f)
                        self.dead.add(self.fd[f][2])
                        continue
                    else:
                        # pass the data to the other end
                        try:
                            # TODO: retransmission should be handled better
                            sent = self.fd[f][1].send(data)
                            if sent != len(data):
                                l.error("APOCALYPSE! Transmitted only %i bytes of received %i bytes" % (sent, len(data)))
                        except Exception, e:
                            l.warning("Exception %s while transmitting data: %s" % (type(e), str(e)))
                            self.dead.add(self.fd[f][2])
                            self.dead.add(f)
                            continue
コード例 #10
0
ファイル: network.py プロジェクト: jakubfi/cbpx
                            # TODO: retransmission should be handled better
                            sent = self.fd[f][1].send(data)
                            if sent != len(data):
                                l.error("APOCALYPSE! Transmitted only %i bytes of received %i bytes" % (sent, len(data)))
                        except Exception, e:
                            l.warning("Exception %s while transmitting data: %s" % (type(e), str(e)))
                            self.dead.add(self.fd[f][2])
                            self.dead.add(f)
                            continue

                # if something different happened to an fd
                elif event & self.CONN_STATE:
                    l.warning("Erroneous event from poll(): %i" % event)
                    self.dead.add(f)
                else:
                    l.warning("Unhandled event from poll(): %i" % event)

            # remove connections
            self.remove_dead()

            # since we're removing connections only here, we may as well check for switch finale here
            if (cbpx_stats.c_endpoints == 0) and (not relay.isSet()):
                switch_finalize()


# ------------------------------------------------------------------------
class cbpx_listener(Thread):

    # --------------------------------------------------------------------
    def __init__(self, port):
        Thread.__init__(self, name="Listener")
コード例 #11
0
ファイル: cmd.py プロジェクト: jakubfi/cbpx
            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")

        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:
コード例 #12
0
    async def help(self, ctx, *, command_name: str = None):
        """Display a list of all commands or display information about a specific command."""
        if command_name:
            command = self.bot.get_command(command_name)
            if command is None:
                await ctx.send(embed=discord.Embed(
                    color=colors.ERROR,
                    title="Command help",
                    description=f"Could not find command `{command_name}`.",
                ))
            elif await command.can_run(ctx):
                embed = discord.Embed(
                    color=colors.HELP,
                    title="Command help",
                    description=f"`{command.name}`",
                )

                if command.usage or command.clean_params:
                    embed.add_field(
                        name="Synopsis",
                        value=f"`{get_command_signature(command)}`",
                    )
                if command.aliases:
                    aliases = ', '.join(f"`{alias}`"
                                        for alias in command.aliases)
                    embed.add_field(
                        name="Aliases",
                        value=aliases,
                    )
                if command.help:
                    embed.add_field(
                        name="Description",
                        value=command.help,
                        inline=False,
                    )
                if hasattr(command, 'commands'):
                    subcommands = []
                    for subcommand in command.commands:
                        s = f"`{get_command_signature(subcommand)}`"
                        if subcommand.short_doc:
                            s += f" \N{EM DASH} {subcommand.short_doc}"
                        subcommands.append(s)
                    subcommands.sort()
                    embed.add_field(
                        name="Subcommands",
                        value="\n".join(subcommands) or strings.EMPTY_LIST,
                        inline=False,
                    )
                misc = ''
                if not command.enabled:
                    misc += "This command is currently disabled.\n"
                if command.hidden:
                    misc += "This command is usually hidden.\n"
                if misc:
                    embed.add_field(
                        name="Miscellaneous",
                        value=misc,
                        inline=False,
                    )
                await ctx.send(embed=embed)
            else:
                await ctx.send(embed=discord.Embed(
                    color=colors.ERROR,
                    title="Command help",
                    description=
                    f"You have insufficient permission to access `{command_name}`.",
                ))
        else:
            cog_names = []
            for command in self.bot.commands:
                if command.cog_name:
                    if command.cog_name not in cog_names:
                        cog_names.append(command.cog_name)
                else:
                    l.warning(
                        "Command {command.name!r} has no cog, so it will not be listed by the 'help' command"
                    )
            embed = discord.Embed(
                color=colors.HELP,
                title="Command list",
                description=
                f"Invoke a command by prefixing it with `{ctx.prefix}`. Use `{ctx.prefix}{ctx.command.name} [command]` to get help on a specific command.",
            )
            for cog_name in sorted(cog_names):
                lines = []
                cog = self.bot.get_cog(cog_name)
                for command in sorted(cog.get_commands(),
                                      key=lambda cmd: cmd.name):
                    if not command.hidden and (await command.can_run(ctx)):
                        line = f"\N{BULLET} **`{get_command_signature(command)}`**"
                        if command.short_doc:
                            line += f" \N{EM DASH} {command.short_doc}"
                        lines.append(line)
                if lines:
                    if hasattr(cog, 'name'):
                        name = cog.name
                    else:
                        name = cog_name
                    embed.add_field(name=name,
                                    value="\n".join(lines),
                                    inline=False)
            await ctx.send(embed=embed)