Exemple #1
0
    def SvcDoRun(self):

        # __file__ == 'service_win32.py'
        exe_dir = os.path.dirname(os.path.dirname(__file__))
        os.chdir(exe_dir)

        win32evtlogutil.ReportEvent(self._svc_name_,
                                    servicemanager.PYS_SERVICE_STARTED, 0,
                                    servicemanager.EVENTLOG_INFORMATION_TYPE,
                                    (self._svc_name_, ''))

        config_file = os.path.join(exe_dir, 'agent.conf')
        config = Config(config_file)

        supervisor = Supervisor(config)
        win32evtlogutil.ReportEvent(self._svc_name_,
                                    servicemanager.PYS_SERVICE_STOPPED, 0,
                                    servicemanager.EVENTLOG_INFORMATION_TYPE,
                                    (self._svc_name_, ''))

        thread = Thread(target=supervisor.start)
        thread.daemon = True
        thread.start()

        while True:
            rc = win32event.WaitForSingleObject(self.hWaitStop,
                                                win32event.INFINITE)
            if rc == win32event.WAIT_OBJECT_0:
                win32evtlogutil.ReportEvent(
                    self._svc_name_, servicemanager.PYS_SERVICE_STOPPED, 0,
                    servicemanager.EVENTLOG_INFORMATION_TYPE,
                    (self._svc_name_, ''))
                break
Exemple #2
0
def run_agent():
    def print_help():
        print(usage_msg)
        sys.exit(7)

    usage_msg = """
{prog} agent [OPTIONS] COMMANDS

Examples:
    {prog} agent version
    {prog} agent metric-list
    {prog} agent metric-get <metric key>
""".format(prog=sys.argv[0])

    parser = optparse.OptionParser(
        usage=usage_msg, version='%prog agent {0}'.format(__version__))
    parser.add_option('-c',
                      '--config',
                      dest='config',
                      help=optparse.SUPPRESS_HELP)
    args, commands = parser.parse_args()

    cfg = Config(args.config)
    host = cfg.fetch('agent', 'host')
    port = cfg.fetch('agent', 'port', int)
    url, key = None, None

    if len(commands) == 0:
        return print_help()
    if commands[0] == 'version':
        if len(commands) >= 2:
            return print_help()
        url = 'http://{0}:{1}/version'.format(host, port)
    elif commands[0] == 'metric-list':
        if len(commands) >= 2:
            return print_help()
        url = 'http://{0}:{1}/list'.format(host, port)
    elif commands[0] == 'metric-get':
        if not len(commands) == 2:
            return print_help()
        key = commands[1]
        url = 'http://{0}:{1}/get?key={2}'.format(host, port, key)
    else:
        return print_help()

    request = urllib2.Request(url)
    try:
        response = urllib2.urlopen(request)
    except Exception as e:
        sys.stderr.write('Open url: {0}, error: {1}\n'.format(url, e))
        sys.exit(9)

    if not response.code == 200:
        sys.stderr.write('Bad response from url {0}, code: {1}\n'.format(
            url, response.code))
        sys.exit(8)
    else:
        try:
            body = response.read()
        except Exception as e:
            sys.stderr.write('Read url: {0}, error: {1}\n'.format(url, e))
            sys.exit(9)
        if body == API.UNKNOWN_VERSION:
            sys.stderr.write('Unknown API version\n')
            sys.exit(9)
        elif body == API.METRIC_NOT_FOUND and key is not None:
            sys.stderr.write('Metric \'{0}\' not found\n'.format(key))
            sys.exit(9)
        elif body == API.METRIC_NOT_FOUND and key is None:
            sys.stderr.write('Unknown API version\n')
            sys.exit(9)
        else:
            print(body)
