コード例 #1
0
ファイル: nginx_plugin.py プロジェクト: kentwang929/install
    def write_plugin(self, out):
        count = 0  # number of server being monitored

        utils.print_step('Begin writing nginx plugin for collectd')
        out.write('LoadPlugin "nginx"\n')
        out.write('<Plugin "nginx">\n')

        self.plugin_usage()

        while count == 0:  # can only monitor one for this plugin
            url = utils.get_input(
                'Please enter the url that contains your '
                'nginx-status:\n(ex: localhost/nginx-status)\n'
                '(This plugin can only monitor one server)')
            utils.cprint()
            utils.print_step('Checking http response for %s' % url)
            res = utils.get_command_output('curl -s -i '+url)

            if res is None:
                ret = utils.INVALID_URL
            else:
                ret = utils.check_http_response(res)

            if ret == utils.NOT_AUTH:
                # skip for this case for now, ask for user/pass
                utils.eprint(
                    'Authorization server status is required, please '
                    'try again.\n')
            elif ret == utils.NOT_FOUND or ret == utils.INVALID_URL:
                utils.print_failure()
                utils.eprint(
                    'Invalid url was provided, please try '
                    'again.\n')
            elif ret == utils.HTTP_OK:
                utils.print_success()
                res = self.check_nginx_status(res)
                if not res:
                    utils.print_warn(
                        'The url you have provided '
                        'does not seem to be the correct nginx_status '
                        'page.  Incorrect server-status will not be '
                        'recorded by collectd.')
                    res = utils.ask(
                        'Would you like to record this url anyway?', 'no')

                if res:
                    plugin_instance = (
                        '    URL "{url}"\n').format(url=url)
                    utils.cprint('Result from:\n{}'.format(plugin_instance))
                    res = utils.ask(
                        'Is this the correct url to monitor?')
                    if res:
                        count = count + 1
                        out.write(plugin_instance)
        out.write('</Plugin>\n')
        return count
コード例 #2
0
ファイル: nginx_plugin.py プロジェクト: kentwang929/install
    def check_dependency(self):
        utils.print_step('Checking dependency')
        utils.print_step('  Checking http_stub_status_module')

        cmd_res = utils.get_command_output(
            'nginx -V 2>&1 | grep -o '
            'with-http_stub_status_module')
        if cmd_res is None:
            utils.print_warn(
                'http_stub_status_module is not enabled.\n'
                'This module is required to enable the '
                'nginx-status page.')
            self.raise_error('http_stub_status_module')
        utils.print_success()
コード例 #3
0
def check_http_response(http_res):
    http_status_re = re.match('HTTP/1.1 (\d* [\w ]*)\s', http_res)
    if http_status_re is None:
        utils.print_warn('Invalid http response header!')
        sys.exit(1)

    http_code = http_status_re.group(1)

    if('401 Unauthorized' in http_code):
        return NOT_AUTH
    elif('404 Not Found' in http_code):
        return NOT_FOUND
    elif('200 OK' in http_code):
        return HTTP_OK
    else:
        return INVALID_URL
コード例 #4
0
def check_http_response(http_res):
    http_status_re = re.match('HTTP/1.1 (\d* [\w ]*)\s', http_res)
    if http_status_re is None:
        utils.print_warn('Invalid http response header!')
        sys.exit(1)

    http_code = http_status_re.group(1)

    if ('401 Unauthorized' in http_code):
        return NOT_AUTH
    elif ('404 Not Found' in http_code):
        return NOT_FOUND
    elif ('200 OK' in http_code):
        return HTTP_OK
    else:
        return INVALID_URL
