Exemplo n.º 1
0
    def clear_acl(self, acl):
        """Remove all entries from a acl.

        :param acl: acl id or a file.
        :type acl: ``integer`` or a file path passed as ``string``
        :return: True if command succeeds otherwise False
        :rtype: bool

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.clear_acl(acl=4)
          True
          >>> hap.clear_acl(acl='/etc/haproxy/bl_frontend')
          True
        """
        if isint(acl):
            cmd = "clear acl #{}".format(acl)
        else:
            cmd = "clear acl {}".format(acl)

        results = cmd_across_all_procs(self._hap_processes, 'command',
                                       cmd)

        return check_command(results)
Exemplo n.º 2
0
    def add_acl(self, acl, pattern):
        """Add an entry into the acl.

        :param acl: acl id or a file.
        :type acl: ``integer`` or a file path passed as ``string``
        :param pattern: entry to add.
        :type pattern: ``string``
        :return: ``True`` if command succeeds otherwise ``False``
        :rtype: ``bool``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.show_acl(acl=4)
          ['0x23181c0 /static/css/']
          >>> hap.add_acl(acl=4, pattern='/foo/' )
          True
          >>> hap.show_acl(acl=4)
          ['0x23181c0 /static/css/', '0x238f790 /foo/']
        """
        if isint(acl):
            cmd = "add acl #{} {}".format(acl, pattern)
        else:
            cmd = "add acl {} {}".format(acl, pattern)

        results = cmd_across_all_procs(self._hap_processes, 'command',
                                       cmd)

        return check_command(results)
Exemplo n.º 3
0
    def add_map(self, mapid, key, value):
        """Add an entry into the map.

        :param mapid: map id or a file.
        :type mapid: ``integer`` or a file path passed as ``string``
        :param key: key to add.
        :type key: ``string``
        :param value: Value assciated to the key.
        :type value: ``string``
        :return: ``True`` if command succeeds otherwise ``False``.
        :rtype: ``bool``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.show_map(0)
          ['0x1a78b20 1 www.foo.com-1']
          >>> hap.add_map(0, '9', 'foo')
          True
          >>> hap.show_map(0)
          ['0x1a78b20 1 www.foo.com-1', '0x1b15c80 9 foo']
        """
        if isint(mapid):
            cmd = "add map #{} {} {}".format(mapid, key, value)
        else:
            cmd = "add map {} {} {}".format(mapid, key, value)

        results = cmd_across_all_procs(self._hap_processes, 'command',
                                       cmd)

        return check_command(results)
Exemplo n.º 4
0
    def command(self, cmd):
        """Send a command to haproxy process.

        This allows a user to send any kind of command to
        haproxy. We **do not* perfom any sanitization on input
        and on output.

        :param cmd: a command to send to haproxy process.
        :type cmd: ``string``
        :return: list of 2-item tuple

        #. HAProxy process number
        #. what the method returned

        :rtype: ``list``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.command('show stats')
          ['0x23181c0 /static/css/']
          >>> hap.add_acl(acl=4, pattern='/foo/' )
          True
          >>> hap.show_acl(acl=4)
          ['0x23181c0 /static/css/', '0x238f790 /foo/']
        """
        return cmd_across_all_procs(self._hap_processes,
                                    'command', cmd, full_output=True)
Exemplo n.º 5
0
    def get_acl(self, acl, value):
        """Lookup the value in the ACL.

        :param acl: acl id or a file.
        :type acl: ``integer`` or a file path passed as ``string``
        :param value: value to lookup
        :type value: ``string``
        :return: matching patterns associated with ACL.
        :rtype: ``string``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.show_acl(acl=4)
          ['0x2318120 /static/js/', '0x23181c0 /static/css/']
          >>> hap.get_acl(acl=4, value='/foo')
          'type=beg, case=sensitive, match=no'
          >>> hap.get_acl(acl=4, value='/static/js/')
          'type=beg, case=sensitive, match=yes, idx=tree, pattern="/static/js/"'
        """
        if isint(acl):
            cmd = "get acl #{} {}".format(acl, value)
        else:
            cmd = "get acl {} {}".format(acl, value)

        get_results = cmd_across_all_procs(self._hap_processes, 'command', cmd)
        get_info_proc1 = get_results[0][1]
        if not check_output(get_info_proc1):
            raise ValueError(get_info_proc1)

        return get_info_proc1
