Пример #1
0
    def check_socket_path(self, path):
        if path is None:
            return False
        # if it begins with ~ then do expand user

        if self.os == config.DEBIAN:
            socket_re = re.match(
                r'mysqld.sock$|(~/|/)(.*/)*mysqld.sock$', path)
        if self.os == config.REDHAT:
            socket_re = re.match(
                r'mysql.sock$|(~/|/)(.*/)*mysql.sock$', path)

        if socket_re is None:
            utils.eprint(
                'Invalid path was given.\n'
                ' -filename has to end with .sock.\n'
                ' -Debian uses mysqld.sock, Redhat uses mysql.sock\n'
                ' -If relative path is used, please add ~/ '
                'to the beginning')
            return False

        if socket_re.group(1) == '~/':
            res = utils.check_path_exists(path, expand=True, debug=True)
        else:
            res = utils.check_path_exists(path, debug=True)

        if not res:
            utils.eprint(
                'Invalid path was given. '
                'Could not find {}.'.format(path))

        return res
Пример #2
0
def check_http_response(url):
    """
    check if the url is a valid

    Input:
        url string: the url provided by the user
    Output:
        ret_val bool:
            True if the url is valid and returns 200 OK
            False otherwise
    """
    ret_val = False
    utils.print_step('Checking http response for {url}'.format(url=url))
    res = utils.get_command_output('curl -s --head {url}'.format(url=url))

    if res is None:
        ret_code = utils.INVALID_URL
    else:
        ret_code = utils.get_http_return_code(res)

    if ret_code == utils.NOT_AUTH:
        # skip for this case for now, ask for user/pass
        utils.print_failure()
        utils.eprint('Authorization is required, please ' 'try again.\n')
    elif ret_code == utils.NOT_FOUND or ret_code == utils.INVALID_URL:
        utils.print_failure()
        utils.eprint('Invalid url was provided, please try ' 'again.\n')
    elif ret_code == utils.HTTP_OK:
        utils.print_success()
        ret_val = True

    return ret_val
Пример #3
0
    def collect_data(self):
        """
        data = {
            servers: []
        }
        """
        data = {'servers': []}
        server_list = []

        while utils.ask('\nWould you like to add a server to monitor?'):
            (host, port) = p_utils.get_host_and_port(def_port='11211')
            if (host, port) in server_list:
                utils.eprint(
                    'You have already added this {host}:{port}.'.format(
                        host=host, port=port))
                continue

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

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

            if res:
                utils.print_step('Saving instance')
                server_list.append((host, port))
                data['servers'].append('{host}:{port}'.format(host=host,
                                                              port=port))
                utils.print_success()
            else:
                utils.cprint('This instance is not saved.')

        return data
Пример #4
0
def check_url(url, url_list=[]):
    """
    check if the url provided is a valid url

    Input:
        url string: the url provided by the user
        url_list []string: list of url user has monitored already
    Output:
        True if the user provides a valid url
        False otherwise
    """
    if url is None:
        return False

    if not utils.check_url_scheme(url):
        utils.print_color_msg(
            '\nPlease provide the url scheme.',
            utils.YELLOW)
        return False

    # check repeat
    if url in url_list:
        utils.eprint(
            'You have already added this {}'.format(url))
        return False

    if not check_http_response(url):
        return False

    return True
Пример #5
0
    def edit_cass_conf(self, out, plugin_instance):
        """
        -read cass file
        -write to the temp file
        -replace ServiceURL line
        -close the read file
        """
        if config.DEBUG:
            filepath = '{conf_dir}/{conf_name}'.format(
                conf_dir=config.PLUGIN_CONF_DIR,
                conf_name=self.conf_name)
        else:
            filepath = '{app_dir}/{conf_dir}/{conf_name}'.format(
                app_dir=config.APP_DIR,
                conf_dir=config.PLUGIN_CONF_DIR,
                conf_name=self.conf_name)

        try:
            with open(filepath) as cfile:
                for line in cfile:
                    url_re = re.search(
                        r'ServiceURL "CHANGE_THIS"', line)
                    if url_re is None:
                        out.write(line)
                    else:
                        out.write(plugin_instance)
        except (IOError, OSError) as e:
            utils.eprint('Cannot open {}'.format(filepath))
            raise Exception(
                  'Error: {}\n'
                  'Cannot open {}.'.format(e, filepath))
