Пример #1
0
    def __init__(self, config=None, path=None):
        """ Creates or loads the config file based on if it exists.
            :param dict config: data used to create the config file
            :param str path: path to the config file
        """
        super().__init__()
        if path:
            self.config_dir = os.path.dirname(path)
            self.config_file = path
        else:
            self.config_dir = DEFAULT_CONFIG_DIR
            self.config_file = DEFAULT_CONFIG_FILE

        if config:
            self.create_config(config, self.config_file)
            self._config = self.load_config(self.config_file)
        else:
            if not os.path.isfile(self.config_file):
                self.create_config(self.default_data, self.config_file)
            self._config = self.load_config(self.config_file)

        # In case there is not a list of nodes in the config file,
        # the node will be replaced by a list of pre-defined nodes,
        # sorted by least latency, no-response nodes are dropped.
        if isinstance(self._config['node'], str):
            sorted_nodes = get_sorted_nodelist(self.node_list)
            self._config['node'] = sorted_nodes
            self.save_config()
Пример #2
0
def sort_nodes(ctx):
    nodelist = ctx.config["node"]
    timeout = int(ctx.obj.get("sortnodes"))

    host_ip = '8.8.8.8'
    if ping(host_ip, 3) is False:
        click.echo("Internet NOT available! Please check your connection!")
        log.critical("Internet not available, exiting")
        sys.exit(78)

    if timeout > 0:
        click.echo(
            "Checking for nearest nodes with timeout < {} sec....".format(
                timeout))
        nodelist = get_sorted_nodelist(ctx.config["node"], timeout)
        click.echo("Nearest nodes ->  " + str(nodelist))
    return nodelist
Пример #3
0
    def new_func(ctx, *args, **kwargs):
        nodelist = ctx.config["node"]
        timeout = int(ctx.obj.get("sortnodes"))

        host_ip = '8.8.8.8'
        if ping(host_ip, 3) is False:
            click.echo("internet NOT available! Please check your connection!")
            log.critical("Internet not available, exiting")
            sys.exit(78)

        if timeout > 0:
            click.echo(
                "Checking for nearest nodes with timeout < {} sec....".format(
                    timeout))
            nodelist = get_sorted_nodelist(ctx.config["node"], timeout)
            click.echo("Nearest nodes ->  " + str(nodelist))

        ctx.bitshares = BitShares(nodelist,
                                  num_retries=-1,
                                  expiration=60,
                                  **ctx.obj)
        set_shared_bitshares_instance(ctx.bitshares)
        return ctx.invoke(f, *args, **kwargs)