コード例 #5
0
ファイル: gather_metrics.py プロジェクト: kentwang929/install
def installer_menu(app_list, support_dict):
    """
    provide the menu and prompts for the user to interact with the installer

    installer flow:
      1. show selections
      2. installs a plugin
      3. updates install state (not yet implemented)
      4. menu changes with install state (not yet implemented)

    Option  Name                 State      Date
    (1)     mysql Installer      Installed  (installation date)
    (2)     apache Installer     Incomplete
    (3)     postgres Installer   New

    if resinstall,
      warn that this will overwrite {conf_file}.
    """
    exit_cmd = [
        'quit', 'q', 'exit']

    # the format of each row in installing menu
    menu_rowf = (
        '{index:{index_pad}} {name:{name_pad}} '
        '{state:{state_pad}} {date}')
    index_pad = 7
    name_pad = 30
    state_pad = 12
    color = utils.BLACK  # default

    res = None  # to begin the prompt loop
    utils.cprint()
    utils.cprint(
        'We have detected the following applications that are '
        'supported by our collectd installers.')

    while res not in exit_cmd:
        utils.cprint()
        utils.cprint(
            'The following are the available installers:')

        utils.cprint(
            menu_rowf.format(
                index='Option', index_pad=index_pad,
                name='Name', name_pad=name_pad,
                state='State', state_pad=state_pad,
                date='Date'))

        install_state = check_install_state(app_list)
        for i, app in enumerate(app_list):
            index = '({i})'.format(i=i)
            app_installer = '{} installer'.format(app)
            app_state = install_state[app]['state']
            if 'date' in install_state[app]:
                date = install_state[app]['date']
            else:
                date = ''

            if app_state == NEW:
                state = 'New'
                color = utils.GREEN
            elif app_state == INCOMPLETE:
                state = 'Incomplete'
                color = utils.YELLOW
            elif app_state == INSTALLED:
                state = 'Installed'
                color = utils.BLACK

            utils.print_color_msg(
                menu_rowf.format(
                    index=index, index_pad=index_pad,
                    name=app_installer, name_pad=name_pad,
                    state=state, state_pad=state_pad,
                    date=date), color)
        utils.cprint()
        utils.cprint(
            'To pick a installer, type in the corresponding number '
            'next to the installer.\n'
            'To quit out of this installer, type "[Q]uit" or "exit".')
        res = utils.get_input(
            'Which installer would you like to run?').lower()
        if res not in exit_cmd:
            option = check_option(res, len(app_list))
            if option is not None:
                app = support_dict[app_list[option]]
                utils.cprint(
                    'You have selected ({option}) {app} installer'.format(
                        option=option, app=app_list[option]))
                app_state = install_state[app_list[option]]['state']
                if app_state == INSTALLED:
                    utils.print_warn(
                        'You have previously used this installer\n'
                        'Reinstalling will overwrite the old configuration '
                        'file, {}.'.format(app['conf_name']))
                confirm = utils.ask(
                    'Would you like to proceed with '
                    'the installer?')
                if confirm:
                    Installer = getattr(
                        importlib.import_module(
                            app['module']),
                            app['class_name'])
                    instance = Installer(
                        config.OPERATING_SYSTEM,
                        app['plugin_name'],
                        app['conf_name'])
                    if instance.install():
                        install_state[app_list[option]]['state'] = INSTALLED
                    else:
                        install_state[app_list[option]]['state'] = INCOMPLETE
                    install_state[app_list[option]]['date'] = '{:%c}'.format(
                        datetime.now())
                    update_install_state(install_state)
            else:
                utils.print_reminder('Invalid option.')
コード例 #6
0
ファイル: gather_metrics.py プロジェクト: kentwang929/install
    if res < 0 or res >= max_length:
        return None
    return res

if __name__ == '__main__':
    check_version()
    conf.check_collectd_exists()
    conf.check_collectd_path()

    # the first argument will be the log file
    arg_len = len(sys.argv)
    if arg_len == 3:
        config.OPERATING_SYSTEM = sys.argv[1]
        config.INSTALL_LOG = sys.argv[2]
    elif arg_len == 1:
        config.INSTALL_LOG = '/dev/null'
    else:
        utils.eprint('Invalid arguments.')
        sys.exit(1)

    if config.DEBUG:
        utils.print_warn('DEBUG IS ON')

    (s_list, s_dict) = detect_applications()

    try:
        installer_menu(s_list, s_dict)
    except KeyboardInterrupt:
        utils.eprint('\nQuitting the installer via keyboard interrupt.')
        sys.exit(1)
