Exemple #1
0
def test_clean():
    """ Test the clean function """
    instance = Action()
    status = instance.clean()
    assert isinstance(status, tuple)
    status = instance.clean(name='rq_worker2')
    assert isinstance(status, tuple)
Exemple #2
0
    def create(self):
        self.add_handlers({'^T': self.quit, '^Q': self.quit})
        self.add(npyscreen.Textfield,
                 value=self.n_action + ' a network tap capture container.',
                 editable=False,
                 color='STANDOUT')
        self.add(npyscreen.Textfield,
                 value='Choose a container to ' + self.n_action,
                 editable=False,
                 color='STANDOUT')

        self.nextrely += 1

        try:
            # display all containers by sending a get request to ntap/list
            # nlist returns tuple and get_request returns tuple
            url = Action().get_vent_tool_url('network-tap')[1] + '/list'
            request = Action().get_request(url)

            # create selection for containers
            if request[0]:
                request = ast.literal_eval(str(request[1]))
                data = [d for d in list(request[1])]
                self.ms = self.add(npyscreen.TitleMultiSelect,
                                   max_height=20,
                                   name='Choose one or more containers to ' +
                                   self.n_action,
                                   values=data)

            else:
                npyscreen.notify_confirm('Failure: ' + str(request[1]))

        except Exception as e:  # pragma: no cover
            npyscreen.notify_confirm('Failure: ' + str(e))
Exemple #3
0
    def on_ok(self):
        # error check to make sure all fields were filled out
        if not self.nic.value or not self.id.value or not self.interval.value \
           or not self.iters.value:
            npyscreen.notify_confirm('Please fill out all fields',
                                     form_color='CAUTION')
            return

        # create a dictionary with user entered data
        payload = {}
        payload[self.nic.name] = self.nic.value
        payload[self.id.name] = self.id.value
        payload[self.interval.name] = self.interval.value
        payload[self.filter.name] = self.filter.value
        payload[self.iters.name] = self.iters.value

        try:
            url = Action().get_vent_tool_url('network-tap')[1] + \
                '/create'
            request = Action().post_request(url, str(payload))

            if request[0]:
                npyscreen.notify_confirm('Success: ' + str(request[1]))
                self.quit()

            else:
                npyscreen.notify_confirm('Failure: ' + str(request[1]))
        except Exception as e:  # pragma: no cover
            npyscreen.notify_confirm('Failure: {0}'.format(str(e)))

        return
Exemple #4
0
    def create(self):
        self.add_handlers({'^T': self.quit, '^Q': self.quit})
        self.add(npyscreen.Textfield,
                 value='List all avilable network interfaces',
                 editable=False,
                 color='STANDOUT')

        self.nextrely += 1

        try:
            url = Action().get_vent_tool_url('network-tap')[1] + '/nics'
            request = Action().get_request(url)

            if request[0]:
                box = self.add(npyscreen.BoxTitle,
                               name='Available Network Interfaces',
                               max_height=40)
                request = ast.literal_eval(str(request[1]))
                data = [d for d in request[1].split('\n')]
                box.values = data
            else:
                npyscreen.notify_confirm('Failure: ' + request[1])

        except Exception as e:  # pragma no cover
            npyscreen.notify_confirm('Failure: ' + str(e))
Exemple #5
0
    def on_ok(self):
        # error check to make sure all fields were filled out
        if not self.nic.value or not self.id.value or not self.interval.value \
           or not self.iters.value:
            npyscreen.notify_confirm("Please fill out all fields",
                                     form_color='CAUTION')
            return

        # create a dictionary with user entered data
        payload = {}
        payload[self.nic.name] = self.nic.value
        payload[self.id.name] = self.id.value
        payload[self.interval.name] = self.interval.value
        payload[self.filter.name] = self.filter.value
        payload[self.iters.name] = self.iters.value

        # create an action object and have it do the work
        self.api_action = Action()
        try:
            url = self.api_action.get_vent_tool_url('network-tap')[1] + \
                  '/create'
            request = self.api_action.post_request(url, str(payload))

            if request[0]:
                npyscreen.notify_confirm("Success: " + str(request[1]))
                self.quit()

            else:
                npyscreen.notify_confirm("Failure: " + str(request[1]))
        except Exception as e:  # pragma: no cover
            npyscreen.notify_confirm("Failure: " + str(e))

        return