Exemple #3
0
def start():
    def quit_handler(_signo=None, _stack_frame=None):
        logging.info("Bye bye!")
        sys.exit(0)

    signal.signal(signal.SIGTERM, quit_handler)
    if platform.LINUX:
        signal.signal(signal.SIGQUIT, quit_handler)

    commands = sys.argv[1:]
    if len(commands) > 0:
        tool = commands[0]
        if tool == '-h' or tool == '--help':
            print_total_help()
        elif tool == 'bootstrap':
            from mamonsu.tools.bootstrap.start import run_deploy
            sys.argv.remove('bootstrap')
            return run_deploy()
        elif tool == 'report':
            from mamonsu.tools.report.start import run_report
            sys.argv.remove('report')
            return run_report()
        elif tool == 'tune':
            from mamonsu.tools.tune.start import run_tune
            sys.argv.remove('tune')
            return run_tune()
        elif tool == 'zabbix':
            from mamonsu.tools.zabbix_cli.start import run_zabbix
            sys.argv.remove('zabbix')
            return run_zabbix()
        elif tool == 'agent':
            from mamonsu.tools.agent.start import run_agent
            sys.argv.remove('agent')
            return run_agent()
        elif tool == 'export':
            args, commands = parse_args()
            cfg = Config(args.config_file, args.plugins_dirs)
            if not len(commands) == 3:
                print_total_help()
            elif commands[1] == 'config':
                with open(commands[2], 'w') as fd:
                    cfg.config.write(fd)
                    sys.exit(0)
            elif commands[1] == 'template':
                plugins = []
                for klass in Plugin.only_child_subclasses():
                    plugins.append(klass(cfg))
                template = ZbxTemplate(args.template, args.application)
                with codecs.open(commands[2], 'w', 'utf-8') as f:
                    f.write(template.xml(plugins))
                    sys.exit(0)
            else:
                print_total_help()

    args, commands = parse_args()
    if len(commands) > 0:
        print_total_help()
    cfg = Config(args.config_file, args.plugins_dirs)

    # simple daemon
    if args.daemon:
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except Exception as e:
            sys.stderr.write('Can\'t fork: {0}\n'.format(e))
            sys.exit(2)

    # write pid-file
    if args.pid is not None:
        try:
            with open(args.pid, 'w') as pidfile:
                pidfile.write(str(os.getpid()))
        except Exception as e:
            sys.stderr.write('Can\'t write pid file, error: %s\n'.format(e))
            sys.exit(2)

    supervisor = Supervisor(cfg)

    try:
        logging.info("Start mamonsu")
        supervisor.start()
    except KeyboardInterrupt:
        quit_handler()