コード例 #7
0
ファイル: redis_plugin.py プロジェクト: kentwang929/install
    def write_plugin(self, out):
        """
        Flow:
        create /opt/collectd/plugins/python directory
        mv the redis_info.py into there
        ask for instance name
        then ask for hostname, port
        ask for auth
        """
        count = 0  # number of server being monitored
        iname_list = []
        server_list = []
        first_prompt = True
        python_plugin_path = '/opt/collectd/plugins/python'
        if config.DEBUG:
            plugin_src = '{}/{}'.format(
                config.PLUGIN_EXTENSION_DIR, 'redis_info.py')
        else:
            plugin_src = '{}/{}/{}'.format(
                config.APP_DIR,
                config.PLUGIN_EXTENSION_DIR,
                'redis_info.py')

        metrics = (
            '    Verbose false\n'
            '    # Catch Redis metrics (prefix with Redis_)\n'
            '    Redis_uptime_in_seconds "gauge"\n'
            '    Redis_used_cpu_sys "counter"\n'
            '    Redis_used_cpu_user "counter"\n'
            '    Redis_used_cpu_sys_children "counter"\n'
            '    Redis_used_cpu_user_children "counter"\n'
            '    Redis_uptime_in_days "gauge"\n'
            '    Redis_lru_clock "counter"\n'
            '    Redis_connected_clients "gauge"\n'
            '    Redis_connected_slaves "gauge"\n'
            '    Redis_client_longest_output_list "gauge"\n'
            '    Redis_client_biggest_input_buf "gauge"\n'
            '    Redis_blocked_clients "gauge"\n'
            '    Redis_expired_keys "counter"\n'
            '    Redis_evicted_keys "counter"\n'
            '    Redis_rejected_connections "counter"\n'
            '    Redis_used_memory "bytes"\n'
            '    Redis_used_memory_rss "bytes"\n'
            '    Redis_used_memory_peak "bytes"\n'
            '    Redis_used_memory_lua "bytes"\n'
            '    Redis_mem_fragmentation_ratio "gauge"\n'
            '    Redis_changes_since_last_save "gauge"\n'
            '    Redis_instantaneous_ops_per_sec "gauge"\n'
            '    Redis_rdb_bgsave_in_progress "gauge"\n'
            '    Redis_total_connections_received "counter"\n'
            '    Redis_total_commands_processed "counter"\n'
            '    Redis_total_net_input_bytes "counter"\n'
            '    Redis_total_net_output_bytes "counter"\n'
            '    Redis_keyspace_hits "derive"\n'
            '    Redis_keyspace_misses "derive"\n'
            '    Redis_latest_fork_usec "gauge"\n'
            '    Redis_connected_slaves "gauge"\n'
            '    Redis_repl_backlog_first_byte_offset "gauge"\n'
            '    Redis_master_repl_offset "gauge"\n')

        slave_metrics = (
            '    #Slave-Only'
            '    Redis_master_last_io_seconds_ago "gauge"\n'
            '    Redis_slave_repl_offset "gauge"\n')

        utils.print_step(
            'Begin configuring Redis python plugin for collectd')

        # create directory if it doesn't exist
        if not utils.check_path_exists(python_plugin_path):
            utils.print_step(
                '  Creating directory {} '
                'for collectd python plugin'.format(python_plugin_path))
            res = utils.call_command(
                'mkdir -p {}'.format(python_plugin_path))
            if res == 0:
                utils.print_success()
            else:
                utils.print_failure()
                raise Exception('Unable to create directory.')
                
        utils.print_step(
            '  Moving python plugin')
        res = utils.call_command(
            'cp {src} {dst}'.format(
                src=plugin_src, dst=python_plugin_path))
        if res == 0:
            utils.print_success()
        else:
            utils.print_failure()
            raise Exception('Failed to move the plugin.')
            
        utils.print_step('Begin writing redis configuration for collectd')
        # pull comment and append to it
        if not self.pull_comment(out):
            utils.print_warn('Failed to pull comment.')

        out.write('\n\n')
        out.write(
            '<LoadPlugin python>\n'
            '  Globals true\n'
            '</LoadPlugin>\n\n'
            '<Plugin python>\n'
            '  ModulePath "{path}"\n'
            '  Import "redis_info"\n'.format(path=python_plugin_path))

        while utils.ask('Would you like to add a server to monitor?'):
            iname = utils.prompt_and_check_input(
                prompt=(
                    '\nHow would you like to name this monitoring instance?\n'
                    '(How it should appear on your wavefront metric page, \n'
                    'space between words will be removed)'),
                check_func=(
                    lambda x: x.replace(" ", "") not in iname_list),
                usage=(
                    '{} has already been used.'.format),
                usage_fmt=True).replace(" ", "")

            host = utils.prompt_and_check_input(
                prompt=(
                    'Please enter the hostname that connects to your\n'
                    'redis server: (ex: localhost)'),
                check_func=utils.hostname_resolves,
                usage='{} does not resolve.'.format,
                usage_fmt=True)

            port = utils.prompt_and_check_input(
                prompt=(
                    'What is the TCP-port used to connect to the host? '),
                check_func=utils.check_valid_port,
                usage=(
                    'A valid port is a number '
                    'between (0, 65535) inclusive.\n'),
                default='6379')

            if (host, port) in server_list:
                utils.eprint(
                    'You have already monitored {host}:{port}.'.format(
                        host=host, port=port))
                continue

            plugin_instance = (
                '    Instance "{iname}"\n'
                '    Host "{host}"\n'
                '    Port "{port}"\n').format(
                    iname=iname,
                    host=host, port=port)

            if utils.ask(
                    'Is there an authorization password set up for\n'
                    '{host}:{port}'.format(host=host, port=port),
                    default=None):
                auth = utils.get_input(
                    'What is the authorization password?')
                plugin_instance += (
                    '    Auth "{auth}"\n'.format(auth=auth))

            slave = utils.ask(
                'Is this a slave server?', default='no')

            utils.cprint()
            if slave:
                utils.cprint('(slave server)')
            utils.cprint('Result: \n{}'.format(plugin_instance))
            res = utils.ask('Is the above information correct?')

            if res:
                utils.print_step('Saving instance')
                count = count + 1
                iname_list.append(iname)
                server_list.append((host, port))
                out.write(
                    '\n  <Module redis_info>\n'
                    '{plugin_instance}'
                    '{metrics}'.format(
                        plugin_instance=plugin_instance,
                        metrics=metrics))
                if slave:
                    out.write(slave_metrics)
                out.write('  </Module>\n')
                utils.print_success()
            else:
                utils.cprint('This instance is not saved.')
        out.write('</Plugin>\n')
        return count