Exemple #6
0
 def while_waiting(self):
     """ Update with current tools that are not cores """
     if not self.triggered:
         i = 4
         api_action = Action()
         response = api_action.inventory(choices=['repos', 'tools', 'core'])
         if response[0]:
             inventory = response[1]
             for repo in inventory['repos']:
                 repo_name = repo.rsplit("/", 2)[1:]
                 self.tools_tc[repo] = {}
                 title_text = self.add(npyscreen.TitleText, name='Plugin: '+repo, editable=False, rely=i, relx=5)
                 title_text.display()
                 i += 1
                 for tool in inventory['tools']:
                     r_name = tool[0].split(":")
                     if repo_name[0] == r_name[0] and repo_name[1] == r_name[1]:
                         core = False
                         for item in inventory['core']:
                             if tool[0] == item[0]:
                                 core = True
                         t = tool[1]
                         if t == "":
                             t = "/"
                         if core:
                             t += ":" + ":".join(tool[0].split(":")[-2:])
                             self.tools_tc[repo][t] = self.add(npyscreen.CheckBox, name=t, value=True, relx=10)
                             self.tools_tc[repo][t].display()
                             i += 1
                 i += 2
             self.triggered = 1
     return
 def while_waiting(self):
     """ Update with current tools that are not cores """
     if not self.triggered:
         i = 4
         api_action = Action()
         response = api_action.inventory(choices=['repos', 'tools', 'core'])
         if response[0]:
             inventory = response[1]
             for repo in inventory['repos']:
                 repo_name = repo.rsplit("/", 2)[1:]
                 self.tools_tc[repo] = {}
                 title_text = self.add(npyscreen.TitleText, name='Plugin: '+repo, editable=False, rely=i, relx=5)
                 title_text.display()
                 i += 1
                 for tool in inventory['tools']:
                     r_name = tool[0].split(":")
                     if repo_name[0] == r_name[0] and repo_name[1] == r_name[1]:
                         core = False
                         for item in inventory['core']:
                             if tool[0] == item[0]:
                                 core = True
                         t = tool[1]
                         if t == "":
                             t = "/"
                         if core:
                             t += ":" + ":".join(tool[0].split(":")[-2:])
                             self.tools_tc[repo][t] = self.add(npyscreen.CheckBox, name=t, value=True, relx=10)
                             self.tools_tc[repo][t].display()
                             i += 1
                 i += 2
             self.triggered = 1
     return
Exemple #8
0
    def on_ok(self):
        # error check to make sure at least one box was selected
        if not self.ms.value:
            npyscreen.notify_confirm('Please select at least one container.',
                                     form_color='CAUTION')

        # format the data into something ncontrol likes
        else:
            payload = {
                'id': list(x['id'] for x in self.ms.get_selected_objects())
            }

        # grab the url that network-tap is listening to
        try:
            npyscreen.notify_wait('Please wait. Currently working')
            url = Action().get_vent_tool_url('network-tap')[1] + '/' \
                + self.n_action
            request = Action().post_request(url, payload)

            if request[0]:
                npyscreen.notify_confirm('Success: ' + str(request[1]))
                self.quit()

            else:
                npyscreen.notify_confirm('Failure: ' + str(request[1]))

        except Exception as e:  # pragma: no cover
            npyscreen.notify_confirm('Failure: ' + str(e))
Exemple #9
0
    def create(self):
        self.add_handlers({'^T': self.quit, '^Q': self.quit})
        self.add(npyscreen.Textfield,
                 value='List all network tap capture containers',
                 editable=False,
                 color='STANDOUT')

        self.nextrely += 1

        try:
            self.api_action = Action()
            url = self.api_action.get_vent_tool_url('network-tap')[1] + '/list'
            request = self.api_action.get_request(url)

            if request[0]:
                box = self.add(npyscreen.BoxTitle,
                               name='Network Tap Capture Containers',
                               max_height=40)
                request = ast.literal_eval(str(request[1]))
                data = [d for d in list(request[1])]
                box.values = data
            else:
                npyscreen.notify_confirm('Failure: ' + request[1])

        except Exception as e:  # pragma no cover
            npyscreen.notify_confirm('Failure: ' + str(e))