Exemplo n.º 6
0
    def address(self):
        """The assigned address of server.

        :getter: :rtype: ``string``
        :setter:
          :param address: address to set.
          :type address: ``string``
          :rtype: ``bool``
        """
        values = cmd_across_all_procs(
            self._server_per_proc, 'metric', 'addr'
        )

        try:
            value = compare_values(values)
        except IncosistentData as exc:
            # haproxy returns address:port and compare_values() may raise
            # IncosistentData exception because assigned port is different
            # per process and not the assigned address.
            # Since we want to report the address, we simply catch that case
            # and report the assigned address.
            addr_across_proc = [value[1].split(':')[0] for value in values]
            if not elements_of_list_same(addr_across_proc):
                raise exc
            else:
                return addr_across_proc[0]
        else:
            return value.split(':')[0]
Exemplo n.º 7
0
    def get_map(self, mapid, value):
        """Lookup the value in the map.

        :param mapid: map id or a file.
        :type mapid: ``integer`` or a file path passed as ``string``
        :param value: value to lookup.
        :type value: ``string``
        :return: matching patterns associated with map.
        :rtype: ``string``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.show_map(0)
          ['0x1a78980 11 new2', '0x1b15c00 22 0']
          >>> hap.get_map(0, '11')
          'type=str, case=sensitive, found=yes, idx=tree, key="11", value="new2", type="str"'
          >>> hap.get_map(0, '10')
          'type=str, case=sensitive, found=no'
        """
        if isint(mapid):
            cmd = "get map #{} {}".format(mapid, value)
        else:
            cmd = "get map {} {}".format(mapid, value)

        get_results = cmd_across_all_procs(self._hap_processes, 'command',
                                           cmd)
        get_info_proc1 = get_results[0][1]
        if not check_output(get_info_proc1):
            raise CommandFailed(get_info_proc1[0])

        return get_info_proc1
Exemplo n.º 8
0
    def setmaxconn(self, value):
        """Set maximum connection to the frontend.

        :param die: control the handling of errors.
        :type die: ``bool``
        :param value: max connection value.
        :type value: ``integer``
        :return: ``True`` if value was set.
        :rtype: ``bool``
        :raise: If ``die`` is ``True``
          :class:`haproxyadmin.exceptions.CommandFailed` or
          :class:`haproxyadmin.exceptions.MultipleCommandResults` is raised
          when something bad happens otherwise returns ``False``.

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> frontend = hap.frontend('frontend1_proc34')
          >>> frontend.maxconn
          >>> frontend.setmaxconn(50000)
          True
          >>> frontend.maxconn
          100000
        """
        if not isinstance(value, int):
            raise ValueError("Expected integer and got {}".format(type(value)))

        cmd = "set maxconn frontend {} {}".format(self.name, value)
        results = cmd_across_all_procs(self._frontend_per_proc, 'command', cmd)

        return check_command(results)
Exemplo n.º 9
0
    def clear_map(self, mapid):
        """Remove all entries from a mapid.

        :param mapid: map id or a file
        :type mapid: ``integer`` or a file path passed as ``string``
        :return: ``True`` if command succeeds otherwise ``False``
        :rtype: ``bool``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.clear_map(0)
          True
          >>> hap.clear_map(mapid='/etc/haproxy/bl_frontend')
          True
        """
        if isint(mapid):
            cmd = "clear map #{}".format(mapid)
        else:
            cmd = "clear map {}".format(mapid)

        results = cmd_across_all_procs(self._hap_processes, 'command',
                                       cmd)

        return check_command(results)
Exemplo n.º 10
0
    def address(self, address):
        """Set server's address."""
        cmd = "set server {}/{} addr {}".format(
            self.backendname, self.name, address
        )
        results = cmd_across_all_procs(self._server_per_proc, 'command', cmd)

        return check_command_addr_port('addr', results)
Exemplo n.º 11
0
    def port(self, port):
        """Set server's port."""
        cmd = "set server {}/{} addr {} port {}".format(
            self.backendname, self.name, self.address, port
        )
        results = cmd_across_all_procs(self._server_per_proc, 'command', cmd)

        return check_command_addr_port('port', results)