コード例 #8
0
ファイル: apache_plugin.py プロジェクト: kentwang929/install
    def write_plugin(self, out):
        count = 0
        server_list = []
        sv_list = []
        overwrite = True

        utils.print_step('Begin writing apache plugin for collectd')
        out.write('LoadPlugin "apache"\n')
        out.write('<Plugin "apache">\n')
        self.apache_plugin_usage()

        while utils.ask('Would you like to add a server to monitor?'):
            sv_name = utils.get_input(
                'How would you like to name this server? '
                '(space between words will be removed)').replace(" ", "")

            if sv_name in sv_list:
                utils.cprint('You have already used {}.'.format(
                    sv_name))
                continue

            url = utils.get_input(
                'Please enter the url that contains your '
                'server-status (ex: www.apache.org/server_status):')
            utils.cprint()

            if url in server_list:
                utils.eprint(
                    'You have already added this {} server.'.format(url))
                continue

            utils.print_step('Checking http response for %s' % url)
            res = utils.get_command_output('curl -s -i '+url)

            if res is None:
                ret = utils.INVALID_URL
            else:
                ret = utils.check_http_response(res)

            if ret == utils.NOT_AUTH:
                # skip for this case for now, ask for user/pass
                utils.eprint(
                    'Authorization server status is required, please '
                    'try again.\n')
            elif ret == utils.NOT_FOUND or ret == utils.INVALID_URL:
                utils.print_failure()
                utils.eprint(
                    'Invalid url was provided, please try '
                    'again.\n')
            elif ret == utils.HTTP_OK:
                utils.print_success()
                overwrite = True
                status = self.check_apache_server_status(res)
                if status is None:
                    utils.print_warn(
                        'The url you have provided '
                        'does not seem to be the correct server_status '
                        'page.  Incorrect server-status will not be '
                        'recorded by collectd.')
                    overwrite = utils.ask(
                        'Would you like to record this url anyway?', 'no')

                if overwrite:
                    if status:
                        utils.cprint(status)
                    url_auto = url+'?auto'
                    plugin_instance = (
                        '  <Instance "{instance}">\n'
                        '    URL "{url}"\n'
                        '  </Instance>\n').format(instance=sv_name,
                                                  url=url_auto)
                    utils.cprint()
                    utils.cprint(
                        'Your url is appended with ?auto to convert '
                        'the content into machine readable code.\n'
                        '{}'.format(plugin_instance))
                    res = utils.ask(
                        'Is this the correct status to monitor?')
                    if res:
                        utils.print_step('Saving instance')
                        count = count + 1
                        server_list.append(url)
                        sv_list.append(sv_name)
                        out.write(plugin_instance)
                        utils.print_success()
                    else:
                        utils.cprint('Instance is not saved.')
        out.write('</Plugin>\n')
        return count