Exemple #10
0
 def while_waiting(self):
     """ Update with current tools that are not cores """
     if not self.triggered:
         i = 4
         api_action = Action()
         response = api_action.inventory(choices=[
             'repos', 'tools', 'built', 'enabled', 'running', 'core'
         ])
         if response[0]:
             inventory = response[1]
             for repo in inventory['repos']:
                 if repo != 'https://github.com/cyberreboot/vent':
                     repo_name = repo.rsplit("/", 2)[1:]
                     self.tools_tc[repo] = {}
                     title_text = self.add(npyscreen.TitleText,
                                           name='Plugin: ' + repo,
                                           editable=False,
                                           rely=i,
                                           relx=5)
                     title_text.display()
                     i += 1
                     for tool in inventory['tools']:
                         r_name = tool[0].split(":")
                         if repo_name[0] == r_name[0] and repo_name[
                                 1] == r_name[1]:
                             core = False
                             running = False
                             built = False
                             enabled = False
                             for item in inventory['core']:
                                 if tool[0] == item[0]:
                                     core = True
                             for item in inventory['running']:
                                 if tool[0] == item[0] and item[
                                         2] == 'running':
                                     running = True
                             for item in inventory['built']:
                                 if tool[0] == item[0] and item[2] == 'yes':
                                     built = True
                             for item in inventory['enabled']:
                                 if tool[0] == item[0] and item[2] == 'yes':
                                     enabled = True
                             t = tool[1]
                             if t == "":
                                 t = "/"
                             if not core and not running and built and enabled:
                                 t += ":" + ":".join(
                                     tool[0].split(":")[-2:])
                                 self.tools_tc[repo][t] = self.add(
                                     npyscreen.CheckBox,
                                     name=t,
                                     value=True,
                                     relx=10)
                                 self.tools_tc[repo][t].display()
                                 i += 1
                     i += 2
             self.triggered = 1
     return
Exemple #11
0
def test_add():
    """ Test the add function """
    instance = Action()
    status = instance.add('bad')
    assert isinstance(status, tuple)
    assert status[0] == False
    status = instance.add('https://github.com/cyberreboot/vent', build=False)
    assert isinstance(status, tuple)
    assert status[0] == True
Exemple #12
0
def test_remove():
    """ Test the remove function """
    instance = Action()
    status = instance.remove()
    assert isinstance(status, tuple)
    assert status[0] == True
    status = instance.remove(repo='https://github.com/cyberreboot/vent')
    assert isinstance(status, tuple)
    assert status[0] == True
    def on_ok(self):
        """
        Take the tool selections and start them
        """
        def diff(first, second):
            """
            Get the elements that exist in the first list and not in the second
            """
            second = set(second)
            return [item for item in first if item not in second]

        def popup(original, orig_type, thr, title):
            """
            Start the thread and display a popup of info
            until the thread is finished
            """
            thr.start()
            info_str = ""
            while thr.is_alive():
                if orig_type == 'containers':
                    info = diff(Containers(), original)
                elif orig_type == 'images':
                    info = diff(Images(), original)
                if info:
                    info_str = ""
                for entry in info:
                    # TODO limit length of info_str to fit box
                    info_str += entry[0] + ": " + entry[1] + "\n"
                npyscreen.notify_wait(info_str, title=title)
                time.sleep(1)
            return

        original_containers = Containers()

        api_action = Action()
        tool_dict = {}
        for repo in self.tools_tc:
            for tool in self.tools_tc[repo]:
                self.logger.info(tool)
                if self.tools_tc[repo][tool].value:
                    t = tool
                    if t.startswith('/:'):
                        t = " " + t[1:]
                    t = t.split(":")
                    status = api_action.prep_start(name=t[0],
                                                   branch=t[1],
                                                   version=t[2])
                    if status[0]:
                        tool_dict.update(status[1])
        thr = threading.Thread(target=api_action.start,
                               args=(),
                               kwargs={'tool_dict': tool_dict})
        popup(original_containers, "containers", thr,
              'Please wait, starting containers...')
        npyscreen.notify_confirm("Done starting containers.",
                                 title='Started containers')
        self.quit()
Exemple #14
0
def test_backup():
    """ Test the backup function """
    vent_config = os.path.join(os.path.expanduser('~'), '.vent', 'vent.cfg')
    with open(vent_config, 'w') as f:
        f.write('[main]\nfiles = /test')
    instance = Action()
    status = instance.backup()
    assert isinstance(status, tuple)
    assert status[0] == True
    assert os.path.exists(status[1])
Exemple #15
0
def test_restart_tools():
    instance = Action()
    status = instance.restart_tools(main_cfg=True, old_val='', new_val='')
    assert isinstance(status, tuple)
    assert status[0]
    status = instance.restart_tools(main_cfg=True, old_val='junk', new_val='[ext]')
    assert isinstance(status, tuple)
    assert status[0]
    status = instance.restart_tools()
    assert isinstance(status, tuple)
    assert status[0]