Exemplo n.º 12
0
    def check_code(self):
        """Return the check code.

        :rtype: ``integer``
        """
        values = cmd_across_all_procs(
            self._server_per_proc, 'metric', 'check_code'
        )

        return compare_values(values)
Exemplo n.º 13
0
    def check_status(self):
        """Return the check status.

        :rtype: ``string``
        """
        values = cmd_across_all_procs(
            self._server_per_proc, 'metric', 'check_status'
        )

        return compare_values(values)
Exemplo n.º 14
0
    def requests_per_process(self):
        """Return the number of requests for the server per process.

        :rtype: A list of tuple, where 1st element is process number and 2nd
          element is requests.

        """
        results = cmd_across_all_procs(self._server_per_proc, 'metric', 'stot')

        return results
Exemplo n.º 15
0
    def weight(self):
        """Return the weight.

        :rtype: ``integer``
        :raise: :class:`IncosistentData` exception if weight is different
          per process
        """
        values = cmd_across_all_procs(self._server_per_proc, 'metric', 'weight')

        return compare_values(values)
Exemplo n.º 16
0
    def last_agent_check(self):
        """Return the last agent check contents or textual error.

        :rtype: ``string``
        """
        values = cmd_across_all_procs(
            self._server_per_proc, 'metric', 'last_agt'
        )

        return compare_values(values)
Exemplo n.º 17
0
    def status(self):
        """Return the status of the backend.

        :rtype: ``string``
        :raise: :class:`IncosistentData` exception if status is different
          per process.

        """
        results = cmd_across_all_procs(self._backend_per_proc, 'metric', 'status')

        return compare_values(results)
Exemplo n.º 18
0
    def status(self):
        """Return the status of the server.

        :rtype: ``string``
        :raise: :class:`IncosistentData` exception if status is different
          per process

        """
        values = cmd_across_all_procs(self._server_per_proc, 'metric', 'status')

        return compare_values(values)
Exemplo n.º 19
0
    def shutdown(self):
        """Terminate all the sessions attached to the specified server.

        :return: ``True`` if command succeeds otherwise ``False``.
        :rtype: ``bool``
        """

        cmd = "shutdown sessions server {b}/{s}".format(b=self.backendname,
                                                        s=self.name)
        results = cmd_across_all_procs(self._server_per_proc, 'command', cmd)

        return check_command(results)
Exemplo n.º 20
0
    def shutdown(self):
        """Disable the frontend.

        .. warning::
           HAProxy removes from the running configuration a frontend, so
           further operations on the frontend will return an error.

        :rtype: ``bool``
        """
        cmd = "shutdown frontend {}".format(self.name)
        results = cmd_across_all_procs(self._frontend_per_proc, 'command', cmd)

        return check_command(results)
Exemplo n.º 21
0
    def stats_per_process(self):
        """Return all stats of the frontend per process.

        :return: a list of tuples with 2 elements

          #. process number
          #. a dict with all stats

        :rtype: ``list``

        """
        results = cmd_across_all_procs(self._frontend_per_proc, 'stats')

        return results
Exemplo n.º 22
0
    def setaddress(self, new_address, new_port=None):
        """Set this servers address.

        :param new_address: new ip address of server
        :param new_port: new port of server (optional)

        :rtype: ``string``
        """

        values = cmd_across_all_procs(
            self._server_per_proc, 'setaddress', new_address=str(new_address), new_port=new_port
        )

        return compare_values(values)
Exemplo n.º 23
0
    def requests_per_process(self):
        """Return the number of requests for the backend per process.

        :return: a list of tuples with 2 elements

          #. process number of HAProxy
          #. requests

        :rtype: ``list``

        """
        results = cmd_across_all_procs(self._backend_per_proc, 'metric', 'stot')

        return results
Exemplo n.º 24
0
    def stats_per_process(self):
        """Return all stats of the server per process.

        :return: A list of tuple 2 elements

          #. process number
          #. a dict with all stats

        :rtype: ``list``

        """
        values = cmd_across_all_procs(self._server_per_proc, 'stats')

        return values
Exemplo n.º 25
0
    def stats_per_process(self):
        """Return all stats of the backend per process.

        :return: a list of tuples with 2 elements

          #. process number
          #. a dict with all stats

        :rtype: ``list``

        """
        values = cmd_across_all_procs(self._backend_per_proc, 'stats')

        return values