コード例 #9
0
def write_apache_plugin(out):
    out.write('LoadPlugin "apache"\n')
    out.write('<Plugin "apache">\n')

    count = 0
    server_list = []

    apache_plugin_usage()
    sys.stdout.write(
        'To check whether the server-status page is working, please visit\n'
        '\tyour-server-name/server-status\n'
        'It should look similar to\n'
        '\tapache.org/server-status\n')

    while utils.ask('Would you like to add a server to monitor?'):
        url = utils.get_input(
            'Please enter the url that contains your ' +
            'server-status (ex: www.apache.org/server_status):')
        print
        utils.print_step('Checking http response for %s' % url)
        res = utils.get_command_output('curl -s -i '+url)

        if res is None:
            ret = INVALID_URL
        else:
            ret = check_http_response(res)

        if ret == NOT_AUTH:
            # skip for this case for now, ask for user/pass
            sys.stderr.write(
                'Authorization server status is required, please '
                'try again.\n')
        elif ret == NOT_FOUND or ret == INVALID_URL:
            utils.print_failure()
            sys.stderr.write(
                'Invalid url was provided, please try '
                'again.\n')
        elif ret == HTTP_OK:
            utils.print_success()
            if url in server_list:
                utils.print_warn(
                    'You have already added this server instance.')
            else:
                res = check_apache_server_status(res)
                if res is None:
                    utils.print_warn(
                        'The url you have provided '
                        'does not seem to be the correct server_status '
                        'page.  Incorrect server-status will not be recorded '
                        'by collectd.')
                    utils.ask(
                        'Would you like to record this url anyway?', 'no')
                else:
                    print res
                    res = utils.ask('Is this the correct status to monitor?')
                    print
                    if res:
                        count = count + 1
                        server_list.append(url)
                        instance = 'apache%d' % count
                        url_auto = url+'?auto'
                        plugin_instance = (
                            '  <Instance "{instance}">\n'
                            '    URL "{url}"\n'
                            '  </Instance>\n').format(instance=instance,
                                                      url=url_auto)
                        out.write(plugin_instance)

    out.write('</Plugin>\n')
    return count