Exemple #16
0
def test_startup():
    """
    Test the startup function; uses the startup file configured in
    .setup_travis in order to populate the startup file with fields
    """
    instance = Action()
    status = instance.startup()
    assert isinstance(status, tuple)
    assert status[0]
    with open(instance.plugin.manifest) as man:
        assert 'rabbitmq' in man.read()
Exemple #17
0
def test_update():
    """ Test the update function """
    instance = Action()
    status = instance.add('https://github.com/cyberreboot/vent',
                          branch='master',
                          tools=[('vent/core/elasticsearch', '')])
    assert isinstance(status, tuple)
    assert status[0]
    status = instance.update(name='elasticsearch', branch='master')
    assert isinstance(status, tuple)
    assert status[0]
Exemple #18
0
def test_update():
    """ Test the update function """
    instance = Action()
    status = instance.add('https://github.com/cyberreboot/vent',
                          branch='master',
                          tools=[('vent/core/elasticsearch', '')])
    assert isinstance(status, tuple)
    assert status[0]
    status = instance.update(name='elasticsearch', branch='master',
                             new_version='a45e8b3c79964c9a6953b6b45f079bd833edbf46')
    assert isinstance(status, tuple)
    assert status[0]
def test_logs():
    """ Test the logs function """
    instance = Action()
    status = instance.logs()
    assert type(status) == tuple
    assert status[0] == True
    status = instance.logs(grep_list=['foo'])
    assert type(status) == tuple
    assert status[0] == True
    status = instance.logs(container_type="core")
    assert type(status) == tuple
    assert status[0] == True
Exemple #20
0
def test_logs():
    """ Test the logs function """
    instance = Action()
    status = instance.logs()
    assert isinstance(status, tuple)
    assert status[0] == True
    status = instance.logs(grep_list=['foo'])
    assert isinstance(status, tuple)
    assert status[0] == True
    status = instance.logs(c_type="core")
    assert isinstance(status, tuple)
    assert status[0] == True
Exemple #21
0
def test_build():
    """ Test the build function """
    instance = Action()
    status = instance.add('https://github.com/cyberreboot/vent-plugins',
                          branch='master',
                          tools=[('kibana','')],
                          build=False)
    assert isinstance(status, tuple)
    assert status[0] ==  True
    status = instance.build(branch='master', name='kibana')
    assert isinstance(status, tuple)
    assert status[0] == True
    def on_ok(self):
        """
        Take the tool selections and start them
        """
        def diff(first, second):
            """
            Get the elements that exist in the first list and not in the second
            """
            second = set(second)
            return [item for item in first if item not in second]

        def popup(original, orig_type, thr, title):
            """
            Start the thread and display a popup of info
            until the thread is finished
            """
            thr.start()
            info_str = ""
            while thr.is_alive():
                if orig_type == 'containers':
                    info = diff(Containers(), original)
                elif orig_type == 'images':
                    info = diff(Images(), original)
                if info:
                    info_str = ""
                for entry in info:
                    # TODO limit length of info_str to fit box
                    info_str += entry[0]+": "+entry[1]+"\n"
                npyscreen.notify_wait(info_str, title=title)
                time.sleep(1)
            return

        original_containers = Containers()

        api_action = Action()
        tool_dict = {}
        for repo in self.tools_tc:
            for tool in self.tools_tc[repo]:
                self.logger.info(tool)
                if self.tools_tc[repo][tool].value:
                    t = tool
                    if t.startswith('/:'):
                        t = " "+t[1:]
                    t = t.split(":")
                    status = api_action.prep_start(name=t[0], branch=t[1], version=t[2])
                    if status[0]:
                        tool_dict.update(status[1])
        thr = threading.Thread(target=api_action.start, args=(), kwargs={'tool_dict':tool_dict})
        popup(original_containers, "containers", thr,
              'Please wait, starting containers...')
        npyscreen.notify_confirm("Done starting containers.",
                                 title='Started containers')
        self.quit()
