File: haproxy.py

package info (click to toggle)
python-haproxyadmin 0.2.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 436 kB
  • sloc: python: 1,500; makefile: 165; sh: 1
file content (1061 lines) | stat: -rw-r--r-- 34,105 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
# -*- coding: utf-8 -*- #
# pylint: disable=superfluous-parens
#

"""
haproxyadmin.haproxy
~~~~~~~~~~~~~~~~~~~~

This module implements the main haproxyadmin API.

"""
import os
import glob

from haproxyadmin.frontend import Frontend
from haproxyadmin.backend import Backend
from haproxyadmin.utils import (is_unix_socket, cmd_across_all_procs, converter,
                                calculate, isint, should_die, check_command,
                                check_output, compare_values, connected_socket)
from haproxyadmin.internal.haproxy import _HAProxyProcess
from haproxyadmin.exceptions import CommandFailed


HAPROXY_METRICS = [
    'SslFrontendMaxKeyRate',
    'Hard_maxconn',
    'SessRateLimit',
    'Process_num',
    'Memmax_MB',
    'CompressBpsRateLim',
    'MaxSslConns',
    'ConnRateLimit',
    'SslRateLimit',
    'MaxConnRate',
    'CumConns',
    'SslBackendKeyRate',
    'SslCacheLookups',
    'CurrSslConns',
    'Run_queue',
    'Maxpipes',
    'Idle_pct',
    'SslFrontendKeyRate',
    'Tasks',
    'MaxZlibMemUsage',
    'SslFrontendSessionReuse_pct',
    'CurrConns',
    'SslCacheMisses',
    'SslRate',
    'CumSslConns',
    'PipesUsed',
    'Maxconn',
    'CompressBpsIn',
    'ConnRate',
    'Ulimit-n',
    'SessRate',
    'SslBackendMaxKeyRate',
    'CumReq',
    'PipesFree',
    'ZlibMemUsage',
    'Uptime_sec',
    'CompressBpsOut',
    'Maxsock',
    'MaxSslRate',
    'MaxSessRate',
]