コード例 #10
0
def install_apache_plugin():
    install = check_install_state('Apache')
    print
    if not install:
        sys.stdout.write(
            'This script has detected that you have apache installed and '
            'running.')
        res = utils.ask(
            'Would you like to run the apache plugin installer to '
            'enable collectd to collect data from apache?')
    else:
        print 'You have previously installed this plugin.'
        res = utils.ask(
            'Would you like to reinstall this plugin?', default='no')

    if not res:
        return

    apache_title()
    print
    sys.stdout.write(
        'To enable collectd plugin with Apache, the following '
        'steps need to be taken:\n'
        '1. mod_status for apache needs to be enabled. (Default is enabled)\n'
        '2. ExtendedStatus needs to be turned on.  (Default is off)\n'
        '3. Enable the server-status handler for each virtual host.\n')

    _ = raw_input('Press Enter to continue')
    utils.print_step('Begin collectd Apache plugin installer')

    # check point
    #  - check dependency
    #  - change system file
    #  - check mod status
    #  - TODO: pull template
    #  - prompt for user information
    if not utils.command_exists('curl'):
        utils.exit_with_failure('Curl is needed for this plugin.')

    # ubuntu check
    # Assumption:
    # -latest apache2 is installed and the installation
    # -directory is in the default place
    utils.print_step('  Checking if mod_status is enabled')
    cmd_res = utils.get_command_output('ls /etc/apache2/mods-enabled')
    if 'status.conf' not in cmd_res or 'status.load' not in cmd_res:
        utils.print_step('Enabling apache2 mod_status module.')
        ret = utils.call_command('sudo a2enmod status')
        if ret != 0:
            utils.exit_with_message('a2enmod command was not found')
    utils.print_success()
    print
    sys.stdout.write(
        'In order to enable the apache plugin with collectd, the '
        'ExtendedStatus setting must be turned on.\n'
        'This setting can be turned on by having "ExtendedStatus on" '
        'in one of the .conf file.\n')

    sys.stdout.write(
        'If you have already enabled this status, '
        'answer "no" to the next question '
        'and ignore the following warning.\n'
        'If you would like us to enable this status, answer "yes" and we will '
        'include a extendedstatus.conf file in your apache folder.\n')

    res = utils.ask(
        'Would you like us to enable '
        'the ExtendedStatus?')

    # missing the flow where user wants to turn on the setting themselves.
    if res:
        # include the config file in /apache2/conf-enabled
        conf_dir = '/etc/apache2/conf-enabled'
        utils.print_step('Checking if ' + conf_dir + ' exists.')
        if utils.check_path_exists(conf_dir):
            # pull config file here
            utils.print_success()
            include_apache_es_conf(conf_dir)
            sys.stdout.write(
                '\nextendedstatus.conf is now included in the ' +
                conf_dir + ' dir.\n')
            utils.print_step('Restarting apache')
            ret = utils.call_command(
                'service apache2 restart >> ' +
                config.INSTALL_LOG + ' 2>&1')
            if ret != 0:
                utils.exit_with_message('Failed to restart apache service.')
            utils.print_success()
        else:
            exit_with_message(conf_dir + ' dir does not exist, ' +
                              'please consult [email protected]' +
                              'for help.')
    else:
        utils.print_warn(
            'Collectd plugin will not work with apache if the '
            'ExtendedStatus is not turned on.')

    # Begin writing apache plugin
    print
    utils.print_step('Begin writing apache plugin for collectd')
    plugin_file = 'wavefront_temp_apache.conf'
    out = utils.write_file(plugin_file)
    error = False
    if out is None:
        utils.exit_with_message('')

    try:
        res = write_apache_plugin(out)
    except:
        sys.stderr.write('Unexpected flow.\n')
        error = True
    finally:
        out.close()
        if error:
            sys.stderr.write('Closing and removing temp file.\n')
            utils.call_command('rm ' + plugin_file)
            sys.exit(1)

    # if there was at least one instance being monitor
    if res:
        utils.print_step('Copying the plugin file to the correct place')
        outfile = 'wavefront_apache.conf'
        cp_cmd = (
            'cp {infile} {conf_dir}/{outfile}').format(
                infile=plugin_file,
                conf_dir=COLLECTD_CONF_DIR,
                outfile=outfile)
        ret = utils.call_command(cp_cmd)

        if ret == 0:
            utils.print_success()
            print 'Apache_plugin has been written successfully.'
            sys.stdout.write(
                'wavefront_apache.conf can be found at %s.\n' %
                COLLECTD_CONF_DIR)
        else:
            exit_with_message('Failed to copy the plugin file.\n')
    else:
        sys.stdout.write('You did not provide any instance to monitor.\n')

    utils.call_command('rm {}'.format(plugin_file))