def test_inventory():
    """ Test the inventory function """
    instance = Action()
    status = instance.inventory(choices=[])
    assert type(status) == tuple
    assert status[0] == True
    assert type(status[1]) == dict
    status = instance.inventory(choices=[
        'repos', 'core', 'tools', 'images', 'built', 'running', 'enabled',
        'foo'
    ])
    assert type(status) == tuple
    assert status[0] == True
    assert type(status[1]) == dict
 def while_waiting(self):
     """ Update the text with the core tools in the inventory when nothing is happening """
     if self.action is None:
         self.action = Action()
     # include only core tools in this inventory
     response = self.action.inventory(choices=[
         'repos', 'core', 'tools', 'images', 'built', 'running', 'enabled'
     ])
     if response[0]:
         inventory = response[1]
         value = "Tools for each plugin found:\n"
         for repo in inventory['repos']:
             value += "\n  Plugin: " + repo + "\n"
             repo_name = repo.rsplit("/", 2)[1:]
             for tool in inventory['tools']:
                 is_core = False
                 for core in inventory['core']:
                     if core[0] == tool[0]:
                         is_core = True
                 if is_core:
                     r_name = tool[0].split(":")
                     if repo_name[0] == r_name[0] and repo_name[
                             1] == r_name[1]:
                         value += "    " + tool[1] + "\n"
                         for built in inventory['built']:
                             if built[0] == tool[0]:
                                 value += "      Built: " + built[2] + "\n"
                         for enabled in inventory['enabled']:
                             if enabled[0] == tool[0]:
                                 value += "      Enabled: " + enabled[
                                     2] + "\n"
                         for image in inventory['images']:
                             if image[0] == tool[0]:
                                 value += "      Image name: " + image[
                                     2] + "\n"
                         for running in inventory['running']:
                             if running[0] == tool[0]:
                                 value += "      Status: " + running[
                                     2] + "\n"
             tmp_value = value.split("\n")
             if "Plugin: " in tmp_value[-2]:
                 value = "\n".join(value.split("\n")[:-2])
     else:
         value = "There was an issue with core inventory retrieval:\n" + str(
             response[1]) + "\nPlease see vent.log for more details."
     self.inventory_mle.values = value.split("\n")
     self.inventory_mle.display()
     return
Exemple #25
0
    def on_ok(self):
        """
        Take the tool selections and add them as plugins
        """
        def diff(first, second):
            """
            Get the elements that exist in the first list and not in the second
            """
            second = set(second)
            return [item for item in first if item not in second]

        def popup(original_tools, branch, thr, title):
            """
            Start the thread and display a popup of the tools being added until
            the thread is finished
            """
            thr.start()
            tool_str = 'Adding tools...'
            npyscreen.notify_wait(tool_str, title=title)
            while thr.is_alive():
                tools = diff(Tools(), original_tools)
                if tools:
                    tool_str = ''
                for tool in tools:
                    pre_tool = 'Added: ' + branch + '/' + tool + '\n'
                    tool_str = pre_tool + tool_str
                npyscreen.notify_wait(tool_str, title=title)
                time.sleep(1)
            return

        original_tools = Tools()
        for branch in self.tools_tc:
            api_action = Action()
            tools = []
            for tool in self.tools_tc[branch]:
                if self.tools_tc[branch][tool].value:
                    # get rid of temporary show for multiple tools in same
                    # directory
                    if tool == '/':
                        tools.append(('.', ''))
                    else:
                        tools.append((tool, ''))
            repo = self.parentApp.repo_value['repo']
            version = self.parentApp.repo_value['versions'][branch]
            build = self.parentApp.repo_value['build'][branch]
            thr = threading.Thread(target=api_action.add,
                                   args=(),
                                   kwargs={
                                       'repo': repo,
                                       'branch': branch,
                                       'tools': tools,
                                       'version': version,
                                       'build': build
                                   })
            popup(original_tools, branch, thr,
                  'Please wait, adding tools for the ' + branch + ' branch...')
        npyscreen.notify_confirm('Done adding repository: ' +
                                 self.parentApp.repo_value['repo'],
                                 title='Added Repository')
        self.quit()
Exemple #26
0
 def __init__(self, action_dict=None, action_name=None, *args, **keywords):
     api_action = Action()
     action = {'api_action': api_action}
     if action_dict:
         action.update(action_dict)
     logger = Logger(action_name)
     InventoryForm.__init__(self, action, logger, *args, **keywords)
Exemple #27
0
class LogsForm(npyscreen.FormBaseNew):
    """ Logs form for the Vent CLI """
    def quit(self, *args, **kwargs):
        """ Overridden to switch back to MAIN form """
        self.parentApp.switchForm('MAIN')

    def create(self):
        """ Override method for creating FormBaseNew form """
        self.add_handlers({'^T': self.quit, '^Q': self.quit})
        self.add(npyscreen.TitleFixedText, name='Logs:', value='')
        msg = 'Checking for container logs, please wait...'
        self.logs_mle = self.add(npyscreen.Pager, values=[msg])
        self.action = Action()
        response = self.action.logs()
        if response[0]:
            value = 'Logs for each Vent container found:\n'
            logs = response[1]
            for container in logs:
                value += '\n Container: ' + container + '\n'
                for log in logs[container]:
                    value += '    ' + log + '\n'
                value += '\n'
            self.logs_mle.values = value.split('\n')
        else:
            msg = 'There was an issue retrieving logs for Vent containers: '
            self.logs_mle.values = [
                msg,
                str(response[1]), 'Please see vent.log for more details.'
            ]
