Beispiel #1
0
def main():
    arguments = docopt(__doc__)

    if (arguments['--socket']):
        try:
            hap = haproxy.HAProxy(socket_file=arguments['--socket'])
        except (SocketApplicationError, SocketConnectionError,
                SocketPermissionError) as error:
            print(error)
            sys.exit(1)
        except ValueError as error:
            print(error)
            sys.exit(1)
    else:
        try:
            hap = haproxy.HAProxy(socket_dir=arguments['--socket-dir'])
        except (SocketApplicationError, SocketConnectionError,
                SocketPermissionError) as error:
            print(error)
            sys.exit(1)
        except ValueError as error:
            print(error)
            sys.exit(1)

    cmd = BackendCommand(hap, arguments)
    method = get_arg_option(arguments)
    getattr(cmd, method)()
Beispiel #2
0
def main():
    arguments = docopt(__doc__)

    if (arguments['--socket']):
        try:
            hap = haproxy.HAProxy(socket=arguments['--socket'])
        except (SocketApplicationError,
                SocketConnectionError,
                SocketPermissionError) as error:
            print(error)
            sys.exit(1)
        except ValueError as error:
            print(error)
            sys.exit(1)
    else:
        try:
            hap = haproxy.HAProxy(socket_dir=arguments['--socket-dir'])
        except (SocketApplicationError,
                SocketConnectionError,
                SocketPermissionError) as error:
            print(error)
            sys.exit(1)
        except ValueError as error:
            print(error)
            sys.exit(1)

    cmd = HAProxyCommand(hap, arguments)
    method = get_arg_option(arguments)
    try:
        getattr(cmd, method)()
    except CommandFailed as error:
        sys.exit("failed with error: {err}".format(err=error))
    def __init__(self,
                 metric,
                 frontend=None,
                 backend=None,
                 server=None,
                 hasocketdir=None,
                 hasocketfile=None,
                 nozerocounters=False,
                 min=None,
                 max=None,
                 scan=False):

        self.haadmin = hapm.HAProxy(socket_dir=hasocketdir,
                                    socket_file=hasocketfile)
        self.metric = metric
        self.frontend = frontend
        self.backend = backend
        self.server = server
        self.set_mode()
        self.nozerocounters = nozerocounters
        self.min = min
        self.max = max

        if scan:
            self.scan()
            exit()
        else:
            if not self.get_ha_resource():
                raise ValueError(
                    "HA resource was not found. Use --scan to check for resources."
                )
Beispiel #4
0
def get_server(backend_name, server_name):
    hap = haproxy.HAProxy(socket_file=HAPROXY_SOCKET_FILE)
    servers = hap.server(server_name, backend=backend_name)
    if (len(servers) > 0):
        return ServerSchema().dump(servers[0]).data
    else:
        return None
 def __init__(self):
     self.hap = haproxy.HAProxy(socket_dir='/run/haproxy')
     self.frontend_metrics = {}
     self.backend_metrics = {}
     self.server_metrics = {}
     self.FRONTEND = "frontend"
     self.BACKEND = "backend"
     self.SERVER = "server"
Beispiel #6
0
def fetch_backend_sockets(data):
    """
    Function to fetch data from haproxy sockets
    """
    hap = haproxy.HAProxy(socket_dir="/var/lib/haproxy")
    backends = hap.backends()
    for backend in backends:
        if backend.name == data:
            print backend.process_nb
Beispiel #7
0
def del_ip():
  if 'ipaddress' in request.form and request.form['ipaddress']:
    ip=request.form['ipaddress'].strip()
    if ipFormatChk(ip):
      hap=haproxy.HAProxy(socket_dir='/var/run/',socket_file='haproxy.sock')
      for x in hap.show_acl(0):
        if x.split()[1] == ip :
          hap.del_acl(0,ip)
          return redirect(url_for('dashboard'))
  return redirect(url_for('dashboard'))
Beispiel #8
0
def add_ip():
  if not 'ipaddress' in request.form or not request.form['ipaddress']:
    ip=get_x_ip()
  else:
    ip=request.form['ipaddress']
  ip=ip.strip()
  if ipFormatChk(ip):
    hap=haproxy.HAProxy(socket_dir='/var/run/',socket_file='haproxy.sock')
    acls=[ x.split()[1] for x in hap.show_acl(0) ]
    if not ip in acls:
      hap.add_acl(0,ip)
  return redirect(url_for('dashboard'))
