예제 #1
0
def get_connection_status():
    """Return the eth & wlan connection status of the specified probe,

    The only argument is mac, which should be the probe's MAC address
    Returned statuses will be either:
        invalid-mac
        unknown-mac
        {"eth0": 0 or 1, "wlan0": 1 or 0}

        For backwards compatibility:
        connected
    """
    mac = request.args.get('mac', '')
    if mac == '':
        return 'invalid-mac'

    mac = util.convert_mac(mac, 'storage')
    probe = database.get_probe(mac)
    if probe is None:
        return 'unknown-mac'

    status = util.is_probe_connected(probe.port)
    if status:
        con_stat = util.get_interface_connection_status(probe.port)
        if con_stat is not None:
            return con_stat
        else:
            return 'connected'

    return '{"eth0": 0, "wlan0": 0}'
예제 #2
0
def export_to_inventory(username, database):
    """Export an Ansible hosts file for 'username' at
    <ansible_root>/inventory/<username> from the supplied SQL database

    Each inventory entry will be in the following format:
    [<username>]
    <mac> ansible_host=localhost ansible_port=<port> probe_name=<name>
    ...
    """
    from probe_website.database import Probe

    dir_path = os.path.join(settings.ANSIBLE_PATH, 'inventory')
    if not os.path.exists(dir_path):
        makedirs(dir_path)

    user = database.get_user(username)
    with open(os.path.join(dir_path, username), 'w') as f:
        f.write('[{}]\n'.format(username))
        for probe in database.session.query(Probe).filter(Probe.user_id == user.id).all():
            if (probe.associated and
                    util.is_probe_connected(probe.port) and
                    database.valid_network_configs(probe) and
                    database.valid_database_configs(user)):
                entry = '{} ansible_host=localhost ansible_port={} username="******" probe_name="{}"'.format(
                            probe.custom_id,
                            probe.port,
                            username,
                            probe.name)
                f.write(entry + '\n')
예제 #3
0
def probes():
    """Render page for viewing all the user's probes. On POST: add,
    update or remove a probe.

    More specifically, the following can be done via POST:
        - Add a new probe
        - Remove a probe
        - Reboot a probe
        - Renew a probe's association period (if not already associated)
        - Push configurations to probes (i.e. run Ansible)
    """
    user = database.get_user(current_user.username)
    if request.method == 'POST':
        action = request.form.get('action', '')
        if action == 'new_probe':
            form_parsers.new_probe(current_user.username)
        elif action == 'reboot_probe':
            probe_id = request.form.get('probe_id', '')
            probe = database.get_probe(probe_id)
            if probe is not None and probe.user.username == current_user.username and probe.associated:
                success = util.reboot_probe(probe.port)
                if not success:
                    flash('Unable to reboot probe (possibly no connection)')
        elif action == 'remove_probe':
            probe_id = request.form.get('probe_id', '')
            success = database.remove_probe(current_user.username, probe_id)
            if not success:
                flash('Invalid probe ID', 'error')
            else:
                ansible.remove_host_config(probe_id)
                database.save_changes()
        elif action == 'renew_period':
            probe_id = request.form.get('probe_id', '')
            probe = database.get_probe(probe_id)
            if probe is not None and probe.user.username == current_user.username:
                probe.new_association_period()
                database.save_changes()
        elif action == 'push_config':
            # Only run one instance of Ansible at a time (for each user)
            if not ansible.is_ansible_running(current_user.username):
                # Export configs in the sql database to ansible readable configs
                for probe in database.session.query(Probe).filter(
                        Probe.user_id == user.id).all():
                    # Export script config
                    data = util.strip_id(database.get_script_data(probe))
                    ansible.export_host_config(probe.custom_id,
                                               {'host_script_configs': data},
                                               'script_configs')
                    # Export probe info config
                    ansible.export_host_config(
                        probe.custom_id, {
                            'probe_name': probe.name,
                            'probe_location': probe.location,
                            'probe_mac': probe.custom_id,
                            'probe_organization': user.get_organization()
                        }, 'probe_info')

                    if (probe.associated
                            and util.is_probe_connected(probe.port)
                            and database.valid_network_configs(
                                probe, with_warning=True)
                            and database.valid_database_configs(
                                user, with_warning=True)):
                        data = util.strip_id(
                            database.get_network_config_data(probe))
                        ansible.export_host_config(probe.custom_id,
                                                   {'networks': data},
                                                   'network_configs')
                # Check which probes are selected
                selected_probes = []
                for entry in request.form:
                    match = re.fullmatch('selected\-([0-9a-f]{12})', entry)
                    if match:
                        selected_probes.append(match.group(1))
                ansible.export_to_inventory(current_user.username, database,
                                            selected_probes)
                ansible.export_known_hosts(database)
                ansible.run_ansible_playbook(current_user.username)
            else:
                flash(messages.INFO_MESSAGE['ansible_already_running'], 'info')

        # Redirect to avoid re-POSTing
        return redirect(url_for('probes'))

    probes = database.get_all_probes_data(current_user.username)
    return render_template('probes.html',
                           probes=probes,
                           kibana_dashboard='probe-stats',
                           organization=user.get_organization())