Exemple #28
0
class InventoryForm(npyscreen.FormBaseNew):
    """ Inventory form for the Vent CLI """
    action = None
    def while_waiting(self):
        """ Update the text with the plugins in the inventory when nothing is happening """
        if self.action is None:
            self.action = Action()
        # don't include core tools in this inventory
        response = self.action.inventory(choices=['repos', 'core', 'tools', 'images', 'built', 'running', 'enabled'])
        if response[0]:
            inventory = response[1]
            value = "Tools for each plugin found:\n"
            for repo in inventory['repos']:
                if repo != "https://github.com/cyberreboot/vent":
                    value += "\n  Plugin: "+repo+"\n"
                    repo_name = repo.rsplit("/", 2)[1:]
                    for tool in inventory['tools']:
                        is_core = False
                        for core in inventory['core']:
                            if core[0] == tool[0]:
                                is_core = True
                        if not is_core:
                            r_name = tool[0].split(":")
                            if repo_name[0] == r_name[0] and repo_name[1] == r_name[1]:
                                value += "    "+tool[1]+"\n"
                                for built in inventory['built']:
                                    if built[0] == tool[0]:
                                        value += "      Built: "+built[2]+"\n"
                                for enabled in inventory['enabled']:
                                    if enabled[0] == tool[0]:
                                        value += "      Enabled: "+enabled[2]+"\n"
                                for image in inventory['images']:
                                    if image[0] == tool[0]:
                                        value += "      Image name: "+image[2]+"\n"
                                for running in inventory['running']:
                                    if running[0] == tool[0]:
                                        value += "      Status: "+running[2]+"\n"
        else:
            value = "There was an issue with inventory retrieval:\n"+str(response[1])+"\nPlease see vent.log for more details."
        self.inventory_mle.values=value.split("\n")
        self.inventory_mle.display()
        return

    def create(self):
        """ Override method for creating FormBaseNew form """
        self.add_handlers({"^T": self.change_forms,"^Q": self.exit})
        self.add(npyscreen.TitleFixedText, name='Inventory items:', value='')
        self.inventory_mle = self.add(npyscreen.Pager,
                                      values=['Checking for plugins in the inventory, please wait...'])

    def exit(self, *args, **keywords):
        self.parentApp.switchForm("MAIN")

    def change_forms(self, *args, **keywords):
        """ Toggles back to main """
        change_to = "MAIN"

        # Tell the VentApp object to change forms.
        self.parentApp.change_form(change_to)
Exemple #29
0
 def while_waiting(self):
     """ Update with current tools that are not cores """
     if not self.triggered:
         i = 4
         api_action = Action()
         response = api_action.inventory(choices=['repos', 'tools', 'built', 'enabled', 'running', 'core'])
         if response[0]:
             inventory = response[1]
             for repo in inventory['repos']:
                 if repo != 'https://github.com/cyberreboot/vent':
                     repo_name = repo.rsplit("/", 2)[1:]
                     self.tools_tc[repo] = {}
                     title_text = self.add(npyscreen.TitleText, name='Plugin: '+repo, editable=False, rely=i, relx=5)
                     title_text.display()
                     i += 1
                     for tool in inventory['tools']:
                         r_name = tool[0].split(":")
                         if repo_name[0] == r_name[0] and repo_name[1] == r_name[1]:
                             core = False
                             running = False
                             built = False
                             enabled = False
                             for item in inventory['core']:
                                 if tool[0] == item[0]:
                                     core = True
                             for item in inventory['running']:
                                 if tool[0] == item[0] and item[2] == 'running':
                                     running = True
                             for item in inventory['built']:
                                 if tool[0] == item[0] and item[2] == 'yes':
                                     built = True
                             for item in inventory['enabled']:
                                 if tool[0] == item[0] and item[2] == 'yes':
                                     enabled = True
                             t = tool[1]
                             if t == "":
                                 t = "/"
                             if not core and not running and built and enabled:
                                 t += ":" + ":".join(tool[0].split(":")[-2:])
                                 self.tools_tc[repo][t] = self.add(npyscreen.CheckBox, name=t, value=True, relx=10)
                                 self.tools_tc[repo][t].display()
                                 i += 1
                     i += 2
             self.triggered = 1
     return