Exemplo n.º 26
0
    def setstate(self, state):
        """Set the state of a server in the backend.

        State can be any of the following

          * :const:`haproxyadmin.haproxy.STATE_ENABLE`: Mark the server UP and
            checks are re-enabled
          * :const:`haproxyadmin.haproxy.STATE_DISABLE`: Mark the server DOWN
            for maintenance and checks disabled.
          * :const:`haproxyadmin.haproxy.STATE_READY`: Put server in normal
            mode.
          * :const:`haproxyadmin.haproxy.STATE_DRAIN`: Remove the server from
            load balancing.
          * :const:`haproxyadmin.haproxy.STATE_MAINT`: Remove the server from
            load balancing and health checks are disabled.

        :param state: state to set.
        :type state: ``string``
        :return: ``True`` if command succeeds otherwise ``False``.
        :rtype: ``bool``

        Usage:

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> server = hap.server('member_bkall', backend='backend_proc1')[0]
          >>> server.setstate(haproxy.STATE_DISABLE)
          True
          >>> server.status
          'MAINT'
          >>> server.setstate(haproxy.STATE_ENABLE)
          True
          >>> server.status
          'no check'

        """
        if state not in VALID_STATES:
            states = ', '.join(VALID_STATES)
            raise ValueError("Wrong state, allowed states {}".format(states))
        if state == 'enable' or state == 'disable':
            cmd = "{} server {}/{}".format(state, self.backendname, self.name)
        else:
            cmd = "set server {}/{} state {}".format(
                self.backendname, self.name, state
            )

        results = cmd_across_all_procs(self._server_per_proc, 'command', cmd)

        return check_command(results)
Exemplo n.º 27
0
    def setstate(self, state):
        """Set the state of a server in the backend.

        State can be any of the following

          * :const:`haproxyadmin.haproxy.STATE_ENABLE`: Mark the server UP and
            checks are re-enabled
          * :const:`haproxyadmin.haproxy.STATE_DISABLE`: Mark the server DOWN
            for maintenance and checks disabled.
          * :const:`haproxyadmin.haproxy.STATE_READY`: Put server in normal
            mode.
          * :const:`haproxyadmin.haproxy.STATE_DRAIN`: Remove the server from
            load balancing.
          * :const:`haproxyadmin.haproxy.STATE_MAINT`: Remove the server from
            load balancing and health checks are disabled.

        :param state: state to set.
        :type state: ``string``
        :return: ``True`` if command succeeds otherwise ``False``.
        :rtype: ``bool``

        Usage:

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> server = hap.server('member_bkall', backend='backend_proc1')[0]
          >>> server.setstate(haproxy.STATE_DISABLE)
          True
          >>> server.status
          'MAINT'
          >>> server.setstate(haproxy.STATE_ENABLE)
          True
          >>> server.status
          'no check'

        """
        if state not in VALID_STATES:
            states = ', '.join(VALID_STATES)
            raise ValueError("Wrong state, allowed states {}".format(states))
        if state == 'enable' or state == 'disable':
            cmd = "{} server {}/{}".format(state, self.backendname, self.name)
        else:
            cmd = "set server {}/{} state {}".format(
                self.backendname, self.name, state
            )

        results = cmd_across_all_procs(self._server_per_proc, 'command', cmd)

        return check_command(results)
Exemplo n.º 28
0
    def requests_per_process(self):
        """Return the number of requests for the backend per process.

        :return: a list of tuples with 2 elements

          #. process number of HAProxy
          #. requests

        :rtype: ``list``

        """
        results = cmd_across_all_procs(self._backend_per_proc, 'metric',
                                       'stot')

        return results
Exemplo n.º 29
0
    def nodename(self):
        """Return nodename of HAProxy

        :rtype: ``string``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.nodename
          'test.foo.com'
        """
        values = cmd_across_all_procs(self._hap_processes, 'metric', 'node')

        return compare_values(values)
Exemplo n.º 30
0
    def setratelimitsslsess(self, value):
        """Set process-wide ssl session rate limit.

        :param value: rate ssl session limit.
        :type value: ``integer``
        :return: ``True`` if command succeeds otherwise ``False``.
        :rtype: ``bool``
        :raises: ``ValueError`` if value is not an ``integer``.
        """
        if not isinstance(value, int):
            raise ValueError("Expected integer and got {}".format(type(value)))
        cmd = "set rate-limit ssl-sessions global {}".format(value)

        results = cmd_across_all_procs(self._hap_processes, 'command', cmd)

        return check_command(results)