Exemple #4
0
def start():
    def quit_handler(_signo=None, _stack_frame=None):
        logging.info("Bye bye!")
        sys.exit(0)

    signal.signal(signal.SIGTERM, quit_handler)
    if platform.LINUX:
        signal.signal(signal.SIGQUIT, quit_handler)

    commands = sys.argv[1:]
    if len(commands) > 0:
        tool = commands[0]
        if tool == '-h' or tool == '--help':
            print_total_help()
        elif tool == 'bootstrap':
            from mamonsu.tools.bootstrap.start import run_deploy
            sys.argv.remove('bootstrap')
            return run_deploy()
        elif tool == 'report':
            from mamonsu.tools.report.start import run_report
            sys.argv.remove('report')
            return run_report()
        elif tool == 'tune':
            from mamonsu.tools.tune.start import run_tune
            sys.argv.remove('tune')
            return run_tune()
        elif tool == 'zabbix':
            from mamonsu.tools.zabbix_cli.start import run_zabbix
            sys.argv.remove('zabbix')
            return run_zabbix()
        elif tool == 'agent':
            from mamonsu.tools.agent.start import run_agent
            sys.argv.remove('agent')
            return run_agent()
        elif tool == 'upload':
            args, commands = parse_args()
            if not args.zabbix_address:
                print('Option --zabbix-address is missing')
                sys.exit(2)
            if not os.path.isfile(args.zabbix_file):
                print('Cannot find zabbix file with metric to upload. Check path in --zabbix-file option.')
                sys.exit(2)

            cfg = Config(args.config_file, args.plugins_dirs)
            cfg.config.set('zabbix', 'address', args.zabbix_address)
            cfg.config.set('zabbix', 'port', args.zabbix_port)
            cfg.config.set('zabbix', 'client', args.zabbix_client)
            cfg.config.set('log', 'level', args.zabbix_log_level)

            supervisor = Supervisor(cfg)
            supervisor.send_file_zabbix(cfg, args.zabbix_file)
            sys.exit(0)

        elif tool == 'export':
            args, commands = parse_args()
            # get PG version
            Plugin.VersionPG = define_pg_version(args.pg_version)
            cfg = Config(args.config_file, args.plugins_dirs)
            if args.old_zabbix:
                Plugin.old_zabbix = True
            if not len(commands) == 2 and not len(commands) == 3:
                print_total_help()
            if commands[1] == 'zabbix-parameters':
                # zabbix agent keys generation
                Plugin.Type = 'agent'  # change plugin type for template generator
                plugins = []
                if len(commands) == 2:
                    commands.append('postgrespro_agent.conf')
                for klass in Plugin.only_child_subclasses():
                    if klass.__name__ != "PgWaitSampling" and  klass.__name__ != "Cfs":
                            plugins.append(klass(cfg))
                args.plugin_type = correct_plugin_type(args.plugin_type)
                if args.plugin_type == 'pg' or args.plugin_type == 'sys' or args.plugin_type == 'all':
                    template = GetKeys()
                    # write conf file
                    try:
                        fd = codecs.open(commands[2], 'w', 'utf-8')
                        fd.write(template.txt(args.plugin_type, plugins))  # pass command type
                        print("Configuration file for zabbix-agent has been saved as {0}".format(commands[2]))
                    except (IOError, EOFError) as e:
                        print(" {0} ".format(e))
                        sys.exit(2)
                    # write bash scripts for zabbix - agent to a file
                    # check if conf file has a path
                    len_path = commands[2].rfind("/")
                    # get path for conf file and scripts
                    if len_path != -1:
                        path = commands[2][:len_path] + "/scripts"
                        Plugin.PATH = path
                    else:
                        path = os.getcwd() + "/scripts"
                        Plugin.PATH = path
                    # create directory for scripts along the path of conf file if needed
                    if not os.path.exists(path):
                            os.makedirs(path)
                    for key in Scripts.Bash:
                        with codecs.open(path + "/" + key + ".sh", 'w+', 'utf-8') as f:
                            #   configuration file for zabbix-agent is generated for selected plugin-type
                            f.write(Scripts.Bash[key])  # pass script itself
                        os.chmod(path + "/" + key + ".sh", 0o755)
                    print("Bash scripts for native zabbix-agent have been saved to {0}".format(path))
                else:
                    print("Got wrong plugin types. See help 'mamonsu -- help' ")
                    sys.exit(2)
                sys.exit(0)
            elif commands[1] == 'config':
                # if no name for conf, save to postgrespro.conf
                if len(commands) == 2:
                    commands.append('postgrespro.conf')
                try:
                    fd = open(commands[2], 'w')
                    cfg.config.write(fd)
                    print("Configuration file for mamonsu has been saved as {0}".format(commands[2]))
                    sys.exit(0)
                except (IOError, EOFError) as e:
                    print(" {0} ".format(e))
                    sys.exit(2)
            elif commands[1] == 'template':
                plugins = []
                if len(commands) == 2:
                    commands.append('postgrespro.xml')
                for klass in Plugin.only_child_subclasses():
                        plugins.append(klass(cfg))
                template = ZbxTemplate(args.template, args.application)
                try:
                    fd = codecs.open(commands[2], 'w', 'utf-8')
                    fd.write(template.xml("all", plugins))  # set type to 'all' for mamonsu
                    print('Template for mamonsu has been saved as {file}'.format(file=commands[2]))
                    sys.exit(0)
                except (IOError, EOFError) as e:
                    print(" {0} ".format(e))
                    sys.exit(2)
            elif commands[1] == 'zabbix-template':
                Plugin.Type = 'agent'  # change plugin type for template generator
                if len(commands) == 2:
                    commands.append('postgrespro_agent.xml')
                plugins = []
                args.plugin_type = correct_plugin_type(args.plugin_type)
                if args.plugin_type == 'pg' or args.plugin_type == 'sys' or args.plugin_type == 'all':
                    for klass in Plugin.only_child_subclasses():
                        if klass.__name__ != "PgWaitSampling" and klass.__name__ != "Cfs":  # check if plugin is for EE
                                plugins.append(klass(cfg))
                    template = ZbxTemplate(args.template, args.application)
                    try:
                        fd = codecs.open(commands[2], 'w', 'utf-8')
                        fd.write(template.xml(args.plugin_type, plugins))
                        print('Template for zabbix-agent has been saved as {file}'.format(file=commands[2]))
                        sys.exit(0)
                    except (IOError, EOFError) as e:
                        print(" {0} ".format(e))
                        sys.exit(2)
                else:
                    print("Got wrong plugin types. See help 'mamonsu -- help' ")
                    sys.exit(2)
            else:
                print_total_help()

    args, commands = parse_args()
    if len(commands) > 0:
        print_total_help()
    cfg = Config(args.config_file, args.plugins_dirs)

    # simple daemon
    if args.daemon:
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except Exception as e:
            sys.stderr.write('Can\'t fork: {0}\n'.format(e))
            sys.exit(2)

    # write pid-file
    if args.pid is not None:
        try:
            with open(args.pid, 'w') as pidfile:
                pidfile.write(str(os.getpid()))
        except Exception as e:
            sys.stderr.write('Can\'t write pid file, error: %s\n'.format(e))
            sys.exit(2)

    supervisor = Supervisor(cfg)

    try:
        logging.info("Start mamonsu")
        supervisor.start()
    except KeyboardInterrupt:
        quit_handler()