Beispiel #9
0
    def start(self):
        self.stop()

        os.system(' '.join([
            "haproxy",
            "-f",
            self.config,
            "-p",
            self.pid_file,  # PID
            "-sf",
            _read_file(self.pid_file),
        ]))

        self.socket = haproxy.HAProxy(socket_dir=self.socket_path)

        for tor_group in self.tor_groups:
            for tor in tor_group.instances.values():
                tor.update_haproxy()
                tor.enable()
Beispiel #10
0
def haproxy_object(arguments):
    """Return a HAProxy object.

    :param arguments: Arguments of the progam
    :type arguments: ``dict``
    :return: A HAProxy object or exit main program in case of failure
    :rtype: ``haproxy.HAProxy``
    """
    if arguments['--file'] is not None:
        arguments['--socket-dir'] = None
    try:
        hap = haproxy.HAProxy(socket_file=arguments['--file'],
                              socket_dir=arguments['--socket-dir'])
    except (SocketApplicationError, SocketConnectionError,
            SocketPermissionError) as error:
        sys.exit(1)
    except ValueError as error:
        sys.exit(error)
    else:
        return hap
def fetch_haproxy_data():
    """
    Function to fetch server state and
    current connections from haproxy
    """
    data = {}
    hap = haproxy.HAProxy(socket_dir=config.get('haproxy', 'socket_dir'))
    backends = hap.backends()
    for backend in backends:
        data[backend.name] = {}
        data[backend.name]['bind-process'] = backend.process_nb
        data[backend.name]['servers'] = {}
        data[backend.name]['requests'] = {}
        servers = backend.servers()
        for server in servers:
            try:
                data[backend.name]['servers'][server.name] = server.status
            except:
                data[backend.name]['servers'][server.name] = "INCONSISTENT"
            data[backend.name]['requests'][server.name] = server.metric('scur')
    return data
    def __init__(self, socket, config_file, haproxy_file):
        """Parse the config file and create corresponding watchers and pools"""
        self._watchers = []
        self._orchestrators = []

        # Config parser
        self._configurator = configurator.Configurator(socket, config_file,
                                                       haproxy_file)

        # Get list of services and their configs
        services = self._configurator.parse_config()

        # Write the initial configuration to file
        self._configurator.config_write()

        # If there is an existing HAProxy running that is using the same
        # pid file, take over the existing to avoid conflicts
        if haproxy_cmd.haproxy_proc():
            haproxy_cmd.restart_haproxy()
        else:
            haproxy_cmd.start_haproxy()

        # Instantiate initial connection to haproxy socket only once
        haproxy_sock = haproxy.HAProxy(socket_dir=socket)

        # Share the single instance of haproxy socket and config parser for
        # efficiency
        for service_name, service in services.items():
            self._watchers.append(
                watcher.Watcher(service_name, service, self._configurator))

            # Only create orchestrators when the config is present
            if 'elasticity' in service:
                self._orchestrators.append(
                    orchestrator.Orchestrator(service_name, service,
                                              haproxy_sock))

        # Run self._cleanup on exit
        atexit.register(self._cleanup)
Beispiel #13
0
from flask_restplus import Resource
from base import api, STATUS_CODES
from haproxyadmin import haproxy
import config

hap = haproxy.HAProxy(socket_dir=config.haproxy_socket['DIR'],
                      socket_file=config.haproxy_socket['FILE'])


@api.route("/api/v1/errors", methods=['GET'])
class Errors(Resource):
    def get(self):
        return hap.errors()
Beispiel #14
0
from haproxyadmin import haproxy
hap = haproxy.HAProxy(socket_dir='/var/run/haproxy')
frontends = hap.frontends()
for frontend in frontends:
    print(frontend.name, frontend.requests, frontend.process_nb)
    FRONTEND_METRICS = ['scur', 'stot']
    for m in FRONTEND_METRICS:
        print("name {} value {}".format(m, frontend.metric(m)))

backends = hap.backends()
for backend in backends:
    print(backend.name, backend.requests, backend.process_nb)
    BACKEND_METRICS = ['scur', 'stot']
    for m in BACKEND_METRICS:
        print("name {} value {}".format(m, backend.metric(m)))
    servers = backend.servers()
    for server in servers:
        print(" ", server.name, server.requests)