Exemple #30
0
 def while_waiting(self):
     """ Update the text with the logs from containers not logging to syslog """
     if self.action is None:
         self.action = Action()
         response = self.action.logs()
         if response[0]:
             value = "Logs for each Vent container found:\n"
             for container in logs:
                 value += "\n Container: "+container+"\n"
                 for log in logs[container]:
                     value += "    "+log+"\n"
                 value += "\n"
             self.logs_mle.values=value.split("\n")
             self.logs_mle.display()
         else:
             self.logs_mle.values=["There was an issue retrieving logs for Vent containers: ",
                                   str(response[1]),
                                   "Please see vent.log for more details."]
             self.logs_mle.display()
     return
Exemple #31
0
class ListNTap(npyscreen.ActionForm):
    """ For listing all network tap capture containers """
    def create(self):
        self.add_handlers({"^T": self.quit, "^Q": self.quit})
        self.add(npyscreen.Textfield,
                 value='List all network tap capture containers',
                 editable=False,
                 color="STANDOUT")

        self.nextrely += 1

        try:
            self.api_action = Action()
            url = self.api_action.get_vent_tool_url('network-tap')[1] + '/list'
            request = self.api_action.get_request(url)

            if request[0]:
                box = self.add(npyscreen.BoxTitle,
                               name="Network Tap Capture Containers",
                               max_height=40)
                request = ast.literal_eval(str(request[1]))
                data = [d for d in list(request[1])]
                box.values = data
            else:
                npyscreen.notify_confirm("Failure: " + request[1])

        except Exception as e:  # pragma no cover
            npyscreen.notify_confirm("Failure: " + str(e))

    def quit(self, *args, **kwargs):
        """ Overriden to switch back to MAIN form """
        self.parentApp.switchForm("MAIN")

    def on_cancel(self):
        """ When user cancels, return to MAIN """
        self.quit()

    def on_ok(self):
        self.quit()
Exemple #32
0
class NICsNTap(npyscreen.ActionForm):
    """ For listing all available network interfaces """
    def create(self):
        self.add_handlers({'^T': self.quit, '^Q': self.quit})
        self.add(npyscreen.Textfield,
                 value='List all avilable network interfaces',
                 editable=False,
                 color='STANDOUT')

        self.nextrely += 1

        try:
            self.api_action = Action()
            url = self.api_action.get_vent_tool_url('network-tap')[1] + '/nics'
            request = self.api_action.get_request(url)

            if request[0]:
                box = self.add(npyscreen.BoxTitle,
                               name='Available Network Interfaces',
                               max_height=40)
                request = ast.literal_eval(str(request[1]))
                data = [d for d in request[1].split('\n')]
                box.values = data
            else:
                npyscreen.notify_confirm('Failure: ' + request[1])

        except Exception as e:  # pragma no cover
            npyscreen.notify_confirm('Failure: ' + str(e))

    def quit(self, *args, **kwargs):
        """ Overriden to switch back to MAIN form """
        self.parentApp.switchForm('MAIN')

    def on_cancel(self):
        """ When user cancels, return to MAIN """
        self.quit()

    def on_ok(self):
        self.quit()
Exemple #33
0
    def on_ok(self):
        """
        Take the tool selections and add them as plugins
        """
        def diff(first, second):
            """
            Get the elements that exist in the first list and not in the second
            """
            second = set(second)
            return [item for item in first if item not in second]

        def popup(original_tools, branch, thr, title):
            """
            Start the thread and display a popup of the tools being added until
            the thread is finished
            """
            thr.start()
            tool_str = "Adding tools..."
            npyscreen.notify_wait(tool_str, title=title)
            while thr.is_alive():
                tools = diff(Tools(), original_tools)
                if tools:
                    tool_str = ""
                for tool in tools:
                    # TODO limit length of tool_str to fit box
                    tool_str = "Added: "+branch+"/"+tool+"\n"+tool_str
                npyscreen.notify_wait(tool_str, title=title)
                time.sleep(1)
            return

        original_tools = Tools()
        for branch in self.tools_tc:
            api_action = Action()
            tools = []
            for tool in self.tools_tc[branch]:
                if self.tools_tc[branch][tool].value:
                    if tool == '/':
                        tools.append(('.',''))
                    else:
                        tools.append((tool,''))
            thr = threading.Thread(target=api_action.add, args=(),
                                   kwargs={'repo':self.parentApp.repo_value['repo'],
                                           'branch':branch,
                                           'tools':tools,
                                           'version':self.parentApp.repo_value['versions'][branch],
                                           'build':self.parentApp.repo_value['build'][branch]})
            popup(original_tools, branch, thr,
                  'Please wait, adding tools for the '+branch+' branch...')
        npyscreen.notify_confirm("Done adding repository: "+self.parentApp.repo_value['repo'],
                                 title='Added Repository')
        self.quit()