Exemplo n.º 31
0
    def enable(self):
        """Enable frontend.

        :param die: control the handling of errors.
        :type die: ``bool``
        :return: ``True`` if frontend is enabled otherwise ``False``.
        :rtype: bool
        :raise: If ``die`` is ``True``
          :class:`haproxyadmin.exceptions.CommandFailed` or
          :class:`haproxyadmin.exceptions.MultipleCommandResults` is raised
          when something bad happens otherwise returns ``False``.
        """
        cmd = "enable frontend {}".format(self.name)
        results = cmd_across_all_procs(self._frontend_per_proc, 'command', cmd)

        return check_command(results)
Exemplo n.º 32
0
    def nodename(self):
        """Return nodename of HAProxy

        :rtype: ``string``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.nodename
          'test.foo.com'
        """
        values = cmd_across_all_procs(self._hap_processes, 'metric',
                                      'node')

        return compare_values(values)
Exemplo n.º 33
0
    def enable(self):
        """Enable frontend.

        :param die: control the handling of errors.
        :type die: ``bool``
        :return: ``True`` if frontend is enabled otherwise ``False``.
        :rtype: bool
        :raise: If ``die`` is ``True``
          :class:`haproxyadmin.exceptions.CommandFailed` or
          :class:`haproxyadmin.exceptions.MultipleCommandResults` is raised
          when something bad happens otherwise returns ``False``.
        """
        cmd = "enable frontend {}".format(self.name)
        results = cmd_across_all_procs(self._frontend_per_proc, 'command', cmd)

        return check_command(results)
Exemplo n.º 34
0
    def releasedate(self):
        """Return release date of HAProxy

        :rtype: ``string``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.releasedate
          '2014/10/31'
        """
        values = cmd_across_all_procs(self._hap_processes, 'metric',
                                      'Release_date')

        return compare_values(values)
Exemplo n.º 35
0
    def uptime(self):
        """Return uptime of HAProxy process

        :rtype: string

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.uptime
          '4d 0h16m26s'
        """
        values = cmd_across_all_procs(self._hap_processes, 'metric', 'Uptime')

        # Just return the uptime of the 1st process
        return values[0][1]
Exemplo n.º 36
0
    def description(self):
        """Return description of HAProxy

        :rtype: ``string``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.description
          'test'
        """
        values = cmd_across_all_procs(self._hap_processes, 'metric',
                                      'description')

        return compare_values(values)
Exemplo n.º 37
0
    def description(self):
        """Return description of HAProxy

        :rtype: ``string``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.description
          'test'
        """
        values = cmd_across_all_procs(self._hap_processes, 'metric',
                                      'description')

        return compare_values(values)
Exemplo n.º 38
0
    def releasedate(self):
        """Return release date of HAProxy

        :rtype: ``string``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.releasedate
          '2014/10/31'
        """
        values = cmd_across_all_procs(self._hap_processes, 'metric',
                                      'Release_date')

        return compare_values(values)
Exemplo n.º 39
0
    def setratelimitsslsess(self, value):
        """Set process-wide ssl session rate limit.

        :param value: rate ssl session limit.
        :type value: ``integer``
        :return: ``True`` if command succeeds otherwise ``False``.
        :rtype: ``bool``
        :raises: ``ValueError`` if value is not an ``integer``.
        """
        if not isinstance(value, int):
            raise ValueError("Expected integer and got {}".format(type(value)))
        cmd = "set rate-limit ssl-sessions global {}".format(value)

        results = cmd_across_all_procs(self._hap_processes, 'command', cmd)

        return check_command(results)