Beispiel #15
0
def main(args):
    critical_level = 0.4  #default percentage of offline servers for critical
    haproxy_socket = '/var/run/haproxy.sock'
    critical_frontends = []
    critical_backends = []
    critical_servers = []

    try:
        opts, args = getopt.getopt(sys.argv[1:], "c:", ["climit="])
        for opt, arg in opts:
            if opt in ('-c', '--climit'):
                critical_level = float(arg)
            if opt in ('-s', '--socket'):
                haproxy_socket = arg

    except:
        print 'Incorrect arguments.'
        return UNKNOWN

    if critical_level > 1:
        critical_level = critical_level / 100

    hap = haproxy.HAProxy(socket_file=haproxy_socket)
    frontend_list = hap.frontends()
    backend_list = hap.backends()

    for frontend in frontend_list:
        if frontend.status != 'OPEN':
            critical_frontends.append((frontend.name, frontend.status))

    for backend in backend_list:
        if backend.status != 'UP':
            critical_backends.append((backend.name, backend.status))
        else:
            server_list = backend.servers()
            if len(server_list) == 0:
                continue
            for server in server_list:
                if server.status != 'UP' and server.status != 'no check':
                    critical_servers.append(
                        (backend.name, server.name, server.status))

            if (count_backend(critical_servers, backend.name) /
                    len(server_list)) >= critical_level:
                critical_backends.append((backend.name, backend.status))

    message = []

    for frontend in critical_frontends:
        message.append(frontend[0] + ' frontend is in ' + frontend[1] +
                       ' state.')

    for backend in critical_backends:
        if backend[1] == 'UP':
            message.append(backend[0] + ' backend has >' +
                           str(critical_level * 100) + '\% of servers down.')
        else:
            message.append(backend[0] + ' backend is in ' + backend[1] +
                           ' state.')

    if len(message) == 0:
        if len(critical_servers) == 0:
            print 'All frontends, backends, and attached servers are running and enabled.'
            return OK
        else:
            for server in critical_servers:
                message.append(server[1] + ' server of ' + server[0] +
                               ' backend is in ' + server[2] + ' state.')

            print '; '.join(message)
            return WARNING

    else:
        print '; '.join(message)
        return CRITICAL
Beispiel #16
0
def main():

    parser = optparse.OptionParser(
        description=
        "Simply Nagios plugin to check HAProxy backends and frontends state",
        version="0.0.1",
        usage="usage: %prog -s /var/run/haproxy/ -t backends")

    parser.add_option(
        "-s",
        "--sockets_path",
        dest="sockets_path",
        help="Enter path to the HAProxy sockets",
    )
    parser.add_option(
        "-t",
        "--section_type",
        dest="section_type",
        help="Select backends or frontends!",
    )
    (opts, args) = parser.parse_args()

    try:
        if not opts.sockets_path or not opts.section_type:
            parser.print_help()
            raise SystemExit(int(SIGNALS["ERROR"]))
        elif opts.sockets_path is None:
            parser.error('Please enter the path to HAProxy sockets!')
        elif opts.section_type is None:
            parser.error('Please select backends or frontends!')
        elif opts.section_type not in ["backends", "frontends"]:
            parser.error(
                'Bad value! Possible values are backends or frontends!')
        elif opts.section_type:
            pass
    except Exception as e:
        logger.error(
            'There was a problem parsing the arguments passed to the script! - {}'
            .format(str(e)))
        sys.exit(int(SIGNALS["ERROR"]))

    try:
        h = haproxy.HAProxy(socket_dir=opts.sockets_path)
        pass
    except Exception as e:
        logger.error('Unable to connect to the HAProxy socket! - {}'.format(
            str(e)))
        sys.exit(int(SIGNALS["ERROR"]))

    if opts.section_type == "backends":
        try:
            backendy = _getBackends(socket=h)
            if backendy:
                pass
            else:
                sys.exit(int(SIGNALS["UNKNOWN"]))
        except Exception as e:
            logger.error('Unable to retrieve backends data! - {}'.format(
                str(e)))
            sys.exit(int(SIGNALS["ERROR"]))

    if opts.section_type == "frontends":
        try:
            frontendy = _getFrontends(socket=h)
            if frontendy:
                pass
            else:
                sys.exit(int(SIGNALS["UNKNOWN"]))
        except Exception as e:
            logger.error('Unable to retrieve frontends data! - {}'.format(
                str(e)))
            sys.exit(int(SIGNALS["ERROR"]))

    if opts.section_type == "frontends":
        filtered_frontends = {
            k: v
            for k, v in frontendy.items() if k not in exclude_app
        }
    else:
        filtered_backends = {
            k: v
            for k, v in backendy.items() if k not in exclude_app
        }

    try:
        other_backend = {}
        down_backend = {}
        up_backend = {}

        if opts.section_type == "frontends":
            for k, v in filtered_frontends.items():
                if v == "DOWN":
                    down_backend[k] = v
                elif v == "OPEN":
                    up_backend[k] = v
                else:
                    other_backend.append(k)
        elif opts.section_type == "backends":
            for k, v in filtered_backends.items():
                if v == "DOWN":
                    down_backend[k] = v
                elif v == "UP":
                    up_backend[k] = v
                else:
                    other_backend[k] = v

        if down_backend and not other_backend:
            raise ExceptionDownBackend
        if other_backend:
            raise ExceptionOtherBackend
        if up_backend:
            raise ExceptionUpBackend

    except ExceptionDownBackend:
        logger.error('Some {} has DOWN state: {}'.format(
            opts.section_type, down_backend))
        raise SystemExit(int(SIGNALS["ERROR"]))
    except ExceptionOtherBackend:
        logger.error('UNKNOW status of {}: - {}'.format(
            opts.section_type, other_backend))
        raise SystemExit(int(SIGNALS["UNKNOWN"]))
    except ExceptionUpBackend:
        logger.info('OK: All {} {} are right state'.format(
            len(up_backend), opts.section_type))
        raise SystemExit(int(SIGNALS["OK"]))
    except Exception as e:
        logger.error('Error processing or parsing output! - {}'.format(str(e)))
        sys.exit(int(SIGNALS["ERROR"]))
    finally:
        if down_backend and other_backend:
            error_backend = {**down_backend, **other_backend}
            logger.error('Some {} has DOWN or UNKNOWN state: {}'.format(
                opts.section_type, error_backend))
            raise SystemExit(int(SIGNALS["ERROR"]))
        else:
            pass