class HAProxy(object):
    """Build a user-created :class:`HAProxy` object for HAProxy.

    This is the main class to interact with HAProxy and provides methods
    to create objects for managing frontends, backends and servers. It also
    provides an interface to interact with HAProxy as a way to
    retrieve settings/statistics but also change settings.

    ACLs and MAPs are also managed by :class:`HAProxy` class.

    :param socket_dir: a directory with HAProxy stats files.
    :type socket_dir: ``string``
    :param socket_file: absolute path of HAProxy stats file.
    :type socket_file: ``string``
    :param retry: number of times to retry to open a UNIX socket
      connection after a failure occurred, possible values

      - None => don't retry
      - 0 => retry indefinitely
      - 1..N => times to retry

    :type retry: ``integer`` or ``None``
    :param retry_interval: sleep time between the retries.
    :type retry_interval: ``integer``
    :param timeout: timeout for the connection
    :type timeout: ``float``
    :return: a user-created :class:`HAProxy` object.
    :rtype: :class:`HAProxy`
    """

    def __init__(self,
                 socket_dir=None,
                 socket_file=None,
                 retry=2,
                 retry_interval=2,
                 timeout=1,
                 ):

        self._hap_processes = []
        socket_files = []

        if socket_dir:
            if not os.path.exists(socket_dir):
                raise ValueError("socket directory does not exist "
                                 "{}".format(socket_dir))

            for _file in glob.glob(os.path.join(socket_dir, '*')):
                if is_unix_socket(_file) and connected_socket(_file, timeout):
                    socket_files.append(_file)
        elif (socket_file and is_unix_socket(socket_file) and
              connected_socket(socket_file, timeout)):
            socket_files.append(os.path.realpath(socket_file))
        else:
            raise ValueError("UNIX socket file was not set")

        if not socket_files:
            raise ValueError("No valid UNIX socket file was found, directory: "
                             "{} file: {}".format(socket_dir, socket_file))

        for so_file in socket_files:
            self._hap_processes.append(
                _HAProxyProcess(
                    socket_file=so_file,
                    retry=retry,
                    retry_interval=retry_interval,
                    timeout=timeout
                 )
            )

    @should_die
    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)

    @should_die
    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)

    @should_die
    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)

    @should_die
    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)

    @should_die
    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)

    @property
    def totalrequests(self):
        """Return total cumulative number of requests processed by all processes.

        :rtype: ``integer``

        .. note::
           This is the total number of requests that are processed by HAProxy.
           It counts requests for frontends and backends. Don't forget that
           a single client request passes HAProxy twice.

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.totalrequests
          457
        """
        return self.metric('CumReq')

    @property
    def processids(self):
        """Return the process IDs of all HAProxy processes.

        :rtype: ``list``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.processids
          [22029, 22028, 22027, 22026]
        """
        return [x.metric('Pid') for x in self._hap_processes]

    @should_die
    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)
        else:
            cmd = "del acl {} {}".format(acl, key)

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

        return check_command(results)

    @should_die
    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)
        else:
            cmd = "del map {} {}".format(mapid, key)

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

        return check_command(results)

    @should_die
    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)

    def frontends(self, name=None):
        """Build a list of :class:`Frontend <haproxyadmin.frontend.Frontend>`

        :param name: (optional) frontend name to look up.
        :type name: ``string``
        :return: list of :class:`Frontend <haproxyadmin.frontend.Frontend>`.
        :rtype: ``list``
        """
        return_list = []

        # store _Frontend objects for each frontend per haproxy process.
        # key: name of the frontend
        # value: a list of _Frontend objects
        frontends_across_hap_processes = {}

        # loop over all haproxy processes and get a list of frontend objects
        for haproxy in self._hap_processes:
            for frontend in haproxy.frontends(name):
                if frontend.name not in frontends_across_hap_processes:
                    frontends_across_hap_processes[frontend.name] = []
                frontends_across_hap_processes[frontend.name].append(frontend)

        # build the returned list
        for value in frontends_across_hap_processes.values():
            return_list.append(Frontend(value))

        return return_list

    def frontend(self, name):
        """Build a :class:`Frontend <haproxyadmin.frontend.Frontend>` object.

        :param name: frontend name to look up.
        :type name: ``string``
        :return: a :class:`Frontend <haproxyadmin.frontend.Frontend>` object
          for the frontend.
        :rtype: :class:`Frontend <haproxyadmin.frontend.Frontend>`
        :raises: :class::`ValueError` when frontend isn't found or more than 1
          frontend is found.
        """
        _frontend = self.frontends(name)
        if len(_frontend) == 1:
            return _frontend[0]
        elif len(_frontend) == 0:
            raise ValueError("Could not find frontend")
        else:
            raise ValueError("Found more than one frontend!")

    @should_die
    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

    @should_die
    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

    def info(self):
        """Dump info about haproxy stats on current process.

        :return: A list of ``dict`` for each process.
        :rtype: ``list``
        """
        return_list = []

        for haproxy in self._hap_processes:
            return_list.append(haproxy.proc_info())

        return return_list

    @property
    def maxconn(self):
        """Return the sum of configured maximum connection allowed for HAProxy.

        :rtype: ``integer``
        """
        return self.metric('Maxconn')

    def server(self, hostname, backend=None):
        """Build :class:`Server <haproxyadmin.server.Server> for a server.`
        objects for the given server.

        If ``backend`` specified then lookup is limited to that backend.

        .. note::
            If a server is member of more than 1 backend then muliple objects
            for the same server is returned.

        :param hostname: servername to look for.
        :type hostname: ``string``
        :param backend: (optional) backend name to look in.
        :type backend: ``string``
        :return: a list of :class:`Server <haproxyadmin.server.Server>`
          objects.
        :rtype: ``list``
        """
        ret = []
        for backend in self.backends(backend):
            try:
                ret.append(backend.server(hostname))
            except ValueError:
                # lookup for an nonexistent server in backend raise VauleError
                # catch and pass as we query all backends
                pass

        if not ret:
            raise ValueError("Could not find server")

        return ret

    def servers(self, backend=None):
        """Build :class:`Server <haproxyadmin.server.Server>` for each server.

        If ``backend`` specified then lookup is limited to that backend.

        :param backend: (optional) backend name.
        :type backend: ``string``
        :return: A list of :class:`Server <Server>` objects
        :rtype: ``list``.
        """
        return_list = []
        for backend in self.backends(backend):
            servers = backend.servers()
            return_list += servers

        return return_list

    def metric(self, name):
        """Return the value of a metric.

        Performs a calculation on the metric across all HAProxy processes.
        The type of calculation is either sum or avg and defined in
        :data:`haproxyadmin.utils.METRICS_SUM` and
        :data:`haproxyadmin.utils.METRICS_AVG`.

        :param name: metric name to retrieve
        :type name: any of :data:`haproxyadmin.haproxy.HAPROXY_METRICS`
        :return: value of the metric
        :rtype: ``integer``
        :raise: ``ValueError`` when a given metric is not found
        """
        if name not in HAPROXY_METRICS:
            raise ValueError("{} is not valid metric".format(name))

        metrics = [x.metric(name) for x in self._hap_processes]
        metrics[:] = (converter(x) for x in metrics)
        metrics[:] = (x for x in metrics if x is not None)

        return calculate(name, metrics)

    def backends(self, name=None):
        """Build a list of :class:`Backend <haproxyadmin.backend.Backend>`

        :param name: (optional) backend name to look up.
        :type name: ``string``
        :return: list of :class:`Backend <haproxyadmin.backend.Backend>`.
        :rtype: ``list``
        """
        return_list = []

        # store _Backend objects for each backend per haproxy process.
        # key: name of the backend
        # value: a list of _Backend objects
        backends_across_hap_processes = {}

        # loop over all HAProxy processes and get a set of backends
        for hap_process in self._hap_processes:
            # Returns object _Backend
            for backend in hap_process.backends(name):
                if backend.name not in backends_across_hap_processes:
                    backends_across_hap_processes[backend.name] = []
                backends_across_hap_processes[backend.name].append(backend)

        # build the returned list
        for backend_obj in backends_across_hap_processes.values():
            return_list.append(Backend(backend_obj))

        return return_list

    def backend(self, name):
        """Build a :class:`Backend <haproxyadmin.backend.Backend>` object.

        :param name: backend name to look up.
        :type name: ``string``
        :raises: :class::`ValueError` when backend isn't found or more than 1
          backend is found.
        """
        _backend = self.backends(name)
        if len(_backend) == 1:
            return _backend[0]
        elif len(_backend) == 0:
            raise ValueError("Could not find backend")
        else:
            raise ValueError("Found more than one backend!")

    @property
    def ratelimitconn(self):
        """Return the process-wide connection rate limit."""
        return self.metric('ConnRateLimit')

    @property
    def ratelimitsess(self):
        """Return the process-wide session rate limit."""
        return self.metric('SessRateLimit')

    @property
    def ratelimitsslsess(self):
        """Return the process-wide ssl session rate limit."""
        return self.metric('SslRateLimit')

    @property
    def requests(self):
        """Return total requests processed by all frontends.

        :rtype: ``integer``

        Usage::

          >>> from haproxyadmin import haproxy
          >>> hap = haproxy.HAProxy(socket_dir='/run/haproxy')
          >>> hap.requests
          457
        """
        return sum([x.requests for x in self.frontends()])

    @should_die
    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)
        else:
            cmd = "set map {} {} {}".format(mapid, key, value)

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

        return check_command(results)

    @should_die
    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)

    @should_die
    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)

    @should_die
    def setratelimitconn(self, value):
        """Set process-wide connection rate limit.

        :param value: rate connection 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 connections global {}".format(value)

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

        return check_command(results)

    @should_die
    def setratelimitsess(self, value):
        """Set process-wide session rate limit.

        :param value: rate 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 sessions global {}".format(value)

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

        return check_command(results)

    @should_die
    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)

    @should_die
    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

    @should_die
    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

    @property
    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]

    @property
    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)

    @property
    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)

    @property
    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]

    @property
    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)

    @property
    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)