Exemplo n.º 40
0
    def show_acl(self, aclid=None):
        """Dump info about acls.

        Without argument, the list of all available acls is returned.
        If a aclid is specified, its contents are dumped.

        :param aclid: (optional) acl id or a file
        :type aclid: ``integer`` or a file path passed as ``string``
        :return: a list with the acls
        :rtype: ``list``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.show_acl(aclid=6)
          ['0x1d09730 ver%3A27%3Bvar%3A0']
          >>> hap.show_acl()
          ['# id (file) description',
          "1 () acl 'ssl_fc' file '/etc/haproxy/haproxy.cfg' line 83",
          "2 () acl 'src' file '/etc/haproxy/haproxy.cfg' line 95",
          "3 () acl 'path_beg' file '/etc/haproxy/haproxy.cfg' line 97",
          ]
        """
        if aclid is not None:
            if isint(aclid):
                cmd = "show acl #{}".format(aclid)
            else:
                cmd = "show acl {}".format(aclid)
        else:
            cmd = "show acl"

        acl_info = cmd_across_all_procs(self._hap_processes,
                                        'command',
                                        cmd,
                                        full_output=True)
        # ACL can't be different per process thus we only return the acl
        # content found in 1st process.
        acl_info_proc1 = acl_info[0][1]

        if not check_output(acl_info_proc1):
            raise CommandFailed(acl_info_proc1[0])

        if len(acl_info_proc1) == 1 and not acl_info_proc1[0]:
            return []
        else:
            return acl_info_proc1
Exemplo n.º 41
0
    def show_acl(self, aclid=None):
        """Dump info about acls.

        Without argument, the list of all available acls is returned.
        If a aclid is specified, its contents are dumped.

        :param aclid: (optional) acl id or a file
        :type aclid: ``integer`` or a file path passed as ``string``
        :return: a list with the acls
        :rtype: ``list``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.show_acl(aclid=6)
          ['0x1d09730 ver%3A27%3Bvar%3A0']
          >>> hap.show_acl()
          ['# id (file) description',
          "1 () acl 'ssl_fc' file '/etc/haproxy/haproxy.cfg' line 83",
          "2 () acl 'src' file '/etc/haproxy/haproxy.cfg' line 95",
          "3 () acl 'path_beg' file '/etc/haproxy/haproxy.cfg' line 97",
          ]
        """
        if aclid is not None:
            if isint(aclid):
                cmd = "show acl #{}".format(aclid)
            else:
                cmd = "show acl {}".format(aclid)
        else:
            cmd = "show acl"

        acl_info = cmd_across_all_procs(self._hap_processes, 'command',
                                        cmd,
                                        full_output=True)
        # ACL can't be different per process thus we only return the acl
        # content found in 1st process.
        acl_info_proc1 = acl_info[0][1]

        if not check_output(acl_info_proc1):
            raise CommandFailed(acl_info_proc1[0])

        if len(acl_info_proc1) == 1 and not acl_info_proc1[0]:
            return []
        else:
            return acl_info_proc1
Exemplo n.º 42
0
    def version(self):
        """Return version of HAProxy

        :rtype: ``string``

        Usage::
          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.version
          '1.5.8'
        """
        # If multiple version of HAProxy share the same socket directory
        # then this wil always raise IncosistentData exception.
        # TODO: Document this on README
        values = cmd_across_all_procs(self._hap_processes, 'metric', 'Version')

        return compare_values(values)
Exemplo n.º 43
0
    def uptimesec(self):
        """Return uptime of HAProxy process in seconds

        :rtype: ``integer``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.uptimesec
          346588
        """
        values = cmd_across_all_procs(self._hap_processes, 'metric',
                                      'Uptime_sec')

        # Just return the uptime of the 1st process
        return values[0][1]
Exemplo n.º 44
0
    def uptime(self):
        """Return uptime of HAProxy process

        :rtype: string

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.uptime
          '4d 0h16m26s'
        """
        values = cmd_across_all_procs(self._hap_processes, 'metric',
                                      'Uptime')

        # Just return the uptime of the 1st process
        return values[0][1]
Exemplo n.º 45
0
    def setweight(self, value):
        """Set a weight.

        If the value ends with the '%' sign, then the new weight will be
        relative to the initially configured weight.  Absolute weights
        are permitted between 0 and 256.

        :param value: Weight to set
        :type value: integer or string with '%' sign
        :return: ``True`` if command succeeds otherwise ``False``.
        :rtype: ``bool``

        Usage:

           >>> from haproxyadmin import haproxy
           >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
           >>> server = hap.server('member_bkall', backend='backend_proc1')[0]
           >>> server.weight
           100
           >>> server.setweight('20%')
           True
           >>> server.weight
           20
           >>> server.setweight(58)
           True
           >>> server.weight
           58
        """
        msg = (
            "Invalid weight, absolute weights are permitted between 0 and "
            "256 and need to be passed as integers or relative weights "
            "are allowed when the value ends with the '%' sign pass as "
            "string"
        )
        if isinstance(value, int) and 0 <= value < 256 or (
                isinstance(value, str) and value.endswith('%')):
            cmd = "set weight {}/{} {}".format(self.backendname,
                                               self.name,
                                               value)
        else:
            raise ValueError(msg)

        results = cmd_across_all_procs(self._server_per_proc, 'command', cmd)

        return check_command(results)