Beispiel #17
0
import os

from flask import Flask, render_template, redirect, url_for, g
from haproxyadmin import haproxy, server

app = Flask(__name__)
config = os.environ.get('HAPLO_CONFIG', 'config.DevelopmentConfig')
app.config.from_object(config)
hap = haproxy.HAProxy(uris=app.config['HAPROXY_URIS'],
                      socket_dir=app.config['HAPROXY_SOCKET_DIR'],
                      socket_file=app.config['HAPROXY_SOCKET_FILE'])


@app.route('/')
def index():
    refresh_servers()
    return render_template('index.html.j2')


@app.route('/disable_server/<backend>/<s_name>')
def disable_server(backend=None, s_name=None):
    b = hap.backend(backend)
    s = b.server(s_name)
    s.setstate(server.STATE_DISABLE)

    return redirect(url_for('index'))


@app.route('/enable_server/<backend>/<s_name>')
def enable_server(backend=None, s_name=None):
    b = hap.backend(backend)
Beispiel #18
0
def set_server_state(backend_name, server_name, state):
    hap = haproxy.HAProxy(socket_file=HAPROXY_SOCKET_FILE)
    servers = hap.server(server_name, backend=backend_name)
    if (len(servers) > 0):
        servers[0].setstate(state)
Beispiel #19
0
def dashboard():
  ip=get_x_ip()
  hap=haproxy.HAProxy(socket_dir='/var/run/',socket_file='haproxy.sock')
  acls=[ x.split()[1] for x in hap.show_acl(0) ]
  #hap.add_acl(0,'111.47.27.238/32')   ##ref: http://haproxyadmin.readthedocs.io/en/latest/user/haproxy.html?highlight=acl
  return render_template('dashboard.html', name=current_user.username, user_ip=ip, acls=acls)
Beispiel #20
0
def list_backends():
    hap = haproxy.HAProxy(socket_file=config.haproxy.unix_socket)
    backends = hap.backends()
    return BackendSchema().dump(backends, many=True).data
Beispiel #21
0
def list_servers(backend_name):
    hap = haproxy.HAProxy(socket_file=HAPROXY_SOCKET_FILE)
    backend = hap.backend(backend_name)
    servers = backend.servers()
    return ServerSchema().dump(servers, many=True).data