Exemple #5
0
def start():
    def quit_handler(_signo=None, _stack_frame=None):
        logging.info("Bye bye!")
        sys.exit(0)

    signal.signal(signal.SIGTERM, quit_handler)
    if platform.LINUX:
        signal.signal(signal.SIGQUIT, quit_handler)

    commands = sys.argv[1:]
    if len(commands) > 0:
        tool = commands[0]
        if tool == '-h' or tool == '--help':
            print_total_help()
        elif tool == 'bootstrap':
            from mamonsu.tools.bootstrap.start import run_deploy
            sys.argv.remove('bootstrap')
            return run_deploy()
        elif tool == 'report':
            from mamonsu.tools.report.start import run_report
            sys.argv.remove('report')
            return run_report()
        elif tool == 'tune':
            from mamonsu.tools.tune.start import run_tune
            sys.argv.remove('tune')
            return run_tune()
        elif tool == 'zabbix':
            from mamonsu.tools.zabbix_cli.start import run_zabbix
            sys.argv.remove('zabbix')
            return run_zabbix()
        elif tool == 'agent':
            from mamonsu.tools.agent.start import run_agent
            sys.argv.remove('agent')
            return run_agent()
        elif tool == 'export':
            args, commands = parse_args()
            # get PG version
            version_args = args.pg_version.split('_')
            define_pg_version(version_args)
            cfg = Config(args.config_file, args.plugins_dirs)
            if not len(commands) == 2 and not len(commands) == 3:
                print_total_help()
            if commands[1] == 'zabbix-parameters':
                # zabbix agent keys generation
                Plugin.Type = 'agent'  # change plugin type for template generator
                plugins = []
                if len(commands) == 2:
                    commands.append('postgrespro_agent.conf')
                    print('Configuration file for zabbix-agent have been saved in postgrespro_agent.conf file')
                for klass in Plugin.only_child_subclasses():
                    if klass.__name__ == "PgWaitSampling":  # check if plugin is for EE
                        if Plugin.VersionPG['type'] == 'PGEE':
                            plugins.append(klass(cfg))
                    else:
                        if klass.__name__ != "Cfs":
                            plugins.append(klass(cfg))
                args.plugin_type = correct_plugin_type(args.plugin_type)
                if args.plugin_type == 'pg' or args.plugin_type == 'sys' or args.plugin_type == 'all':
                    # check if conf file has a path
                    len_path = commands[2].rfind("/")
                    # get path for conf file and scripts
                    if len_path != -1:
                            path = commands[2][:len_path] + "/scripts"
                            Plugin.PATH = path
                    else:
                        path = os.getcwd() + "/scripts"
                        Plugin.PATH = path
                    # create directory for scripts along the path of conf file if needed
                    if not os.path.exists(path):
                        os.makedirs(path)
                        print("Directory for scripts has created")
                    template = GetKeys()
                    # if no name for zabbix-parameters save to postgrespro.conf
                    if commands[2].rfind("/") == len(commands[2]) - 1:
                        commands[2] = commands[2][:-1] + "/postgrespro.conf"
                    # write conf file
                    with codecs.open(commands[2], 'w', 'utf-8') as f:
                        f.write(template.txt(args.plugin_type, plugins))  # pass command type
                    # write bash scripts for zabbix - agent to a file
                    for key in Scripts.Bash:
                        with codecs.open(path + "/" + key + ".sh", 'w+', 'utf-8') as f:
                            #   configuration file for zabbix-agent is generated for selected plugin-type
                            f.write(Scripts.Bash[key])  # pass script itself
                        os.chmod(path + "/" + key + ".sh", 0o755)
                    print("Bash scripts for native zabbix-agent have been saved to {0}".format(path))
                else:
                    print("Got wrong plugin types. For help, see the message below")
                    print_total_help()
                sys.exit(0)
            elif commands[1] == 'config':
                if len(commands) == 2:
                    commands.append('postgrespro.conf')
                    print('Configuration file for mamonsu have been saved in postgrespro.conf file')
                # if no name for conf, save to mamonsu.conf
                if commands[2].rfind("/") == len(commands[2]) - 1:
                    commands[2] = commands[2][:-1] + "/mamonsu.conf"
                with open(commands[2], 'w') as fd:
                    cfg.config.write(fd)
                    sys.exit(0)
            elif commands[1] == 'template':
                plugins = []
                if len(commands) == 2:
                    commands.append('postgrespro.xml')
                    print('Template for mamonsu have been saved in postgrespro.conf file')
                for klass in Plugin.only_child_subclasses():
                    if klass.__name__ == "PgWaitSampling":  # check if plugin is for EE
                        if Plugin.VersionPG['type'] == 'PGEE':
                            plugins.append(klass(cfg))
                    else:
                        plugins.append(klass(cfg))
                template = ZbxTemplate(args.template, args.application)
                # if no name for template save to postgrespro.xml
                if commands[2].rfind("/") == len(commands[2]) - 1:
                    commands[2] = commands[2][:-1] + "/postgrespro.xml"
                with codecs.open(commands[2], 'w', 'utf-8') as f:
                    #   template for mamonsu (zabbix-trapper) is generated for all available plugins
                    f.write(template.xml("all", plugins))  # set type to 'all' for mamonsu
                    sys.exit(0)
            elif commands[1] == 'zabbix-template':
                Plugin.Type = 'agent'  # change plugin type for template generator
                if len(commands) == 2:
                    commands.append('postgrespro_agent.xml')
                    print('Template for zabbix-agent have been saved in postgrespro_agent.xml file')
                plugins = []
                args.plugin_type = correct_plugin_type(args.plugin_type)
                if args.plugin_type == 'pg' or args.plugin_type == 'sys' or args.plugin_type == 'all':
                    for klass in Plugin.only_child_subclasses():
                        if klass.__name__ == "PgWaitSampling":  # check if plugin is for EE
                            if Plugin.VersionPG['type'] == 'PGEE':
                                plugins.append(klass(cfg))
                        else:
                            if klass.__name__ != "Cfs":
                                plugins.append(klass(cfg))
                    template = ZbxTemplate(args.template, args.application)
                    # if no name for template save to postgrespro.xml
                    if commands[2].rfind("/") == len(commands[2]) - 1:
                        commands[2] = commands[2][:-1] + "/postgrespro.xml"
                    with codecs.open(commands[2], 'w', 'utf-8') as f:
                        #   template for zabbix-agent is generated for selected plugin-type
                        f.write(template.xml(args.plugin_type, plugins))
                    sys.exit(0)
                else:
                    print("Got wrong plugin types. For help, see the message below")
                    print_total_help()
            else:
                print_total_help()

    args, commands = parse_args()
    if len(commands) > 0:
        print_total_help()
    cfg = Config(args.config_file, args.plugins_dirs)

    # simple daemon
    if args.daemon:
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except Exception as e:
            sys.stderr.write('Can\'t fork: {0}\n'.format(e))
            sys.exit(2)

    # write pid-file
    if args.pid is not None:
        try:
            with open(args.pid, 'w') as pidfile:
                pidfile.write(str(os.getpid()))
        except Exception as e:
            sys.stderr.write('Can\'t write pid file, error: %s\n'.format(e))
            sys.exit(2)

    supervisor = Supervisor(cfg)

    try:
        logging.info("Start mamonsu")
        supervisor.start()
    except KeyboardInterrupt:
        quit_handler()