Пример #4
0
def configure_dexbot(config, ctx):
    """ Main `cli configure` entrypoint

        :param dexbot.config.Config config: dexbot config
    """
    whiptail = get_whiptail('DEXBot configure')
    workers = config.get('workers', {})
    bitshares_instance = ctx.bitshares
    validator = ConfigValidator(bitshares_instance)

    if not workers:
        while True:
            txt = whiptail.prompt("Your name for the worker")
            if len(txt) == 0:
                whiptail.alert("Worker name cannot be blank. ")
            else:
                config['workers'] = {txt: configure_worker(whiptail, {}, bitshares_instance)}
                if not whiptail.confirm("Set up another worker?\n(DEXBot can run multiple workers in one instance)"):
                    break
        setup_systemd(whiptail, config)
    else:
        while True:
            action = whiptail.menu(
                "You have an existing configuration.\nSelect an action:",
                [('LIST', 'List your workers'),
                 ('NEW', 'Create a new worker'),
                 ('EDIT', 'Edit a worker'),
                 ('DEL_WORKER', 'Delete a worker'),
                 ('ADD', 'Add a bitshares account'),
                 ('DEL_ACCOUNT', 'Delete a bitshares account'),
                 ('SHOW', 'Show bitshares accounts'),
                 ('NODES', 'Edit Node Selection'),
                 ('ADD_NODE', 'Add Your Node'),
                 ('SORT_NODES', 'By latency (uses default list)'),
                 ('DEL_NODE', 'Delete A Node'),
                 ('HELP', 'Where to get help'),
                 ('EXIT', 'Quit this application')])

            my_workers = [(index, index) for index in workers]

            if action == 'EXIT':
                # Cancel will also exit the application. but this is a clearer label
                # Todo: modify cancel to be "Quit" or "Exit" for the whiptail menu item.
                break
            elif action == 'LIST':
                if len(my_workers):
                    # List workers, then provide option to list config of workers
                    worker_name = whiptail.menu("List of Your Workers. Select to view Configuration.", my_workers)
                    content = config['workers'][worker_name]
                    text = '\n'
                    for key, value in content.items():
                        text += '{}: {}\n'.format(key, value)
                    whiptail.view_text(text, pager=False)
                else:
                    whiptail.alert('No workers to view.')
            elif action == 'EDIT':
                if len(my_workers):
                    worker_name = whiptail.menu("Select worker to edit", my_workers)
                    config['workers'][worker_name] = configure_worker(whiptail, config['workers'][worker_name],
                                                                      bitshares_instance)
                else:
                    whiptail.alert('No workers to edit.')
            elif action == 'DEL_WORKER':
                if len(my_workers):
                    worker_name = whiptail.menu("Select worker to delete", my_workers)
                    del config['workers'][worker_name]
                    # Pass ctx.config which is a loaded config (see ui.py configfile()), while `config` in a Config()
                    # instance, which is empty dict, but capable of returning keys via __getitem__(). We need to pass
                    # loaded config into StrategyBase to avoid loading a default config and preserve `--configfile`
                    # option
                    strategy = StrategyBase(worker_name, bitshares_instance=bitshares_instance, config=ctx.config)
                    strategy.clear_all_worker_data()
                else:
                    whiptail.alert('No workers to delete.')
            elif action == 'NEW':
                worker_name = whiptail.prompt("Your name for the new worker. ")
                if not worker_name:
                    whiptail.alert("Worker name cannot be blank. ")
                elif not validator.validate_worker_name(worker_name):
                    whiptail.alert('Worker name needs to be unique. "{}" is already in use.'.format(worker_name))
                else:
                    config['workers'][worker_name] = configure_worker(whiptail, {}, bitshares_instance)
            elif action == 'ADD':
                add_account(whiptail, bitshares_instance)
            elif action == 'DEL_ACCOUNT':
                del_account(whiptail, bitshares_instance)
            elif action == 'SHOW':
                account_list = list_accounts(bitshares_instance)
                if account_list:
                    action = whiptail.menu("Bitshares Account List (Name - Type)", account_list)
                else:
                    whiptail.alert('You do not have any bitshares accounts in the wallet')
            elif action == 'ADD_NODE':
                txt = whiptail.prompt("Your name for the new node: e.g. wss://dexnode.net/ws")
                # Insert new node on top of the list
                config['node'].insert(0, txt)
            elif action == 'NODES':
                choice = whiptail.node_radiolist(
                    msg="Choose your preferred node",
                    items=select_choice(config['node'][0],
                                        [(index, index) for index in config['node']]))
                # Move selected node as first item in the config file's node list
                config['node'].remove(choice)
                config['node'].insert(0, choice)
                setup_systemd(whiptail, config)
            elif action == 'SORT_NODES':
                nodelist = config['node']
                sorted_nodes = get_sorted_nodelist(nodelist, 2.0)
                config['node'] = sorted_nodes
            elif action == 'DEL_NODE':
                choice = whiptail.node_radiolist(
                    msg="Choose node to delete",
                    items=select_choice(config['node'][0],
                                        [(index, index) for index in config['node']]))
                config['node'].remove(choice)
                # delete node permanently from config
                setup_systemd(whiptail, config)
            elif action == 'HELP':
                whiptail.alert("Please see https://github.com/Codaone/DEXBot/wiki")

    whiptail.clear()
    return config