Exemplo n.º 46
0
    def show_map(self, mapid=None):
        """Dump info about maps.

        Without argument, the list of all available maps is returned.
        If a mapid is specified, its contents are dumped.

        :param mapid: (optional) map id or a file.
        :type mapid: ``integer`` or a file path passed as ``string``
        :return: a list with the maps.
        :rtype: ``list``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.show_map()
          ['# id (file) description',
           "0 (/etc/haproxy/v-m1-bk) pattern loaded ...... line 82",
           ]
          >>> hap.show_map(mapid=0)
          ['0x1a78ab0 0 www.foo.com-0', '0x1a78b20 1 www.foo.com-1']
        """
        if mapid is not None:
            if isint(mapid):
                cmd = "show map #{}".format(mapid)
            else:
                cmd = "show map {}".format(mapid)
        else:
            cmd = "show map"
        map_info = cmd_across_all_procs(self._hap_processes,
                                        'command',
                                        cmd,
                                        full_output=True)
        # map can't be different per process thus we only return the map
        # content found in 1st process.
        map_info_proc1 = map_info[0][1]

        if not check_output(map_info_proc1):
            raise CommandFailed(map_info_proc1[0])

        if len(map_info_proc1) == 1 and not map_info_proc1[0]:
            return []
        else:
            return map_info_proc1
Exemplo n.º 47
0
    def set_map(self, mapid, key, value):
        """Modify the value corresponding to each key in a map.

        mapid is the #<id> or <file> returned by
        :func:`show_map <haproxyadmin.haproxy.HAProxy.show_map>`.

        :param mapid: map id or a file.
        :type mapid: ``integer`` or a file path passed as ``string``
        :param key: key id
        :type key: ``string``
        :param value: value to set for the key.
        :type value: ``string``
        :return: ``True`` if command succeeds otherwise ``False``.
        :rtype: ``bool``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.show_map(0)
          ['0x1a78980 11 9', '0x1b15c00 22 0']
          >>> hap.set_map(0, '11', 'new')
          True
          >>> hap.show_map(0)
          ['0x1a78980 11 new', '0x1b15c00 22 0']
          >>> hap.set_map(0, '0x1a78980', 'new2')
          True
          >>> hap.show_map(0)
          ['0x1a78980 11 new2', '0x1b15c00 22 0']
        """
        if key.startswith('0x'):
            key = "#{}".format(key)

        if isint(mapid):
            cmd = "set map #{} {} {}".format(mapid, key, value)
        elif os.path.isfile(mapid):
            cmd = "set map {} {} {}".format(mapid, key, value)
        else:
            raise ValueError("Invalid input")

        results = cmd_across_all_procs(self._hap_processes, 'command', cmd)

        return check_command(results)
Exemplo n.º 48
0
    def status(self):
        """Return the status of the frontend.

        :rtype: ``string``
        :raise: :class:`IncosistentData` exception if status is different
          per process

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> frontend = hap.frontend('frontend2_proc34')
          >>> frontend.status
          'OPEN'
        """
        results = cmd_across_all_procs(self._frontend_per_proc, 'metric',
                                       'status')

        return compare_values(results)