Exemple #34
0
 def create(self):
     """ Override method for creating FormBaseNew form """
     self.add_handlers({"^T": self.quit, "^Q": self.quit})
     self.add(npyscreen.TitleFixedText, name='Logs:', value='')
     msg = 'Checking for container logs, please wait...'
     self.logs_mle = self.add(npyscreen.Pager, values=[msg])
     self.action = Action()
     response = self.action.logs()
     if response[0]:
         value = "Logs for each Vent container found:\n"
         logs = response[1]
         for container in logs:
             value += "\n Container: " + container + "\n"
             for log in logs[container]:
                 value += "    " + log + "\n"
             value += "\n"
         self.logs_mle.values = value.split("\n")
     else:
         msg = "There was an issue retrieving logs for Vent containers: "
         self.logs_mle.values = [
             msg,
             str(response[1]), "Please see vent.log for more details."
         ]
 def while_waiting(self):
     """ Update the text with the core tools in the inventory when nothing is happening """
     if self.action is None:
         self.action = Action()
     # include only core tools in this inventory
     response = self.action.inventory(choices=['repos', 'core', 'tools', 'images', 'built', 'running', 'enabled'])
     if response[0]:
         inventory = response[1]
         value = "Tools for each plugin found:\n"
         for repo in inventory['repos']:
             value += "\n  Plugin: "+repo+"\n"
             repo_name = repo.rsplit("/", 2)[1:]
             for tool in inventory['tools']:
                 is_core = False
                 for core in inventory['core']:
                     if core[0] == tool[0]:
                         is_core = True
                 if is_core:
                     r_name = tool[0].split(":")
                     if repo_name[0] == r_name[0] and repo_name[1] == r_name[1]:
                         value += "    "+tool[1]+"\n"
                         for built in inventory['built']:
                             if built[0] == tool[0]:
                                 value += "      Built: "+built[2]+"\n"
                         for enabled in inventory['enabled']:
                             if enabled[0] == tool[0]:
                                 value += "      Enabled: "+enabled[2]+"\n"
                         for image in inventory['images']:
                             if image[0] == tool[0]:
                                 value += "      Image name: "+image[2]+"\n"
                         for running in inventory['running']:
                             if running[0] == tool[0]:
                                 value += "      Status: "+running[2]+"\n"
             tmp_value = value.split("\n")
             if "Plugin: " in tmp_value[-2]:
                 value = "\n".join(value.split("\n")[:-2])
     else:
         value = "There was an issue with core inventory retrieval:\n"+str(response[1])+"\nPlease see vent.log for more details."
     self.inventory_mle.values=value.split("\n")
     self.inventory_mle.display()
     return
Exemple #36
0
class LogsForm(npyscreen.FormBaseNew):
    """ Logs form for the Vent CLI """
    action = None
    def while_waiting(self):
        """ Update the text with the logs from containers not logging to syslog """
        if self.action is None:
            self.action = Action()
            response = self.action.logs()
            if response[0]:
                value = "Logs for each Vent container found:\n"
                for container in logs:
                    value += "\n Container: "+container+"\n"
                    for log in logs[container]:
                        value += "    "+log+"\n"
                    value += "\n"
                self.logs_mle.values=value.split("\n")
                self.logs_mle.display()
            else:
                self.logs_mle.values=["There was an issue retrieving logs for Vent containers: ",
                                      str(response[1]),
                                      "Please see vent.log for more details."]
                self.logs_mle.display()
        return

    def create(self):
        """ Override method for creating FormBaseNew form """
        self.add_handlers({"^T": self.change_forms,"^Q": self.exit})
        self.add(npyscreen.TitleFixedText, name='Logs:', value='')
        self.logs_mle = self.add(npyscreen.Pager,
                                      values=['Checking for container logs, please wait...'])

    def exit(self, *args, **keywords):
        self.parentApp.switchForm("MAIN")

    def change_forms(self, *args, **keywords):
        """ Toggles back to main """
        change_to = "MAIN"

        # Tell the VentApp object to change forms.
        self.parentApp.change_form(change_to)