Пример #6
0
def check_url(url, url_list=[]):
    """
    check if the url provided is a valid url

    Input:
        url string: the url provided by the user
        url_list []string: list of url user has monitored already
    Output:
        True if the user provides a valid url
        False otherwise
    """
    if url is None:
        return False

    if not utils.check_url_scheme(url):
        utils.print_color_msg('\nPlease provide the url scheme.', utils.YELLOW)
        return False

    # check repeat
    if url in url_list:
        utils.eprint('You have already added this {}'.format(url))
        return False

    if not check_http_response(url):
        return False

    return True
Пример #7
0
    def collect_data(self):
        """
        data = {
            instance_name: {
                host: value
                port: value
            }
        }
        """
        data = {}
        iname_list = []
        server_list = []

        while utils.ask('\nWould 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, port) = p_utils.get_host_and_port(def_port='11211')

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

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

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

            if res:
                utils.print_step('Saving instance')
                iname_list.append(iname)
                server_list.append((host, port))
                data[iname] = {
                    "host": host,
                    "port": port
                }
                utils.print_success()
            else:
                utils.cprint('This instance is not saved.')

        return data
Пример #8
0
    def collect_data(self):
        """
        data = {
            servers: []
        }
        """
        data = {
            'servers': []
        }
        server_list = []

        while utils.ask('\nWould you like to add a server to monitor?'):
            (host, port) = p_utils.get_host_and_port(def_port='6379')
            if (host, port) in server_list:
                utils.eprint(
                    'You have already added this {host}:{port}.'.format(
                        host=host, port=port))
                continue

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

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

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

            if res:
                utils.print_step('Saving instance')
                server_list.append((host, port))
                if protected:
                    url = (
                        ':{auth}@{host}:{port}').format(
                            auth=auth,
                            host=host,
                            port=port)
                else:
                    url = (
                        '{host}:{port}').format(
                            host=host, port=port)
                data['servers'].append(url)
                utils.print_success()
            else:
                utils.cprint('This instance is not saved.')

        return data
Пример #9
0
    def clean_plugin_write(self):
        """
        Prevent unfinished config file from being written into the directory

        Create and write to a temporary file.  Use try catch block to call
        write_plugin function.  If the configuration file is written
        successfully, then it will be copied over to the correct place.
        """
        temp_file = 'wavefront_temp_{0}.conf'.format(utils.random_string(7))
        error = None

        try:
            with open(temp_file, 'w') as out:
                try:
                    data = self.collect_data()
                    res = self.output_config(data, out)
                except KeyboardInterrupt as e:
                    error = e
                except Exception as e:
                    error = e
                finally:
                    if error:
                        utils.eprint('\nClosing and removing temp file.\n')
                        utils.call_command('rm ' + temp_file)
                        raise error
        except (IOError, OSError) as e:
            utils.eprint('Cannot open {}'.format(filepath))
            raise Exception(
                  'Error: {}\n'
                  'Cannot open {}.'.format(e, filepath))

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

            if ret == 0:
                utils.print_success()
                utils.cprint(
                    '{0} can be found at {1}.'.format(
                        self.conf_name,
                        self.conf_dir))
            else:
                utils.call_command('rm {}'.format(temp_file))
                raise Exception('Failed to copy the plugin file.\n')
        else:
            utils.call_command('rm {}'.format(temp_file))
            raise Exception('You did not provide any instance to monitor.\n')

        utils.call_command('rm {}'.format(temp_file))
Пример #10
0
    def collect_data(self):
        """
        data = {
            instance_name: {
                host: value
                port: value
            }
        }
        """
        data = {}
        iname_list = []
        server_list = []

        while utils.ask('\nWould 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, port) = p_utils.get_host_and_port(def_port='11211')

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

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

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

            if res:
                utils.print_step('Saving instance')
                iname_list.append(iname)
                server_list.append((host, port))
                data[iname] = {"host": host, "port": port}
                utils.print_success()
            else:
                utils.cprint('This instance is not saved.')

        return data
Пример #11
0
    def clean_plugin_write(self):
        """
        Prevent unfinished config file from being written into the directory

        Create and write to a temporary file.  Use try catch block to call
        write_plugin function.  If the configuration file is written
        successfully, then it will be copied over to the correct place.
        """
        temp_file = 'wavefront_temp_{0}.conf'.format(utils.random_string(7))
        error = None

        try:
            with open(temp_file, 'w') as out:
                try:
                    data = self.collect_data()
                    res = self.output_config(data, out)
                except KeyboardInterrupt as e:
                    error = e
                except Exception as e:
                    error = e
                finally:
                    if error:
                        utils.eprint('\nClosing and removing temp file.\n')
                        utils.call_command('rm ' + temp_file)
                        raise error
        except (IOError, OSError) as e:
            utils.eprint('Cannot open {}'.format(filepath))
            raise Exception('Error: {}\n'
                            'Cannot open {}.'.format(e, filepath))

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

            if ret == 0:
                utils.print_success()
                utils.cprint('{0} can be found at {1}.'.format(
                    self.conf_name, self.conf_dir))
            else:
                utils.call_command('rm {}'.format(temp_file))
                raise Exception('Failed to copy the plugin file.\n')
        else:
            utils.call_command('rm {}'.format(temp_file))
            raise Exception('You did not provide any instance to monitor.\n')

        utils.call_command('rm {}'.format(temp_file))
Пример #12
0
def update_install_state(agent, app_state_dict):
    """
    update the app state by modifying the json file

    Input:
        agent string:
            the agent chosen for the collector
        app_state_dict {}:
            dict that contains the app state

    Description:
        update the app_state and write to install_state.json
    """
    comment = {
          "standard_format": "see below",
          "AGENT": {
              "APP_NAME": {
                  "state": "(INSTALLED = 0, INCOMPLETE = 1, NEW = 2)",
                  "date": "time_of_installation"
              }
          }
    }

    # to keep order upon writing the dictionary
    json_content = collections.OrderedDict()
    json_content['_comment'] = comment
    json_content.update({'data': app_state_dict})

    if config.DEBUG:
        file_path = config.INSTALL_STATE_FILE
    else:
        if config.AGENT == config.COLLECTD:
            file_path = config.COLLECTD_INSTALL_STATE_FILE_PATH
        elif config.AGENT == config.TELEGRAF:
            file_path = config.TELEGRAF_INSTALL_STATE_FILE_PATH

    try:
        outfile = open(file_path, 'w')
    except:
        utils.eprint(
            'Cannot write to {}.\n'
            'Installed state is not updated.'.format(file_path))
        outfile = None

    if outfile is not None:
        try:
            json.dump(json_content, outfile, indent=4)
        finally:
            outfile.close()
Пример #13
0
    def collect_data(self):
        """
        data = {
            servers: []
        }
        """
        data = {'servers': []}
        server_list = []

        while utils.ask('\nWould you like to add a server to monitor?'):
            (host, port) = p_utils.get_host_and_port(def_port='6379')
            if (host, port) in server_list:
                utils.eprint(
                    'You have already added this {host}:{port}.'.format(
                        host=host, port=port))
                continue

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

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

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

            if res:
                utils.print_step('Saving instance')
                server_list.append((host, port))
                if protected:
                    url = (':{auth}@{host}:{port}').format(auth=auth,
                                                           host=host,
                                                           port=port)
                else:
                    url = ('{host}:{port}').format(host=host, port=port)
                data['servers'].append(url)
                utils.print_success()
            else:
                utils.cprint('This instance is not saved.')

        return data
Пример #14
0
    def pull_comment(self, out):
        if config.DEBUG:
            filepath = '{conf_dir}/{conf_name}'.format(
                conf_dir=config.PLUGIN_CONF_DIR, conf_name=self.conf_name)
        else:
            filepath = '{app_dir}/{conf_dir}/{conf_name}'.format(
                app_dir=config.APP_DIR,
                conf_dir=config.PLUGIN_CONF_DIR,
                conf_name=self.conf_name)

        try:
            with open(filepath) as cfile:
                for line in cfile:
                    out.write(line)
        except (IOError, OSError) as e:
            utils.eprint('Cannot open file at {}'.format(filepath))
            return False

        return True
Пример #15
0
    def pull_comment(self, out):
        if config.DEBUG:
            filepath = '{conf_dir}/{conf_name}'.format(
                conf_dir=config.PLUGIN_CONF_DIR,
                conf_name=self.conf_name)
        else:
            filepath = '{app_dir}/{conf_dir}/{conf_name}'.format(
                app_dir=config.APP_DIR,
                conf_dir=config.PLUGIN_CONF_DIR,
                conf_name=self.conf_name)

        try:
            with open(filepath) as cfile:
                for line in cfile:
                    out.write(line)
        except (IOError, OSError) as e:
            utils.eprint('Cannot open file at {}'.format(filepath))
            return False

        return True
Пример #16
0
def check_app(output, app_dict):
    """
    Input:
        output string:
            the result of ps -ef
        app_dict {}:
            the dictionary that hold's the app's information.
            This is reading from support_plugins.json

    Output:
        return true if the app is running

    Description:
        checks if the keyword from support_plugins can be matched
        in ps -ef output.
        if not, check if the command matches

        Note: lax search, but user has potentially more options
        to pick installers

    """
    app_search = app_dict['app_search']
    app_cmds = app_dict['command'].split('|')

    # lax app search
    app_re = re.compile(
        r'({app_search})'.format(
            app_search=app_search))
    # prevent self detection
    script_re = re.compile(
        r'root(.*)bash -c #!/bin/bash(.*)Install Wavefront Proxy and '
        'configures(.*)function logo')

    app_found = False
    for line in output.decode().split('\n'):
        self_res = script_re.match(line)

        if self_res is None:
            app_found = app_re.search(line)
            if app_found is not None:
                if config.DEBUG:
                    utils.eprint(line)
                return True
        else:
            if config.DEBUG:
                utils.eprint(
                    'Detected self with match:\n{}'.format(
                        self_res.group()))

    # check command if app is not found running
    if app_found is None:
        for cmd in app_cmds:
            if config.DEBUG:
                utils.eprint('Command: {}'.format(cmd))
            if cmd == "None":
                return False
            elif utils.command_exists(cmd):
                return True

    return False
Пример #17
0
    def install(self):
        class_name = self.__class__.__name__
        try:
            self.title()
            self.overview()
            self.check_plugin()
            self.check_dependency()
            self.clean_plugin_write()
        except KeyboardInterrupt as e:
            utils.eprint(
                'Quitting {}.'.format(
                    class_name))
            utils.append_to_log(e, config.INSTALL_LOG)
            return False
        except ex.MissingDependencyError as e:
            utils.eprint(
                'MissingDependencyError: {}\n'
                '{} requires the missing dependency '
                'to continue the installation.'.format(
                    e, class_name))
            utils.append_to_log(e, config.INSTALL_LOG)
            return False
        except Exception as e:
            utils.eprint(
                'Error: {}\n'
                '{} was not installed successfully.'.format(
                    e, class_name))
            utils.append_to_log(e, config.INSTALL_LOG)
            return False

        utils.print_color_msg('{} was installed successfully.'.format(
            class_name), utils.GREEN)
        return True
Пример #18
0
    def install(self):
        class_name = self.__class__.__name__
        try:
            self.title()
            self.overview()
            self.check_plugin()
            self.check_dependency()
            self.clean_plugin_write()
        except KeyboardInterrupt as e:
            utils.eprint('Quitting {}.'.format(class_name))
            utils.append_to_log(e, config.INSTALL_LOG)
            return False
        except ex.MissingDependencyError as e:
            utils.eprint('MissingDependencyError: {}\n'
                         '{} requires the missing dependency '
                         'to continue the installation.'.format(e, class_name))
            utils.append_to_log(e, config.INSTALL_LOG)
            return False
        except Exception as e:
            utils.eprint('Error: {}\n'
                         '{} was not installed successfully.'.format(
                             e, class_name))
            utils.append_to_log(e, config.INSTALL_LOG)
            return False

        utils.print_color_msg(
            '{} was installed successfully.'.format(class_name), utils.GREEN)
        return True
Пример #19
0
    def collect_data(self):
        """
        data = {
            servers: []
        }
        """
        data = {
            'servers': []
        }
        server_list = []

        while utils.ask('\nWould you like to add a server to monitor?'):
            (host, port) = p_utils.get_host_and_port(def_port='11211')
            if (host, port) in server_list:
                utils.eprint(
                    'You have already added this {host}:{port}.'.format(
                        host=host, port=port))
                continue

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

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

            if res:
                utils.print_step('Saving instance')
                server_list.append((host, port))
                data['servers'].append(
                    '{host}:{port}'.format(
                        host=host, port=port))
                utils.print_success()
            else:
                utils.cprint('This instance is not saved.')

        return data
Пример #20
0
def check_http_response(url):
    """
    check if the url is a valid

    Input:
        url string: the url provided by the user
    Output:
        ret_val bool:
            True if the url is valid and returns 200 OK
            False otherwise
    """
    ret_val = False
    utils.print_step('Checking http response for {url}'.format(url=url))
    res = utils.get_command_output('curl -s --head {url}'.format(url=url))

    if res is None:
        ret_code = utils.INVALID_URL
    else:
        ret_code = utils.get_http_return_code(res)

    if ret_code == utils.NOT_AUTH:
        # skip for this case for now, ask for user/pass
        utils.print_failure()
        utils.eprint(
            'Authorization is required, please '
            'try again.\n')
    elif ret_code == utils.NOT_FOUND or ret_code == utils.INVALID_URL:
        utils.print_failure()
        utils.eprint(
            'Invalid url was provided, please try '
            'again.\n')
    elif ret_code == utils.HTTP_OK:
        utils.print_success()
        ret_val = True

    return ret_val
Пример #21
0
def main():
    """
    Provides usage guide and prompt the user for choice of installers
    """
    check_version()

    parser = argparse.ArgumentParser(
        prog='python -m python_installer.gather_metrics',
        description='Python Configuration Installer')
    # os arg
    parser.add_argument(
        '--os',
        choices=['DEBIAN', 'REDHAT'],
        required=True,
        help='Operating system (DEBIAN|REDHAT)',
        metavar='(DEBIAN|REDHAT)')

    # agent arg
    parser.add_argument(
        '--agent',
        choices=['COLLECTD', 'TELEGRAF'],
        required=True,
        help='Agent (COLLECTD|TELEGRAF)',
        metavar='(COLLECTD|TELEGRAF)')

    # app_dir
    parser.add_argument(
        '--app_dir',
        required=True,
        help='The location of WF-PCInstaller where setup.py resides.')

    # log_file
    parser.add_argument(
        '--log_file',
        required=True,
        help='Errors will be logged to this file.')

    # debug
    parser.add_argument(
        '--debug',
        action='store_true',
        default=False,
        help='Turn debug flag on.')

    # --TEST
    parser.add_argument(
        '--TEST',
        action='store_true',
        default=False,
        help='Installs all detected applications with default setting.\n'
        'This is for integeration test.  Default is false.')

    args = parser.parse_args()
    config.OPERATING_SYSTEM = args.os
    config.AGENT = args.agent
    config.APP_DIR = args.app_dir
    config.INSTALL_LOG = args.log_file
    config.DEBUG = args.debug
    config.TEST = args.TEST

    if config.AGENT == config.COLLECTD:
        conf.check_collectd_exists()
        conf.check_collectd_path()

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

    (app_list, app_dict) = detect_applications()

    try:
        if config.TEST:
            test_installer(app_list, app_dict)
        else:
            # if at least one installer is ran to completion,
            # then exit with success
            if installer_menu(app_list, app_dict):
                sys.exit(0)
            else:
                sys.exit(1)
    except KeyboardInterrupt:
        utils.eprint('\nQuitting the installer via keyboard interrupt.')
        sys.exit(1)
Пример #22
0
 def check_telegraf_plugin(self):
     if not utils.command_exists('telegraf'):
         utils.eprint(
             'Cannot execute telegraf command.\n'
             'Please add telegraf to your executable path.')
         raise Exception('Telegraf command is not found.')
Пример #23
0
def check_install_state(app_list):
    """
    check the state of each installer

    Input:
        app_list []:
            a list of app name
    Output:
        install_state {}:
            a dict of app_name and their states

    Flow:
     - check file path exists
     - if exists:
           check each app against the fiel
           keep track of app and their states
    """
    # construct an empty install state if no file found
    empty_state_dict = {}
    empty_state_dict[config.AGENT] = {}
    empty_agent_dict = empty_state_dict[config.AGENT]
    for app in app_list:
        empty_agent_dict[app] = {}
        empty_agent_dict[app]['state'] = NEW

    # get location of install_state file
    if config.DEBUG:
        file_path = config.INSTALL_STATE_FILE
    else:
        if config.AGENT == config.COLLECTD:
            file_path = config.COLLECTD_INSTALL_STATE_FILE_PATH
        elif config.AGENT == config.TELEGRAF:
            file_path = config.TELEGRAF_INSTALL_STATE_FILE_PATH

    file_not_found = False
    try:
        install_file = open(file_path)
    except (IOError, OSError) as e:
        file_not_found = True
    except Exception as e:
        utils.exit_with_message('Error: {}'.format(e))

    if file_not_found:
        return empty_state_dict

    try:
        data = json.load(install_file)
    except Exception as e:
        utils.eprint(
            'Invalid json format.'
            'Error: {}'.format(e))
    finally:
        install_file.close()

    install_state = data['data']
    # create an empty dictionary for the app if key not found
    if config.AGENT not in install_state:
        install_state[config.AGENT] = {}

    agent_data = install_state[config.AGENT]
    for app in app_list:
        if app not in agent_data:
            agent_data[app] = {}
            agent_data[app]['state'] = NEW

    return install_state
Пример #24
0
def detect_applications():
    """
    Detect applications and provide the appropriate plugin information

    Description:
        This function uses unix command ps -ef and check whether
        the supported application is found.
        Check current plugin support in support_plugin.json

    Input:
        None
    Output:
        support_list []:
            the list of supported plugins that were detected
        support_dict {}
            the dictionary associated with each supported plugin
    """

    plugins_file = config.PLUGINS_FILE_PATH
    utils.print_step('Begin app detection')

    res = utils.get_command_output('ps -ef')
    if res is None:
        utils.exit_with_message('Unable to read process off the machine')

    try:
        data_file = open(plugins_file)
    except (IOError, OSError) as e:
        utils.exit_with_message(e)
    except Exception as e:
        utils.exit_with_message(
            'Cannot read support_plugins.json.\n'
            'Unexpected error: {}.'.format(e))

    try:
        data = json.load(data_file)
    except Exception as e:
        utils.cprint(
            'Improper JSON format.\n'
            'Error: {}'.format(e))
    finally:
        data_file.close()

    data = data['data']

    plugin_dict = data['plugins']
    support_dict = {}
    support_list = []

    for app in plugin_dict:
        app_dict = plugin_dict[app]
        if check_app(res, app_dict):
            if config.AGENT in app_dict:
                support_list.append(app)
                support_dict[app] = app_dict

    if len(support_list):
        return (support_list, support_dict)
    else:
        utils.eprint('No supported app plugin is detected.')
        sys.exit(0)
Пример #25
0
    def collect_data(self):
        """
        data = {
            instance_name: {
                host: value,
                port: value,
            (optional)
                auth: value,
                slave: bool
            }
        }
        """
        data = {}
        iname_list = []
        server_list = []

        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=('\nPlease 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=(
                    '\nWhat 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.'),
                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)

            protected = utils.ask(
                'Is there an authorization password set up for\n'
                '{host}:{port}'.format(host=host, port=port),
                default=None)
            if protected:
                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')
                iname_list.append(iname)
                server_list.append((host, port))
                data[iname] = {
                    'host': host,
                    'port': port,
                }
                if protected:
                    data[iname]['auth'] = auth
                if slave:
                    data[iname]['slave'] = True
                utils.print_success()
            else:
                utils.cprint('This instance is not saved.')

        return data
Пример #26
0
 def check_telegraf_plugin(self):
     if not utils.command_exists('telegraf'):
         utils.eprint('Cannot execute telegraf command.\n'
                      'Please add telegraf to your executable path.')
         raise Exception('Telegraf command is not found.')
Пример #27
0
def check_dependency(os):
    """
    Apache checklist:
    - check curl
    - mod_status
    - extended status
    """

    utils.print_step('Checking dependency')
    if not utils.command_exists('curl'):
        raise Exception('Curl is needed for this plugin.')

    # ubuntu check
    # Assumption:
    # -latest apache2 is installed and the installation
    # -directory is in the default place
    if os == config.DEBIAN:
        utils.print_step('  Checking if mod_status is enabled')
        cmd_res = utils.get_command_output('ls /etc/apache2/mods-enabled')
        if cmd_res is None:
            utils.eprint('Apache2 mods-enabled folder is not '
                         'found /etc/apache2/mods-enabled.')
            utils.print_failure()
        elif '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.print_failure()
                raise Exception('a2enmod command was not found')
            utils.print_success()
        else:
            utils.print_success()

    elif os == config.REDHAT:
        utils.cprint()
        utils.cprint(
            'To enable server status page for the apache web,\n'
            'ensure that mod_status.so module is enabled.\n'
            'This module is often enabled by default.\n'
            '"LoadModule status_module modules/mod_status.so"\n'
            'such line should be included in one of the conf files.\n')
        _ = utils.cinput('Press Enter to continue.')

    utils.cprint()
    utils.cprint(
        'In order to fully utilize the server_status metrics,\n'
        'the ExtendedStatus setting needs be turned on.\n'
        'This setting can be turned on by having "ExtendedStatus on"\n'
        'in one of the .conf file.\n')

    utils.cprint('If you have already enabled this status, '
                 'answer "no" to the next question.\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?')

    if res:
        # dir changes depending on the system
        # tested on Ubuntu 14.04, RHEL 7.2
        if os == config.DEBIAN:
            conf_dir = '/etc/apache2/conf-enabled'
            app_name = 'apache2'
        elif os == config.REDHAT:
            conf_dir = '/etc/httpd/conf.d'
            app_name = 'httpd'

        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)
            utils.cprint('extendedstatus.conf is now included in the '
                         '{0} dir.\n'.format(conf_dir))
            utils.print_step('Restarting apache')
            ret = utils.call_command('service {app_name} restart >> '
                                     '{log} 2>&1'.format(
                                         app_name=app_name,
                                         log=config.INSTALL_LOG))
            if ret != 0:
                raise Exception('Failed to restart apache service.')
            utils.print_success()
        else:
            raise Exception(
                '{cond_dir} dir does not exist. Manual '
                'set up is required. For help, please '
                'consult [email protected]'.format(conf_dir=conf_dir))