Exemplo n.º 49
0
    def del_map(self, mapid, key):
        """Delete all the map entries from the map corresponding to the key.

        :param mapid: map id or a file.
        :type mapid: ``integer`` or a file path passed as ``string``.
        :param key: key to delete
        :type key: ``string``
        :return: ``True`` if command succeeds otherwise ``False``.
        :rtype: ``bool``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.show_map(0)
          ['0x1b15cd0 9 foo', '0x1a78980 11 bar']
          >>> hap.del_map(0, '0x1b15cd0')
          True
          >>> hap.show_map(0)
          ['0x1a78980 11 bar']
          >>> hap.add_map(0, '22', 'bar22')
          True
          >>> hap.show_map(0)
          ['0x1a78980 11 bar', '0x1b15c00 22 bar22']
          >>> hap.del_map(0, '22')
          True
          >>> hap.show_map(0)
          ['0x1a78980 11 bar']
        """
        if key.startswith('0x'):
            key = "#{}".format(key)

        if isint(mapid):
            cmd = "del map #{} {}".format(mapid, key)
        elif os.path.isfile(mapid):
            cmd = "del map {} {}".format(mapid, key)
        else:
            raise ValueError("Invalid input")

        results = cmd_across_all_procs(self._hap_processes, 'command', cmd)

        return check_command(results)
Exemplo n.º 50
0
    def clearcounters(self, all=False):
        """Clear the max values of the statistics counters.

        When ``all`` is set to ``True`` clears all statistics counters in
        each proxy (frontend & backend) and in each server. This has the same
        effect as restarting.

        :param all: (optional) clear all statistics counters.
        :type all: ``bool``
        :return: ``True`` if command succeeds otherwise ``False``.
        :rtype: ``bool``
        """
        if all:
            cmd = "clear counters all"
        else:
            cmd = "clear counters"

        results = cmd_across_all_procs(self._hap_processes, 'command', cmd)

        return check_command(results)
Exemplo n.º 51
0
    def requests_per_process(self):
        """Return the number of requests for the frontend per process.

        :return: a list of tuples with 2 elements

          #. process number of HAProxy
          #. requests

        :rtype: ``list``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> frontend = hap.frontend('frontend2_proc34')
          >>> frontend.requests_per_process()
          [(4, 2), (3, 3)]
        """
        results = cmd_across_all_procs(self._frontend_per_proc, 'metric',
                                       'req_tot')

        return results
Exemplo n.º 52
0
    def setmaxconn(self, value):
        """Set maximum connection to the frontend.

        :param value: value to set.
        :type value: ``integer``
        :return: ``True`` if command succeeds otherwise ``False``.
        :rtype: ``bool``

        Usage:

           >>> from haproxyadmin import haproxy
           >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
           >>> hap.setmaxconn(5555)
           True
        """
        if not isinstance(value, int):
            raise ValueError("Expected integer and got {}".format(type(value)))
        cmd = "set maxconn global {}".format(value)

        results = cmd_across_all_procs(self._hap_processes, 'command', cmd)

        return check_command(results)
Exemplo n.º 53
0
    def del_acl(self, acl, key):
        """Delete all the acl entries from the acl corresponding to the key.

        :param acl: acl id or a file
        :type acl: ``integer`` or a file path passed as ``string``
        :param key: key to delete.
        :type key: ``string``
        :return: ``True`` if command succeeds otherwise ``False``.
        :rtype: ``bool``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.show_acl(acl=4)
          ['0x23181c0 /static/css/', '0x238f790 /foo/', '0x238f810 /bar/']
          >>> hap.del_acl(acl=4, key='/static/css/')
          True
          >>> hap.show_acl(acl=4)
          ['0x238f790 /foo/', '0x238f810 /bar/']
          >>> hap.del_acl(acl=4, key='0x238f790')
          True
          >>> hap.show_acl(acl=4)
          ['0x238f810 /bar/']
        """
        if key.startswith('0x'):
            key = "#{}".format(key)

        if isint(acl):
            cmd = "del acl #{} {}".format(acl, key)
        elif os.path.isfile(acl):
            cmd = "del acl {} {}".format(acl, key)
        else:
            raise ValueError("Invalid input")

        results = cmd_across_all_procs(self._hap_processes, 'command', cmd)

        return check_command(results)
Exemplo n.º 54
0
    def errors(self, iid=None):
        """Dump last known request and response errors.

        If <iid> is specified, the limit the dump to errors concerning
        either frontend or backend whose ID is <iid>.

        :param iid: (optional) ID of frontend or backend.
        :type iid: integer
        :return: A list of tuples of errors per process.

          #. process number
          #. ``list`` of errors

        :rtype: ``list``
        """
        if iid:
            cmd = "show errors {}".format(iid)
        else:
            cmd = "show errors"

        return cmd_across_all_procs(self._hap_processes,
                                    'command',
                                    cmd,
                                    full_output=True)