コード例 #11
0
    -include RemotePort for outbounds connections
        i.e. the servers we are connecting to
    """
    try:
        out = open('10-tcpconns.conf', 'w')
    except IOError:
        sys.stderr.write('Unable to open tcpcons.conf file\n')
        sys.exit(1)
    except:
        sys.stderr.write(
            'Unexpected error.  Unable to write tcpcons.conf file\n')
        sys.exit(1)

    tcp_plugin_bef = (
        'LoadPlugin tcpconns\n'
        '<Plugin "tcpconns">\n'
        '  ListeningPorts false\n')

    out.write(tcp_plugin_bef)
    for port in open_ports:
        out.write('  LocalPort "%d"\n' % port)
    # no remote port yet
    out.write('</Plugin>\n')
    out.close()


if __name__ == '__main__':
    utils.print_warn('This is for testing conf_collected_plugin.py')
    utils.cprint(COLLECTD_HOME)
    utils.cprint(COLLECTD_CONF_DIR)
コード例 #12
0
def write_apache_plugin(out):
    out.write('LoadPlugin "apache"\n')
    out.write('<Plugin "apache">\n')

    count = 0
    server_list = []

    apache_plugin_usage()
    sys.stdout.write(
        'To check whether the server-status page is working, please visit\n'
        '\tyour-server-name/server-status\n'
        'It should look similar to\n'
        '\tapache.org/server-status\n')

    while utils.ask('Would you like to add a server to monitor?'):
        url = utils.get_input(
            'Please enter the url that contains your ' +
            'server-status (ex: www.apache.org/server_status):')
        print
        utils.print_step('Checking http response for %s' % url)
        res = utils.get_command_output('curl -s -i ' + url)

        if res is None:
            ret = INVALID_URL
        else:
            ret = check_http_response(res)

        if ret == NOT_AUTH:
            # skip for this case for now, ask for user/pass
            sys.stderr.write('Authorization server status is required, please '
                             'try again.\n')
        elif ret == NOT_FOUND or ret == INVALID_URL:
            utils.print_failure()
            sys.stderr.write('Invalid url was provided, please try '
                             'again.\n')
        elif ret == HTTP_OK:
            utils.print_success()
            if url in server_list:
                utils.print_warn(
                    'You have already added this server instance.')
            else:
                res = check_apache_server_status(res)
                if res is None:
                    utils.print_warn(
                        'The url you have provided '
                        'does not seem to be the correct server_status '
                        'page.  Incorrect server-status will not be recorded '
                        'by collectd.')
                    utils.ask('Would you like to record this url anyway?',
                              'no')
                else:
                    print res
                    res = utils.ask('Is this the correct status to monitor?')
                    print
                    if res:
                        count = count + 1
                        server_list.append(url)
                        instance = 'apache%d' % count
                        url_auto = url + '?auto'
                        plugin_instance = ('  <Instance "{instance}">\n'
                                           '    URL "{url}"\n'
                                           '  </Instance>\n').format(
                                               instance=instance, url=url_auto)
                        out.write(plugin_instance)

    out.write('</Plugin>\n')
    return count
コード例 #13
0
def install_apache_plugin():
    install = check_install_state('Apache')
    print
    if not install:
        sys.stdout.write(
            'This script has detected that you have apache installed and '
            'running.')
        res = utils.ask('Would you like to run the apache plugin installer to '
                        'enable collectd to collect data from apache?')
    else:
        print 'You have previously installed this plugin.'
        res = utils.ask('Would you like to reinstall this plugin?',
                        default='no')

    if not res:
        return

    apache_title()
    print
    sys.stdout.write(
        'To enable collectd plugin with Apache, the following '
        'steps need to be taken:\n'
        '1. mod_status for apache needs to be enabled. (Default is enabled)\n'
        '2. ExtendedStatus needs to be turned on.  (Default is off)\n'
        '3. Enable the server-status handler for each virtual host.\n')

    _ = raw_input('Press Enter to continue')
    utils.print_step('Begin collectd Apache plugin installer')

    # check point
    #  - check dependency
    #  - change system file
    #  - check mod status
    #  - TODO: pull template
    #  - prompt for user information
    if not utils.command_exists('curl'):
        utils.exit_with_failure('Curl is needed for this plugin.')

    # ubuntu check
    # Assumption:
    # -latest apache2 is installed and the installation
    # -directory is in the default place
    utils.print_step('  Checking if mod_status is enabled')
    cmd_res = utils.get_command_output('ls /etc/apache2/mods-enabled')
    if 'status.conf' not in cmd_res or 'status.load' not in cmd_res:
        utils.print_step('Enabling apache2 mod_status module.')
        ret = utils.call_command('sudo a2enmod status')
        if ret != 0:
            utils.exit_with_message('a2enmod command was not found')
    utils.print_success()
    print
    sys.stdout.write(
        'In order to enable the apache plugin with collectd, the '
        'ExtendedStatus setting must be turned on.\n'
        'This setting can be turned on by having "ExtendedStatus on" '
        'in one of the .conf file.\n')

    sys.stdout.write(
        'If you have already enabled this status, '
        'answer "no" to the next question '
        'and ignore the following warning.\n'
        'If you would like us to enable this status, answer "yes" and we will '
        'include a extendedstatus.conf file in your apache folder.\n')

    res = utils.ask('Would you like us to enable ' 'the ExtendedStatus?')

    # missing the flow where user wants to turn on the setting themselves.
    if res:
        # include the config file in /apache2/conf-enabled
        conf_dir = '/etc/apache2/conf-enabled'
        utils.print_step('Checking if ' + conf_dir + ' exists.')
        if utils.check_path_exists(conf_dir):
            # pull config file here
            utils.print_success()
            include_apache_es_conf(conf_dir)
            sys.stdout.write('\nextendedstatus.conf is now included in the ' +
                             conf_dir + ' dir.\n')
            utils.print_step('Restarting apache')
            ret = utils.call_command('service apache2 restart >> ' +
                                     config.INSTALL_LOG + ' 2>&1')
            if ret != 0:
                utils.exit_with_message('Failed to restart apache service.')
            utils.print_success()
        else:
            exit_with_message(conf_dir + ' dir does not exist, ' +
                              'please consult [email protected]' +
                              'for help.')
    else:
        utils.print_warn('Collectd plugin will not work with apache if the '
                         'ExtendedStatus is not turned on.')

    # Begin writing apache plugin
    print
    utils.print_step('Begin writing apache plugin for collectd')
    plugin_file = 'wavefront_temp_apache.conf'
    out = utils.write_file(plugin_file)
    error = False
    if out is None:
        utils.exit_with_message('')

    try:
        res = write_apache_plugin(out)
    except:
        sys.stderr.write('Unexpected flow.\n')
        error = True
    finally:
        out.close()
        if error:
            sys.stderr.write('Closing and removing temp file.\n')
            utils.call_command('rm ' + plugin_file)
            sys.exit(1)

    # if there was at least one instance being monitor
    if res:
        utils.print_step('Copying the plugin file to the correct place')
        outfile = 'wavefront_apache.conf'
        cp_cmd = ('cp {infile} {conf_dir}/{outfile}').format(
            infile=plugin_file, conf_dir=COLLECTD_CONF_DIR, outfile=outfile)
        ret = utils.call_command(cp_cmd)

        if ret == 0:
            utils.print_success()
            print 'Apache_plugin has been written successfully.'
            sys.stdout.write('wavefront_apache.conf can be found at %s.\n' %
                             COLLECTD_CONF_DIR)
        else:
            exit_with_message('Failed to copy the plugin file.\n')
    else:
        sys.stdout.write('You did not provide any instance to monitor.\n')

    utils.call_command('rm {}'.format(plugin_file))