Пример #28
0
    def collect_data(self):
        """
        data = {
            instance_name: {
                host: value,
                port: value,
            (optional)
                auth: value,
                slave: bool
            }
        }
        """
        data = {}
        iname_list = []
        server_list = []

        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=(
                    '\nPlease 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=(
                    '\nWhat 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.'),
                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)

            protected = utils.ask(
                    'Is there an authorization password set up for\n'
                    '{host}:{port}'.format(host=host, port=port),
                    default=None)
            if protected:
                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')
                iname_list.append(iname)
                server_list.append((host, port))
                data[iname] = {
                    'host': host,
                    'port': port,
                }
                if protected:
                    data[iname]['auth'] = auth
                if slave:
                    data[iname]['slave'] = True
                utils.print_success()
            else:
                utils.cprint('This instance is not saved.')

        return data
Пример #29
0
def check_dependency(os):
    """
    Apache checklist:
    - check curl
    - mod_status
    - extended status
    """

    utils.print_step('Checking dependency')
    if not utils.command_exists('curl'):
        raise Exception('Curl is needed for this plugin.')

    # ubuntu check
    # Assumption:
    # -latest apache2 is installed and the installation
    # -directory is in the default place
    if os == config.DEBIAN:
        utils.print_step('  Checking if mod_status is enabled')
        cmd_res = utils.get_command_output('ls /etc/apache2/mods-enabled')
        if cmd_res is None:
            utils.eprint(
                'Apache2 mods-enabled folder is not '
                'found /etc/apache2/mods-enabled.')
            utils.print_failure()
        elif '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.print_failure()
                raise Exception('a2enmod command was not found')
            utils.print_success()
        else:
            utils.print_success()

    elif os == config.REDHAT:
        utils.cprint()
        utils.cprint(
            'To enable server status page for the apache web,\n'
            'ensure that mod_status.so module is enabled.\n'
            'This module is often enabled by default.\n'
            '"LoadModule status_module modules/mod_status.so"\n'
            'such line should be included in one of the conf files.\n')
        _ = utils.cinput('Press Enter to continue.')

    utils.cprint()
    utils.cprint(
        'In order to fully utilize the server_status metrics,\n'
        'the ExtendedStatus setting needs be turned on.\n'
        'This setting can be turned on by having "ExtendedStatus on"\n'
        'in one of the .conf file.\n')

    utils.cprint(
        'If you have already enabled this status, '
        'answer "no" to the next question.\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?')

    if res:
        # dir changes depending on the system
        # tested on Ubuntu 14.04, RHEL 7.2
        if os == config.DEBIAN:
            conf_dir = '/etc/apache2/conf-enabled'
            app_name = 'apache2'
        elif os == config.REDHAT:
            conf_dir = '/etc/httpd/conf.d'
            app_name = 'httpd'

        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)
            utils.cprint(
                'extendedstatus.conf is now included in the '
                '{0} dir.\n'.format(conf_dir))
            utils.print_step('Restarting apache')
            ret = utils.call_command(
                'service {app_name} restart >> '
                '{log} 2>&1'.format(
                    app_name=app_name,
                    log=config.INSTALL_LOG))
            if ret != 0:
                raise Exception(
                    'Failed to restart apache service.')
            utils.print_success()
        else:
            raise Exception(
                '{cond_dir} dir does not exist. Manual '
                'set up is required. For help, please '
                'consult [email protected]'.format(
                    conf_dir=conf_dir))