hatop-0.7.7/ 0000775 0000000 0000000 00000000000 11452621517 0012644 5 ustar 00root root 0000000 0000000 hatop-0.7.7/.gitignore 0000664 0000000 0000000 00000000043 11452621517 0014631 0 ustar 00root root 0000000 0000000 *.py[co]
*.swp
*.tmp
*.~
.DS_Store
hatop-0.7.7/CHANGES 0000664 0000000 0000000 00000003773 11452621517 0013651 0 ustar 00root root 0000000 0000000 *********
Changelog
*********
This is a brief overview of the changes introduced by each version.
For the full changelog refer to the
`Git version history `_.
HATop 0.7
=========
This is the first public series after reaching a feature complete state.
HATop 0.7.7
-----------
:Date: Oct 05, 2010
- Feature: Display hotkey footer when pressing ENTER on selected service.
- Feature: Use string identifier ("pxname/svname") instead of numerical
identifier ("#iid/#sid") for hotkey actions.
- Bugfix: Display cursor and focus input if started in CLI mode.
- Bugfix: Reload stat data if number of proxies or services has changed.
- Bugfix: Prevent infinite size sync if screen size is larger than supported.
(Jérémy Bonnet)
- Docs: Add notes to INSTALL for the man page. (James Briggs)
- Docs: Fix hatop(1) man page and document the new hotkey footer.
HATop 0.7.6
-----------
:Date: Aug 20, 2010
- Bugfix: Support terminals lacking different cursor visibilities.
(Matt Behrens)
- Bugfix: Handle empty or incomplete info and stat data.
- Bugfix: Handle unknown proxy names with the -p / --proxy filter options.
- Docs: Add initial hatop(1) man page
HATop 0.7.5
-----------
:Date: Aug 18, 2010
- Bugfix: Pressing ENTER on the embedded CLI could result in display
corruption. (Cyril Bonté)
- Docs: Add common packaging files CHANGES and INSTALL
- Docs: Add keybind reference in KEYBINDS
HATop 0.7.4
-----------
:Date: Aug 16, 2010
- Bugfix: Fix the expected stat CSV format. (Jim Riggs)
HATop 0.7.3
-----------
:Date: Aug 16, 2010
- Bugfix: Restore compatibility with Python 2.4 and 2.5.
HATop 0.7.2
-----------
:Date: Aug 16, 2010
- Bugfix: Handle socket connections to incompatible HAProxy versions.
HATop 0.7.1
-----------
:Date: Aug 16, 2010
- Bugfix: Prevent timeout changes to the internal interactive session used to
query for stats.
HATop 0.7.0
-----------
:Date: Aug 15, 2010
- The first public and feature complete version.
.. vim: tw=78
hatop-0.7.7/HACKING 0000664 0000000 0000000 00000007770 11452621517 0013646 0 ustar 00root root 0000000 0000000 # Copyright (C) 2010 John Feuerstein
# HATop hacking...
Development: http://labs.feurix.org/admin/hatop/
Git: git clone git://labs.feurix.org/feurix/admin/hatop.git
*** Screen coordinates:
xmin (0) xmax (>=78)
| |
| | stat
ymin ----+------------------ header ---------------------| idx
(0) | |
| | 0
| info display | [..]
| | 42
| | 43
hpos ----|------------------ columns --------------------| 44
| | 45
= smin ====|= 0.- cmin ===================================|==== 46 = vmin
^ | 1 \ | 47
| | 2 | | 48
| | 3 | | 49
| | 4 |-> screen lines | 50
|-> span | 5 | | 51
| | 6 | | 52
| | 7 | stat display | 53
| | 8 | | 54
| | 9 | | 55
| | 10 | | 56
| cpos ----|- 11 | ------------ cursor --------------------|---- 57 - vpos
| | 12 | | 58
| | 13 | | 59
| | 14 | | 60
| | 15 / | 61
= smax ====|= 16'- cmax ===================================|==== 62 - vmax
| | 63
ymax ----+------------------- footer --------------------' [..]
(>=20)
Smin/max = Screen position
Cmin/max/pos = Curser position
Vmin/max/pos = Virtual position
Dynamic positions:
smin = hpos + 2
smax = ymax - 2
cmax = smax - smin (or last stat slice from vmin to end of list)
vpos = vmin + cpos
vmax = vmin + cmax
span = smax - smin
- stat lines represent the whole set of parsed service stats
- screen lines represent a subset of stat lines which are on screen
*** ScreenCLI INPUT coordinates:
screen.xmin screen.xmax
. .
. .
| |
| |
| |<---------------- ispan ------------------>| |
| | | |
|imin ipos imax|
| | | | |
| [*****************|*************************]-----> input line
| | | | | (at screen.smax)
+-|-----------------|-------------------------|-+
| | |
[..., ..., .|., ..., ..., ...,|..., ..., ..., ..., ..., |.., ..., ...] ibuf
| | | | |
| ibmin ibpos ibmax |
| |
|<--------------------------- iblen -------------------------------->|
Imin/max/pos = Input position (*on screen*)
IBmin/pos/max = Input buffer position
hatop-0.7.7/INSTALL 0000664 0000000 0000000 00000002232 11452621517 0013674 0 ustar 00root root 0000000 0000000 ************
Installation
************
HATop is written as a single executable python script file called ``hatop``.
This allows easy distribution and installation.
:Package maintainers:
Please use "hatop" for the final package and executable name.
This allows users on different platforms to find it easily.
Requirements
============
**HATop is written in pure Python and has no external dependencies!**
* `Python 2.4 `_ or later (no Python 3 support planned yet)
* `HAProxy 1.4 `_ or later
Installation
============
The installation is simple::
$ install -m 755 bin/hatop /usr/local/bin
$ install -m 644 man/hatop.1 /usr/local/share/man/man1
$ gzip /usr/local/share/man/man1/hatop.1
Permissions
===========
HATop itself can be used by any system user.
The permission to connect to a given HAProxy instance is controlled
by the file permission of the unix socket file.
HATop needs ``read`` and ``write`` access (``chmod +rw``) on the socket file.
The initial socket file permissions can be configured in haproxy.conf using
the ``user``, ``group`` and ``mode`` parameters of the ``stats socket`` option.
hatop-0.7.7/KEYBINDS 0000664 0000000 0000000 00000003230 11452621517 0013775 0 ustar 00root root 0000000 0000000 *****************
Keybind Reference
*****************
Global keybinds
===============
::
Key Action
Hh? Display this help screen
CTRL-C / Qq Quit
TAB Cycle mode forwards
SHIFT-TAB Cycle mode backwards
ALT-n / ESC-n Switch to mode n, where n is the numeric mode id
ESC-ESC Jump to previous mode
ENTER Display hotkey menu for selected service
SPACE Copy and paste selected service identifier to the CLI
You can scroll the stat views using UP / DOWN / PGUP / PGDOWN / HOME / END.
Hotkeys for common administrative actions
=========================================
::
Hotkey Action
F4 Restore initial server weight
F5 Decrease server weight: - 10
F6 Decrease server weight: - 1
F7 Increase server weight: + 1
F8 Increase server weight: + 10
F9 Enable server (return from maintenance mode)
F10 Disable server (put into maintenance mode)
Hotkey actions and server responses are logged on the CLI viewport.
Keybinds for the command line interface
=======================================
::
Key Action
ALT-n / ESC-n escape the shell and display given viewport
ENTER execute cmdline or display marker if input empty
UP / DOWN scroll input history up or down
LEFT / RIGHT move input cursor one character to the left or right
HOME / END move input cursor to the beginning or end of line
BACKSPACE / DEL delete one character backwards or forwards
PGUP / PGDOWN scroll output history up or down
hatop-0.7.7/LICENSE 0000664 0000000 0000000 00000104513 11452621517 0013655 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
hatop-0.7.7/README 0000664 0000000 0000000 00000016503 11452621517 0013531 0 ustar 00root root 0000000 0000000 *************
Documentation
*************
*Interactive ncurses client for the HAProxy unix socket*
Author: John Feuerstein
License: GPLv3
Project URL: http://feurix.org/projects/hatop/
Mirror URL: http://code.google.com/p/hatop/
Development URL: http://labs.feurix.org/admin/hatop/
What is HATop?
==============
HATop's appearance is similar to top(1). It supports various modes
for detailed statistics of all configured proxies and services in near
realtime. In addition, it features an interactive CLI for the haproxy
unix socket. This allows administrators to control the given haproxy
instance (change server weight, put servers into maintenance mode, ...)
directly out of hatop and monitor the results immediately.
*It is important to understand that when multiple haproxy processes are started
on the same socket, any process may pick up the request and thus hatop will
output stats owned solely by that process. The current haproxy-internal
process id is displayed top right.*
Installation
============
See ``INSTALL`` or refer to :ref:`install`
Command line options
====================
Invoking hatop without options or with ``-h / --help`` results in:
::
$ hatop --help
Usage: hatop -s SOCKET [OPTIONS]...
Options:
--version show program's version number and exit
-h, --help show this help message and exit
Mandatory:
-s SOCKET, --unix-socket=SOCKET
path to the haproxy unix socket
Optional:
-i INTERVAL, --update-interval=INTERVAL
update interval in seconds (1-30, default: 3)
-m MODE, --mode=MODE
start in specific mode (1-5, default: 1)
-n, --read-only disable the cli and query for stats only
Filters:
Note: All filter options may be given multiple times.
-f FILTER, --filter=FILTER
stat filter in format ""
-p PROXY, --proxy=PROXY
proxy filter in format ""
Display mode reference
======================
See also: :ref:`screenshots`
::
ID Mode Description
1 STATUS The default mode with health, session and queue statistics
2 TRAFFIC Display connection and request rates as well as traffic stats
3 HTTP Display various statistical information related to HTTP
4 ERRORS Display health info, various error counters and downtimes
5 CLI Display embedded command line client for the unix socket
Keybind reference
=================
See also: :ref:`keybinds`
::
Key Action
Hh? Display this help screen
CTRL-C / Qq Quit
TAB Cycle mode forwards
SHIFT-TAB Cycle mode backwards
ALT-n / ESC-n Switch to mode n, where n is the numeric mode id
ESC-ESC Jump to previous mode
ENTER Display hotkey menu for selected service
SPACE Copy and paste selected service identifier to the CLI
You can scroll the stat views using ``UP / DOWN / PGUP / PGDOWN / HOME / END``.
The reverse colored cursor line is used to select a given service instance.
An unique identifier ``[#/<#sid>]`` of the selected
service is displayed bottom right.
You can hit ``SPACE`` to copy and paste the identifier in string format
``pxname/svname`` to the CLI for easy re-use with some commands.
For example:
1. Open the CLI
2. Type "disable server "
3. Switch back to some stat view using TAB / SHIFT-TAB
4. Select the server instance using UP / DOWN
5. Hit SPACE
The result is this command line::
> disable server /
Hotkeys for common administrative actions
-----------------------------------------
::
Hotkey Action
F4 Restore initial server weight
F5 Decrease server weight: - 10
F6 Decrease server weight: - 1
F7 Increase server weight: + 1
F8 Increase server weight: + 10
F9 Enable server (return from maintenance mode)
F10 Disable server (put into maintenance mode)
Hotkey actions and server responses are logged on the CLI viewport.
You can scroll the output on the CLI view using ``PGUP / PGDOWN``.
A brief keybind reference is logged there directly after startup...
Header reference
================
See also: :ref:`screenshots`
::
Node configured name of the haproxy node
Uptime runtime since haproxy was initially started
Pipes pipes are currently used for kernel-based tcp slicing
Procs number of haproxy processes
Tasks number of actice process tasks
Queue number of queued process tasks (run queue)
Proxies number of configured proxies
Services number of configured services
In multiple modes
-----------------
::
NAME name of the proxy and his services
W configured weight of the service
STATUS service status (UP/DOWN/NOLB/MAINT/MAINT(via)...)
CHECK status of last health check (see status reference below)
In STATUS mode
--------------
::
ACT server is active (server), number of active servers (backend)
BCK server is backup (server), number of backup servers (backend)
QCUR current queued requests
QMAX max queued requests
SCUR current sessions
SMAX max sessions
SLIM sessions limit
STOT total sessions
In TRAFFIC mode
---------------
::
LBTOT total number of times a server was selected
RATE number of sessions per second over last elapsed second
RLIM limit on new sessions per second
RMAX max number of new sessions per second
BIN bytes in (IEEE 1541-2002)
BOUT bytes out (IEEE 1541-2002)
In HTTP mode
------------
::
RATE HTTP requests per second over last elapsed second
RMAX max number of HTTP requests per second observed
RTOT total number of HTTP requests received
1xx number of HTTP responses with 1xx code
2xx number of HTTP responses with 2xx code
3xx number of HTTP responses with 3xx code
4xx number of HTTP responses with 4xx code
5xx number of HTTP responses with 5xx code
?xx number of HTTP responses with other codes (protocol error)
In ERRORS mode
--------------
::
CF number of failed checks
CD number of UP->DOWN transitions
CL last status change
ECONN connection errors
EREQ request errors
ERSP response errors
DREQ denied requests
DRSP denied responses
DOWN total downtime
Health check status reference
=============================
::
UNK unknown
INI initializing
SOCKERR socket error
L4OK check passed on layer 4, no upper layers testing enabled
L4TMOUT layer 1-4 timeout
L4CON layer 1-4 connection problem, for example
"Connection refused" (tcp rst) or "No route to host" (icmp)
L6OK check passed on layer 6
L6TOUT layer 6 (SSL) timeout
L6RSP layer 6 invalid response - protocol error
L7OK check passed on layer 7
L7OKC check conditionally passed on layer 7, for example 404 with
disable-on-404
L7TOUT layer 7 (HTTP/SMTP) timeout
L7RSP layer 7 invalid response - protocol error
L7STS layer 7 response error, for example HTTP 5xx
hatop-0.7.7/bin/ 0000775 0000000 0000000 00000000000 11452621517 0013414 5 ustar 00root root 0000000 0000000 hatop-0.7.7/bin/hatop 0000775 0000000 0000000 00000216423 11452621517 0014465 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
#
# Copyright (C) 2010 John Feuerstein
#
# Project URL: http://feurix.org/projects/hatop/
# Mirror URL: http://code.google.com/p/hatop/
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
'''\
HATop is an interactive ncurses client for the HAProxy unix socket
==================================================================
HATop's appearance is similar to top(1). It supports various modes
for detailed statistics of all configured proxies and services in near
realtime. In addition, it features an interactive CLI for the haproxy
unix socket. This allows administrators to control the given haproxy
instance (change server weight, put servers into maintenance mode, ...)
directly out of hatop and monitor the results immediately.
Note: It is important to understand that when multiple haproxy processes
are started on the same socket, any process may pick up the request
and thus hatop will output stats owned solely by that process.
The current haproxy-internal process id is displayed top right.
Display mode reference:
ID Mode Description
1 STATUS The default mode with health, session and queue statistics
2 TRAFFIC Display connection and request rates as well as traffic stats
3 HTTP Display various statistical information related to HTTP
4 ERRORS Display health info, various error counters and downtimes
5 CLI Display embedded command line client for the unix socket
Keybind reference:
Key Action
Hh? Display this help screen
CTRL-C / Qq Quit
TAB Cycle mode forwards
SHIFT-TAB Cycle mode backwards
ALT-n / ESC-n Switch to mode n, where n is the numeric mode id
ESC-ESC Jump to previous mode
ENTER Display hotkey menu for selected service
SPACE Copy and paste selected service identifier to the CLI
You can scroll the stat views using UP / DOWN / PGUP / PGDOWN / HOME / END.
The reverse colored cursor line is used to select a given service instance.
An unique identifier [#/<#sid>] of the selected service is displayed
bottom right.
You can hit SPACE to copy and paste the identifier in string format
"pxname/svname" to the CLI for easy re-use with some commands.
For example:
1) Open the CLI
2) Type "disable server "
3) Switch back to some stat view using TAB / SHIFT-TAB
4) Select the server instance using UP / DOWN
5) Hit SPACE
The result is this command line:
> disable server /
Some common administrative actions have hotkeys:
Hotkey Action
F4 Restore initial server weight
F5 Decrease server weight: - 10
F6 Decrease server weight: - 1
F7 Increase server weight: + 1
F8 Increase server weight: + 10
F9 Enable server (return from maintenance mode)
F10 Disable server (put into maintenance mode)
Hotkey actions and server responses are logged on the CLI viewport.
You can scroll the output on the CLI view using PGUP / PGDOWN.
A brief keybind reference is logged there directly after startup...
Header reference:
Node configured name of the haproxy node
Uptime runtime since haproxy was initially started
Pipes pipes are currently used for kernel-based tcp slicing
Procs number of haproxy processes
Tasks number of actice process tasks
Queue number of queued process tasks (run queue)
Proxies number of configured proxies
Services number of configured services
In multiple modes:
NAME name of the proxy and his services
W configured weight of the service
STATUS service status (UP/DOWN/NOLB/MAINT/MAINT(via)...)
CHECK status of last health check (see status reference below)
In STATUS mode:
ACT server is active (server), number of active servers (backend)
BCK server is backup (server), number of backup servers (backend)
QCUR current queued requests
QMAX max queued requests
SCUR current sessions
SMAX max sessions
SLIM sessions limit
STOT total sessions
In TRAFFIC mode:
LBTOT total number of times a server was selected
RATE number of sessions per second over last elapsed second
RLIM limit on new sessions per second
RMAX max number of new sessions per second
BIN bytes in (IEEE 1541-2002)
BOUT bytes out (IEEE 1541-2002)
In HTTP mode:
RATE HTTP requests per second over last elapsed second
RMAX max number of HTTP requests per second observed
RTOT total number of HTTP requests received
1xx number of HTTP responses with 1xx code
2xx number of HTTP responses with 2xx code
3xx number of HTTP responses with 3xx code
4xx number of HTTP responses with 4xx code
5xx number of HTTP responses with 5xx code
?xx number of HTTP responses with other codes (protocol error)
In ERRORS mode:
CF number of failed checks
CD number of UP->DOWN transitions
CL last status change
ECONN connection errors
EREQ request errors
ERSP response errors
DREQ denied requests
DRSP denied responses
DOWN total downtime
Health check status reference:
UNK unknown
INI initializing
SOCKERR socket error
L4OK check passed on layer 4, no upper layers testing enabled
L4TMOUT layer 1-4 timeout
L4CON layer 1-4 connection problem, for example
"Connection refused" (tcp rst) or "No route to host" (icmp)
L6OK check passed on layer 6
L6TOUT layer 6 (SSL) timeout
L6RSP layer 6 invalid response - protocol error
L7OK check passed on layer 7
L7OKC check conditionally passed on layer 7, for example 404 with
disable-on-404
L7TOUT layer 7 (HTTP/SMTP) timeout
L7RSP layer 7 invalid response - protocol error
L7STS layer 7 response error, for example HTTP 5xx
'''
__author__ = 'John Feuerstein '
__copyright__ = 'Copyright (C) 2010 %s' % __author__
__license__ = 'GNU GPLv3'
__version__ = '0.7.7'
import fcntl
import os
import re
import signal
import socket
import struct
import sys
import time
import tty
import curses
import curses.ascii
from socket import error as SocketError
from _curses import error as CursesError
from collections import deque
from textwrap import TextWrapper
# ------------------------------------------------------------------------- #
# GLOBALS #
# ------------------------------------------------------------------------- #
# Settings of interactive command session over the unix-socket
HAPROXY_CLI_BUFSIZE = 4096
HAPROXY_CLI_TIMEOUT = 60
HAPROXY_CLI_PROMPT = '> '
HAPROXY_CLI_CMD_SEP = ';'
HAPROXY_CLI_CMD_TIMEOUT = 1
HAPROXY_CLI_MAXLINES = 1000
# Settings of the embedded CLI
CLI_MAXLINES = 1000
CLI_MAXHIST = 100
CLI_INPUT_LIMIT = 200
CLI_INPUT_RE = re.compile('[a-zA-Z0-9_:\.\-\+; /#%]')
CLI_INPUT_DENY_CMD = ['prompt', 'set timeout cli', 'quit']
# Note: Only the last 3 lines are visible instantly on 80x25
CLI_HELP_TEXT = '''\
Welcome on the embedded interactive HAProxy shell!
Type `help' to get a command reference
'''
# Screen setup
SCREEN_XMIN = 78
SCREEN_YMIN = 20
SCREEN_XMAX = 200
SCREEN_YMAX = 100
SCREEN_HPOS = 11
HAPROXY_INFO_RE = {
'software_name': re.compile('^Name:\s*(?P\S+)'),
'software_version': re.compile('^Version:\s*(?P\S+)'),
'software_release': re.compile('^Release_date:\s*(?P\S+)'),
'nproc': re.compile('^Nbproc:\s*(?P\d+)'),
'procn': re.compile('^Process_num:\s*(?P\d+)'),
'pid': re.compile('^Pid:\s*(?P\d+)'),
'uptime': re.compile('^Uptime:\s*(?P[\S ]+)$'),
'maxconn': re.compile('^Maxconn:\s*(?P\d+)'),
'curconn': re.compile('^CurrConns:\s*(?P\d+)'),
'maxpipes': re.compile('^Maxpipes:\s*(?P\d+)'),
'curpipes': re.compile('^PipesUsed:\s*(?P\d+)'),
'tasks': re.compile('^Tasks:\s*(?P\d+)'),
'runqueue': re.compile('^Run_queue:\s*(?P\d+)'),
'node': re.compile('^node:\s*(?P\S+)'),
}
HAPROXY_STAT_MAX_SERVICES = 100
HAPROXY_STAT_LIMIT_WARNING = '''\
Warning: You have reached the stat parser limit! (%d)
Use --filter to parse specific service stats only.
''' % HAPROXY_STAT_MAX_SERVICES
HAPROXY_STAT_FILTER_RE = re.compile(
'^(?P-?\d+)\s+(?P-?\d+)\s+(?P-?\d+)$')
HAPROXY_STAT_PROXY_FILTER_RE = re.compile(
'^(?P[a-zA-Z0-9_:\.\-]+)$')
HAPROXY_STAT_COMMENT = '#'
HAPROXY_STAT_SEP = ','
HAPROXY_STAT_CSV = [
# Note: Fields must be listed in correct order, as described in:
# http://haproxy.1wt.eu/download/1.4/doc/configuration.txt [9.1]
# TYPE FIELD
(str, 'pxname'), # proxy name
(str, 'svname'), # service name (FRONTEND / BACKEND / name)
(int, 'qcur'), # current queued requests
(int, 'qmax'), # max queued requests
(int, 'scur'), # current sessions
(int, 'smax'), # max sessions
(int, 'slim'), # sessions limit
(int, 'stot'), # total sessions
(int, 'bin'), # bytes in
(int, 'bout'), # bytes out
(int, 'dreq'), # denied requests
(int, 'dresp'), # denied responses
(int, 'ereq'), # request errors
(int, 'econ'), # connection errors
(int, 'eresp'), # response errors (among which srv_abrt)
(int, 'wretr'), # retries (warning)
(int, 'wredis'), # redispatches (warning)
(str, 'status'), # status (UP/DOWN/NOLB/MAINT/MAINT(via)...)
(int, 'weight'), # server weight (server), total weight (backend)
(int, 'act'), # server is active (server),
# number of active servers (backend)
(int, 'bck'), # server is backup (server),
# number of backup servers (backend)
(int, 'chkfail'), # number of failed checks
(int, 'chkdown'), # number of UP->DOWN transitions
(int, 'lastchg'), # last status change (in seconds)
(int, 'downtime'), # total downtime (in seconds)
(int, 'qlimit'), # queue limit
(int, 'pid'), # process id
(int, 'iid'), # unique proxy id
(int, 'sid'), # service id (unique inside a proxy)
(int, 'throttle'), # warm up status
(int, 'lbtot'), # total number of times a server was selected
(str, 'tracked'), # id of proxy/server if tracking is enabled
(int, 'type'), # (0=frontend, 1=backend, 2=server, 3=socket)
(int, 'rate'), # number of sessions per second
# over the last elapsed second
(int, 'rate_lim'), # limit on new sessions per second
(int, 'rate_max'), # max number of new sessions per second
(str, 'check_status'), # status of last health check
(int, 'check_code'), # layer5-7 code, if available
(int, 'check_duration'), # time in ms took to finish last health check
(int, 'hrsp_1xx'), # http responses with 1xx code
(int, 'hrsp_2xx'), # http responses with 2xx code
(int, 'hrsp_3xx'), # http responses with 3xx code
(int, 'hrsp_4xx'), # http responses with 4xx code
(int, 'hrsp_5xx'), # http responses with 5xx code
(int, 'hrsp_other'), # http responses with other codes (protocol error)
(str, 'hanafail'), # failed health checks details
(int, 'req_rate'), # HTTP requests per second
(int, 'req_rate_max'), # max number of HTTP requests per second
(int, 'req_tot'), # total number of HTTP requests received
(int, 'cli_abrt'), # number of data transfers aborted by client
(int, 'srv_abrt'), # number of data transfers aborted by server
]
HAPROXY_STAT_NUMFIELDS = len(HAPROXY_STAT_CSV)
HAPROXY_STAT_CSV = [(k, v) for k, v in enumerate(HAPROXY_STAT_CSV)]
# All big numeric values on the screen are prefixed using the metric prefix
# set, while everything byte related is prefixed using binary prefixes.
# Note: If a non-byte numeric value fits into the field, we skip prefixing.
PREFIX_BINARY = {
1024: 'K',
1024**2: 'M',
}
PREFIX_METRIC = {
1000: 'k',
1000**2: 'M',
1000**3: 'G',
}
PREFIX_TIME = {
60: 'm',
60*60: 'h',
60*60*24:'d',
}
# ------------------------------------------------------------------------- #
# CLASS DEFINITIONS #
# ------------------------------------------------------------------------- #
# Use bounded length deque if available (Python 2.6+)
try:
deque(maxlen=0)
class RingBuffer(deque):
def __init__(self, maxlen):
assert maxlen > 0
deque.__init__(self, maxlen=maxlen)
except TypeError:
class RingBuffer(deque):
def __init__(self, maxlen):
assert maxlen > 0
deque.__init__(self)
self.maxlen = maxlen
def append(self, item):
if len(self) == self.maxlen:
self.popleft()
deque.append(self, item)
def appendleft(self, item):
if len(self) == self.maxlen:
self.popright()
deque.appendleft(self, item)
def extend(self, iterable):
for item in iterable:
self.append(item)
def extendleft(self, iterable):
for item in iterable:
self.appendleft(item)
class Socket:
def __init__(self, path, readonly=False):
self.path = path
self.ro = readonly
self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
def _recv(self):
# socket.recv() wrapper raising SocketError if we receive
# EOF before seeing the interactive socket prompt.
data = self._socket.recv(HAPROXY_CLI_BUFSIZE)
if not data:
raise SocketError('error while waiting for prompt')
return data
def connect(self):
# Initialize socket connection
self._socket.connect(self.path)
self._socket.settimeout(HAPROXY_CLI_CMD_TIMEOUT)
# Enter the interactive socket mode. This requires HAProxy 1.4+ and
# allows us to error out early if connected to an older version.
try:
self.send('prompt')
self.wait()
self.send('set timeout cli %d' % HAPROXY_CLI_TIMEOUT)
self.wait()
except SocketError:
raise SocketError('error while initializing interactive mode')
def close(self):
try:
self.send('quit')
except:
pass
try:
self._socket.close()
except:
pass
def send(self, cmdline):
self._socket.sendall('%s\n' % cmdline)
def wait(self):
# Wait for the prompt and discard data.
rbuf = ''
while not rbuf.endswith(HAPROXY_CLI_PROMPT):
data = self._recv()
rbuf = rbuf[-(len(HAPROXY_CLI_PROMPT)-1):] + data
def recv(self):
# Receive lines until HAPROXY_CLI_MAXLINES or the prompt is reached.
# If the prompt was still not found, discard data and wait for it.
linecount = 0
rbuf = ''
while not rbuf.endswith(HAPROXY_CLI_PROMPT):
if linecount == HAPROXY_CLI_MAXLINES:
data = self._recv()
rbuf = rbuf[-(len(HAPROXY_CLI_PROMPT)-1):] + data
continue
data = self._recv()
rbuf += data
while linecount < HAPROXY_CLI_MAXLINES and '\n' in rbuf:
line, rbuf = rbuf.split('\n', 1)
linecount += 1
yield line
class SocketData:
def __init__(self, socket):
self.socket = socket
self.pxcount = 0
self.svcount = 0
self.info = {}
self.stat = {}
self._filters = set()
def register_stat_filter(self, stat_filter):
# Validate and register filters
stat_filter_set = set(stat_filter)
for filter in stat_filter_set:
match = HAPROXY_STAT_FILTER_RE.match(filter)
if not match:
raise ValueError('invalid stat filter: %s' % filter)
self._filters.add((
int(match.group('iid'), 10),
int(match.group('type'), 10),
int(match.group('sid'), 10),
))
def register_proxy_filter(self, proxy_filter):
# Validate filters
proxy_filter_set = set(proxy_filter)
for filter in proxy_filter_set:
if not HAPROXY_STAT_PROXY_FILTER_RE.match(filter):
raise ValueError('invalid proxy filter: %s' % filter)
# Convert proxy filters into more efficient stat filters
self.socket.send('show stat')
pxstat, pxcount, svcount = parse_stat(self.socket.recv())
proxy_iid_map = {} # {pxname: iid, ...}
for pxname in proxy_filter_set:
for iid in pxstat:
for sid in pxstat[iid]:
if pxstat[iid][sid]['pxname'] == pxname:
proxy_iid_map[pxname] = iid
break
if pxname in proxy_iid_map:
break
for pxname in proxy_filter_set:
if not pxname in proxy_iid_map:
raise RuntimeError('proxy not found: %s' % pxname)
# Register filters
for iid in proxy_iid_map.itervalues():
self._filters.add((iid, -1, -1))
def update_info(self):
self.socket.send('show info')
iterable = self.socket.recv()
self.info = parse_info(iterable)
def update_stat(self):
# Store current data
pxcount_old = self.pxcount
svcount_old = self.svcount
stat_old = self.stat
# Reset current data
self.pxcount = 0
self.svcount = 0
self.stat = {}
if self._filters:
for filter in self._filters:
self.socket.send('show stat %d %d %d' % filter)
filter_stat, filter_pxcount, filter_svcount = \
parse_stat(self.socket.recv())
if filter_pxcount == 0:
raise RuntimeError('stale stat filter: %d %d %d' % filter)
self.pxcount += filter_pxcount
self.svcount += filter_svcount
self.stat.update(filter_stat)
else:
self.socket.send('show stat')
self.stat, self.pxcount, self.svcount = \
parse_stat(self.socket.recv())
if self.pxcount == 0:
raise RuntimeWarning('no stat data available')
# Warn if the HAProxy configuration has changed on-the-fly
pxdiff = 0
svdiff = 0
if self.pxcount < pxcount_old:
pxdiff -= pxcount_old - self.pxcount
if pxcount_old > 0 and self.pxcount > pxcount_old:
pxdiff += self.pxcount - pxcount_old
if self.svcount < svcount_old:
svdiff -= svcount_old - self.svcount
if svcount_old > 0 and self.svcount > svcount_old:
svdiff += self.svcount - svcount_old
if pxdiff != 0 or svdiff != 0:
raise RuntimeWarning(
'config changed: proxy %+d, service %+d '
'(reloading...)' % (pxdiff, svdiff))
class ScreenCLI:
def __init__(self, screen):
self.screen = screen
# Output
self.obuf = RingBuffer(CLI_MAXLINES)
self.ypos = 0
self.wrapper = TextWrapper()
self.screenlines = []
# Input
self.ihist = RingBuffer(CLI_MAXHIST)
self.ibuf = []
self.ibpos = 0
self.ibmin = 0
# INPUT
@property
def imin(self):
return self.screen.xmin + 2
@property
def imax(self):
return self.screen.xmax - 4
@property
def ispan(self):
return self.imax - self.imin
@property
def ipos(self):
return self.ibpos - self.ibmin
@property
def ibmax(self):
return self.ibmin + self.ispan
@property
def iblen(self):
return len(self.ibuf)
@property
def cmdline(self):
return ''.join(self.ibuf)
# OUTPUT
@property
def ospan(self):
return self.screen.span - 1
def setup(self):
self.ipad = curses.newpad(1, SCREEN_XMAX) # input
self.opad = curses.newpad(SCREEN_YMAX, SCREEN_XMAX) # output
# Display initial help text...
self.obuf.extend(CLI_HELP_TEXT.split('\n'))
self.update_screenlines()
def start(self):
try:
curses.curs_set(1)
except CursesError:
pass
self.draw_output()
self.draw_input()
def stop(self):
try:
curses.curs_set(0)
except CursesError:
pass
def update_screenlines(self):
self.wrapper.width = self.screen.xmax
self.screenlines = []
for line in self.obuf:
if len(line) > self.wrapper.width:
self.screenlines.extend(self.wrapper.wrap(line))
else:
self.screenlines.append(line)
self.ypos = len(self.screenlines)
def reset_input(self):
self.ibuf = []
self.ibpos = 0
self.ibmin = 0
def refresh_input(self, sync=False):
if sync:
refresh = self.ipad.refresh
else:
refresh = self.ipad.noutrefresh
refresh(0, 0,
self.screen.smax, self.screen.xmin,
self.screen.smax, self.screen.xmax - 1)
def refresh_output(self, sync=False):
if sync:
refresh = self.opad.refresh
else:
refresh = self.opad.noutrefresh
refresh(0, 0,
self.screen.smin, self.screen.xmin,
self.screen.smax - 2, self.screen.xmax - 1)
def draw_input(self):
self.ipad.clear()
self.ipad.addstr(0, 0, '> ', curses.A_BOLD)
self.ipad.addstr(0, 2, ''.join(self.ibuf[self.ibmin:self.ibmax]))
# Mark input lines longer than the visible input span
if self.ibmin > 0:
self.ipad.addstr(0, self.imin - 1, '<')
if self.iblen > self.ibmax:
self.ipad.addstr(0, self.imax, '>')
self.ipad.move(0, self.imin + self.ipos)
def draw_output(self):
self.opad.clear()
vmin = max(0, self.ypos - self.ospan)
vmax = vmin + self.ospan
lines = self.screenlines[vmin:vmax]
self.opad.addstr(0, 0, '\n'.join(lines))
# INPUT
def prev(self):
if len(self.ihist) == 0:
return
if len(self.ibuf) == 0:
self.ibuf = list(self.ihist[-1])
self.mvend()
return
if self.ibuf != self.ihist[-1]:
self.ihist.append(self.ibuf)
self.ihist.rotate(1)
self.ibuf = list(self.ihist[-1])
self.mvend()
def next(self):
if len(self.ihist) == 0:
return
self.ihist.rotate(-1)
self.ibuf = list(self.ihist[-1])
self.mvend()
def puts(self, s):
s = list(s)
if len(self.ibuf) + len(s) >= CLI_INPUT_LIMIT:
return
for c in s:
if not CLI_INPUT_RE.match(c):
return
if self.ibpos < self.iblen:
self.ibuf = self.ibuf[:self.ibpos] + s + self.ibuf[self.ibpos:]
else:
self.ibuf.extend(s)
self.mvc(len(s))
return True
def putc(self, c):
if len(self.ibuf) == CLI_INPUT_LIMIT:
return
if not CLI_INPUT_RE.match(c):
return
if self.ibpos < self.iblen:
self.ibuf.insert(self.ibpos, c)
else:
self.ibuf.append(c)
self.mvc(1)
def delc(self, n):
if n == 0 or self.iblen == 0:
return
# Delete LEFT
elif n < 0 and self.ibpos >= 1:
self.ibuf.pop(self.ibpos - 1)
self.mvc(-1)
# Delete RIGHT
elif n > 0 and self.ibpos < self.iblen:
self.ibuf.pop(self.ibpos)
self.draw_input()
self.refresh_input(sync=True)
def mvhome(self):
self.ibmin = 0
self.ibpos = 0
self.draw_input()
self.refresh_input(sync=True)
def mvend(self):
self.ibmin = max(0, self.iblen - self.ispan)
self.ibpos = self.iblen
self.draw_input()
self.refresh_input(sync=True)
def mvc(self, n):
if n == 0:
return
# Move LEFT
if n < 0:
self.ibpos = max(0, self.ibpos + n)
if self.ibpos < self.ibmin:
self.ibmin = self.ibpos
# Move RIGHT
elif n > 0:
self.ibpos = min(self.iblen, self.ibpos + n)
if self.ibpos > self.ibmax:
self.ibmin += n
self.draw_input()
self.refresh_input(sync=True)
# OUTPUT
def mvo(self, n):
if n == 0:
return
# Move UP
if n < 0 and self.ypos > self.ospan:
self.ypos = max(self.ospan, self.ypos + n)
# Move DOWN
elif n > 0 and self.ypos < len(self.screenlines):
self.ypos = min(len(self.screenlines), self.ypos + n)
self.draw_output()
self.refresh_output(sync=True)
def execute(self):
# Nothing to do... print marker line instead.
if self.iblen == 0:
self.obuf.append('- %s %s' % (time.ctime(), '-' * 50))
self.obuf.append('')
self.update_screenlines()
self.draw_output()
self.refresh_output(sync=True)
self.refresh_input(sync=True)
return
# Validate each command on the command line
cmds = [cmd.strip() for cmd in
self.cmdline.split(HAPROXY_CLI_CMD_SEP)]
for pattern in CLI_INPUT_DENY_CMD:
for cmd in cmds:
if re.match(r'^\s*%s(?:\s|$)' % pattern, cmd):
self.obuf.append('* command not allowed: %s' % cmd)
self.obuf.append('')
self.update_screenlines()
self.draw_output()
self.refresh_output(sync=True)
self.refresh_input(sync=True)
return
self.execute_cmdline(self.cmdline)
self.draw_output()
self.refresh_output(sync=True)
self.ihist.append(self.ibuf)
self.reset_input()
self.draw_input()
self.refresh_input(sync=True)
def execute_cmdline(self, cmdline):
self.obuf.append('* %s' % time.ctime())
self.obuf.append('> %s' % cmdline)
self.screen.data.socket.send(cmdline)
self.obuf.extend(self.screen.data.socket.recv())
self.update_screenlines()
class Screen:
def __init__(self, data, mid=1):
self.data = data
self.modes = SCREEN_MODES
self.sb_conn = StatusBar()
self.sb_pipe = StatusBar()
self.lines = []
self.screen = None
self.xmin = 0
self.xmax = SCREEN_XMIN
self.ymin = 0
self.ymax = SCREEN_YMIN
self.vmin = 0
self.cmin = 0
self.cpos = 0
self.hpos = SCREEN_HPOS
self.help = ScreenHelp(self)
self.cli = ScreenCLI(self)
self._pmid = mid # previous mode id
self._cmid = mid # current mode id
self._mode = self.modes[mid]
# Display state
self.active = False
# Assume a dumb TTY, setup() will detect smart features.
self.dumbtty = True
# Toggled by the SIGWINCH handler...
# Note: Defaults to true to force the initial size sync.
self._resized = True
# Display given exceptions on screen
self.exceptions = []
# Show cursor line?
self.cursor = True
# Show hotkeys?
self.hotkeys = False
def _sigwinchhandler(self, signum, frame):
self._resized = True
@property
def resized(self):
if self.dumbtty:
ymax, xmax = self.getmaxyx()
return ymax != self.ymax or xmax != self.xmax
else:
return self._resized
@property
def mid(self):
return self._cmid
@property
def mode(self):
return self._mode
@property
def ncols(self):
return self.xmax - self.xmin
@property
def smin(self):
return self.hpos + 2
@property
def smax(self):
return self.ymax - 3
@property
def span(self):
return self.smax - self.smin
@property
def cmax(self):
return min(self.span, len(self.lines) - 1)
@property
def cstat(self):
return self.lines[self.vpos].stat
@property
def vpos(self):
return self.vmin + self.cpos
@property
def vmax(self):
return min(self.vmin + self.span, len(self.lines) - 1)
@property
def screenlines(self):
return enumerate(self.lines[self.vmin:self.vmax + 1])
# Proxies
def getch(self, *args, **kwargs):
return self.screen.getch(*args, **kwargs)
def hline(self, *args, **kwargs):
return self.screen.hline(*args, **kwargs)
def addstr(self, *args, **kwargs):
return self.screen.addstr(*args, **kwargs)
def setup(self):
self.screen = curses_init()
self.screen.keypad(1)
self.screen.nodelay(1)
self.screen.idlok(1)
self.screen.move(0, 0)
curses.def_prog_mode()
self.help.setup()
self.cli.setup()
# Register some terminal resizing magic if supported...
if hasattr(curses, 'resize_term') and hasattr(signal, 'SIGWINCH'):
self.dumbtty = False
signal.signal(signal.SIGWINCH, self._sigwinchhandler)
# If we came this far the display is active
self.active = True
def getmaxyx(self):
ymax, xmax = self.screen.getmaxyx()
xmax = min(xmax, SCREEN_XMAX)
ymax = min(ymax, SCREEN_YMAX)
return ymax, xmax
def resize(self):
if not self.dumbtty:
self.clear()
size = fcntl.ioctl(0, tty.TIOCGWINSZ, '12345678')
size = struct.unpack('4H', size)
curses.resize_term(size[0], size[1])
ymax, xmax = self.getmaxyx()
if xmax < SCREEN_XMIN or ymax < SCREEN_YMIN:
raise RuntimeError(
'screen too small, need at least %dx%d'
% (SCREEN_XMIN, SCREEN_YMIN))
if ymax == self.ymax and xmax == self.xmax:
self._resized = False
return
if xmax != self.xmax:
self.xmax = xmax
if ymax != self.ymax:
self.ymax = ymax
self.mode.sync(self)
# Force re-wrapping of the screenlines in CLI mode
if self.mid == 5:
self.cli.update_screenlines()
self.cli.draw_output()
self._resized = False
def reset(self):
if not self.active:
return
curses_reset(self.screen)
def recover(self):
curses.reset_prog_mode()
def refresh(self):
self.screen.noutrefresh()
if self.mid == 0:
self.help.refresh()
elif self.mid == 5:
self.cli.refresh_output()
self.cli.refresh_input()
curses.doupdate()
def clear(self):
# Note: Forces the whole screen to be repainted upon refresh()
self.screen.clear()
def erase(self):
self.screen.erase()
def switch_mode(self, mid):
if mid == 5 and self.data.socket.ro:
return # noop
mode = self.modes[mid]
mode.sync(self)
if self.mid != 5 and mid == 5:
self.cli.start()
elif self.mid == 5 and mid != 5:
self.cli.stop()
self._pmid = self._cmid
self._cmid, self._mode = mid, mode
def toggle_mode(self):
if self._pmid == self._cmid:
return
self.switch_mode(self._pmid)
def cycle_mode(self, n):
if n == 0:
return
if self.data.socket.ro:
border = 4
else:
border = 5
if self._cmid == 0:
self.switch_mode(1)
elif n < 0 and self._cmid == 1:
self.switch_mode(border)
elif n > 0 and self._cmid == border:
self.switch_mode(1)
else:
self.switch_mode(self._cmid + n)
def update_data(self):
self.data.update_info()
try:
self.data.update_stat()
except RuntimeWarning, x:
self.exceptions.append(x)
def update_bars(self):
self.sb_conn.update_max(int(self.data.info['maxconn'], 10))
self.sb_conn.update_cur(int(self.data.info['curconn'], 10))
self.sb_pipe.update_max(int(self.data.info['maxpipes'], 10))
self.sb_pipe.update_cur(int(self.data.info['curpipes'], 10))
def update_lines(self):
# Display non-fatal exceptions on screen
if self.exceptions:
self.mvhome()
self.lines = []
self.cursor = False
for x in self.exceptions:
for line in str(x).splitlines():
line = line.center(SCREEN_XMIN)
self.lines.append(ScreenLine(text=line))
self.exceptions = []
return
# Reset cursor visibility
if not self.cursor:
self.cursor = True
# Update screen lines
self.lines = get_screenlines(self.data.stat)
if self.data.svcount >= HAPROXY_STAT_MAX_SERVICES:
self.lines.append(ScreenLine())
for line in HAPROXY_STAT_LIMIT_WARNING.splitlines():
self.lines.append(ScreenLine(text=line))
def draw_line(self, ypos, xpos=0, text=None,
attr=curses.A_REVERSE):
self.hline(ypos, self.xmin, ' ', self.xmax, attr)
if text:
self.addstr(ypos, self.xmin + xpos, text, attr)
def draw_head(self):
self.draw_line(self.ymin)
attr = curses.A_REVERSE | curses.A_BOLD
self.addstr(self.ymin, self.xmin,
time.ctime().rjust(self.xmax - 1), attr)
self.addstr(self.ymin, self.xmin + 1,
'HATop version ' + __version__, attr)
def draw_info(self):
self.addstr(self.ymin + 2, self.xmin + 2,
'%s Version: %s (released: %s)' % (
self.data.info['software_name'],
self.data.info['software_version'],
self.data.info['software_release'],
), curses.A_BOLD)
self.addstr(self.ymin + 2, self.xmin + 56,
'PID: %d (proc %d)' % (
int(self.data.info['pid'], 10),
int(self.data.info['procn'], 10),
), curses.A_BOLD)
self.addstr(self.ymin + 4, self.xmin + 2,
' Node: %s (uptime %s)' % (
self.data.info['node'] or 'unknown',
self.data.info['uptime'],
))
self.addstr(self.ymin + 6, self.xmin + 2,
' Pipes: %s' % self.sb_pipe)
self.addstr(self.ymin + 7, self.xmin + 2,
'Connections: %s' % self.sb_conn)
self.addstr(self.ymin + 9, self.xmin + 2,
'Procs: %3d Tasks: %5d Queue: %5d '
'Proxies: %3d Services: %4d' % (
int(self.data.info['nproc'], 10),
int(self.data.info['tasks'], 10),
int(self.data.info['runqueue'], 10),
self.data.pxcount,
self.data.svcount,
))
def draw_cols(self):
self.draw_line(self.hpos, text=self.mode.head,
attr=curses.A_REVERSE | curses.A_BOLD)
def draw_foot(self):
xpos = self.xmin
ypos = self.ymax - 1
self.draw_line(ypos)
attr_active = curses.A_BOLD
attr_inactive = curses.A_BOLD | curses.A_REVERSE
# HOTKEYS
if (self.hotkeys and
0 < self.mid < 5 and
self.cstat and
self.cstat['iid'] > 0 and
self.cstat['sid'] > 0):
self.draw_line(ypos)
self.addstr(ypos, 1, 'HOTKEYS:',
curses.A_BOLD | curses.A_REVERSE)
self.addstr(ypos, 11,
'F4=W-RESET '
'F5=W-10 F6=W-1 F7=W+1 F8=W+10 '
'F9=ENABLE F10=DISABLE',
curses.A_NORMAL | curses.A_REVERSE)
return
# VIEWPORTS
for mid, mode in enumerate(self.modes):
if mid == 0:
continue
if mid == 5 and self.data.socket.ro:
continue
if mid == self.mid:
attr = attr_active
else:
attr = attr_inactive
s = ' %d-%s ' % (mid, mode.name)
self.addstr(ypos, xpos, s, attr)
xpos += len(s)
if 0 < self.mid < 5 and self.cstat:
if self.cstat['iid'] > 0 and self.cstat['sid'] > 0:
if self.data.socket.ro:
s = 'READ-ONLY [#%d/#%d]' % (
self.cstat['iid'], self.cstat['sid'])
else:
s = 'ENTER=MENU SPACE=SEL [#%d/#%d]' % (
self.cstat['iid'], self.cstat['sid'])
else:
if self.data.socket.ro:
s = 'READ-ONLY [#%d/#%d]' % (
self.cstat['iid'], self.cstat['sid'])
else:
s = '[#%d/#%d]' % (
self.cstat['iid'], self.cstat['sid'])
elif self.mid == 5:
s = 'PGUP/PGDOWN=SCROLL'
else:
s = 'UP/DOWN=SCROLL H=HELP Q=QUIT'
self.addstr(ypos, self.xmax - len(s) - 1, s, attr_inactive)
def draw_stat(self):
for idx, line in self.screenlines:
if self.cursor and idx == self.cpos:
attr = line.attr | curses.A_REVERSE
else:
attr = line.attr
if not line.stat:
screenline = get_cell(self.xmax, 'L', line.text)
elif 'message' in line.stat:
screenline = get_cell(self.xmax, 'L', line.stat['message'])
else:
screenline = get_screenline(self.mode, line.stat)
self.addstr(self.smin + idx, self.xmin, screenline, attr)
def draw_mode(self):
if self.mid == 0:
self.help.draw()
elif self.mid == 5 and self._pmid == self._cmid:
self.cli.start() # initial mid was 5
elif 0 < self.mid < 5:
self.draw_stat()
def mvc(self, n):
if n == 0:
return
# Move DOWN
if n > 0:
# move cursor
if self.cpos < self.cmax:
self.cpos = min(self.cmax, self.cpos + n)
return
# move screenlines
maxvmin = max(0, len(self.lines) - self.span - 1)
if self.cpos == self.cmax and self.vmin < maxvmin:
self.vmin = min(maxvmin, self.vmin + n)
# Move UP
elif n < 0: # UP
# move cursor
if self.cpos > self.cmin:
self.cpos = max(self.cmin, self.cpos + n)
return
# move screenlines
if self.cpos == self.cmin and self.vmin > 0:
self.vmin = max(0, self.vmin + n)
def mvhome(self):
# move cursor
if self.cpos != self.cmin:
self.cpos = self.cmin
# move screenlines
if self.vmin != 0:
self.vmin = 0
def mvend(self):
# move cursor
if self.cpos != self.cmax:
self.cpos = self.cmax
# move screenlines
maxvmin = max(0, len(self.lines) - self.span - 1)
if self.vmin != maxvmin:
self.vmin = maxvmin
class ScreenHelp:
def __init__(self, screen):
self.screen = screen
self.xmin = screen.xmin + 1
self.xmax = screen.xmax
self.ymin = 0
self.ymax = __doc__.count('\n')
self.xpos = 0
self.ypos = 0
def setup(self):
self.pad = curses.newpad(self.ymax + 1, self.xmax + 1)
def addstr(self, *args, **kwargs):
return self.pad.addstr(*args, **kwargs)
def refresh(self):
self.pad.noutrefresh(
self.ypos, self.xpos,
self.screen.smin, self.xmin,
self.screen.smax, self.xmax - 2)
def draw(self):
self.addstr(0, 0, __doc__)
def mvc(self, n):
if n == 0:
return
# Move DOWN
if n > 0:
self.ypos = min(self.ymax - self.screen.span, self.ypos + n)
# Move UP
elif n < 0:
self.ypos = max(self.ymin, self.ypos + n)
def mvhome(self):
self.ypos = self.ymin
def mvend(self):
self.ypos = self.ymax - self.screen.span
class ScreenMode:
def __init__(self, name):
self.name = name
self.columns = []
@property
def head(self):
return get_head(self)
def sync(self, screen):
for idx, column in enumerate(self.columns):
column.width = get_width(column.minwidth, screen.xmax,
len(self.columns), idx)
class ScreenColumn:
def __init__(self, name, header, minwidth, maxwidth, align, filters={}):
self.name = name
self.header = header
self.align = align
self.minwidth = minwidth
self.maxwidth = maxwidth
self.width = minwidth
self.filters = {'always': [], 'ondemand': []}
self.filters.update(filters)
def get_width(self):
return self._width
def set_width(self, n):
if self.maxwidth:
self._width = min(self.maxwidth, n)
self._width = max(self.minwidth, n)
width = property(get_width, set_width)
class ScreenLine:
def __init__(self, stat=None, text='', attr=0):
self.stat = stat
self.text = text
self.attr = attr
class StatusBar:
def __init__(self, width=60, min=0, max=100, status=True):
self.width = width
self.curval = min
self.minval = min
self.maxval = max
self.status = status
self.prepend = '['
self.append = ']'
self.usedchar = '|'
self.freechar = ' '
def __str__(self):
if self.status:
status = '%d/%d' % (self.curval, self.maxval)
space = self.width - len(self.prepend) - len(self.append)
span = self.maxval - self.minval
if span:
used = min(float(self.curval) / float(span), 1.0)
else:
used = 0.0
free = 1.0 - used
# 100% equals full bar width, ignoring status text within the bar
bar = self.prepend
bar += self.usedchar * int(space * used)
bar += self.freechar * int(space * free)
if self.status:
bar = bar[:(self.width - len(status) - len(self.append))]
bar += status
bar += self.append
return bar
def update_cur(self, value):
value = min(self.maxval, value)
value = max(self.minval, value)
self.curval = value
def update_max(self, value):
if value >= self.minval:
self.maxval = value
else:
self.maxval = self.minval
# ------------------------------------------------------------------------- #
# DISPLAY FILTERS #
# ------------------------------------------------------------------------- #
def human_seconds(numeric):
for minval, prefix in sorted(PREFIX_TIME.items(), reverse=True):
if (numeric/minval):
return '%d%s' % (numeric/minval, prefix)
return '%ds' % numeric
def human_metric(numeric):
for minval, prefix in sorted(PREFIX_METRIC.items(), reverse=True):
if (numeric/minval):
return '%d%s' % (numeric/minval, prefix)
return str(numeric)
def human_binary(numeric):
for minval, prefix in sorted(PREFIX_BINARY.items(), reverse=True):
if (numeric/minval):
return '%.2f%s' % (float(numeric)/float(minval), prefix)
return '%dB' % numeric
def trim(string, length):
if len(string) <= length:
return string
if length == 1:
return string[0]
if length > 5:
return '..%s' % string[-(length-2):]
return '...'
# ------------------------------------------------------------------------- #
# SCREEN LAYOUT #
# ------------------------------------------------------------------------- #
SCREEN_MODES = [
ScreenMode('HELP'),
ScreenMode('STATUS'),
ScreenMode('TRAFFIC'),
ScreenMode('HTTP'),
ScreenMode('ERRORS'),
ScreenMode('CLI'),
]
# Mode: HELP name header xmin xmax align
SCREEN_MODES[0].columns = [
ScreenColumn('help', ' HATop Online Help ',
SCREEN_XMIN, 0, 'L'),
]
# Mode: STATUS name header xmin xmax align
SCREEN_MODES[1].columns = [
ScreenColumn('svname', 'NAME', 10, 50, 'L'),
ScreenColumn('weight', 'W', 4, 6, 'R'),
ScreenColumn('status', 'STATUS', 6, 10, 'L'),
ScreenColumn('check_status', 'CHECK', 7, 20, 'L'),
ScreenColumn('act', 'ACT', 3, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('bck', 'BCK', 3, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('qcur', 'QCUR', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('qmax', 'QMAX', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('scur', 'SCUR', 6, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('smax', 'SMAX', 6, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('slim', 'SLIM', 6, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('stot', 'STOT', 6, 0, 'R',
filters={'ondemand': [human_metric]}),
]
# Mode: TRAFFIC name header xmin xmax align
SCREEN_MODES[2].columns = [
ScreenColumn('svname', 'NAME', 10, 50, 'L'),
ScreenColumn('weight', 'W', 4, 6, 'R'),
ScreenColumn('status', 'STATUS', 6, 10, 'L'),
ScreenColumn('lbtot', 'LBTOT', 8, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('rate', 'RATE', 6, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('rate_lim', 'RLIM', 6, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('rate_max', 'RMAX', 6, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('bin', 'BIN', 12, 0, 'R',
filters={'always': [human_binary]}),
ScreenColumn('bout', 'BOUT', 12, 0, 'R',
filters={'always': [human_binary]}),
]
# Mode: HTTP name header xmin xmax align
SCREEN_MODES[3].columns = [
ScreenColumn('svname', 'NAME', 10, 50, 'L'),
ScreenColumn('weight', 'W', 4, 6, 'R'),
ScreenColumn('status', 'STATUS', 6, 10, 'L'),
ScreenColumn('req_rate', 'RATE', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('req_rate_max', 'RMAX', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('req_tot', 'RTOT', 7, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('hrsp_1xx', '1xx', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('hrsp_2xx', '2xx', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('hrsp_3xx', '3xx', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('hrsp_4xx', '4xx', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('hrsp_5xx', '5xx', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('hrsp_other', '?xx', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
]
# Mode: ERRORS name header xmin xmax align
SCREEN_MODES[4].columns = [
ScreenColumn('svname', 'NAME', 10, 50, 'L'),
ScreenColumn('weight', 'W', 4, 6, 'R'),
ScreenColumn('status', 'STATUS', 6, 10, 'L'),
ScreenColumn('check_status', 'CHECK', 7, 20, 'L'),
ScreenColumn('chkfail', 'CF', 3, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('chkdown', 'CD', 3, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('lastchg', 'CL', 3, 0, 'R',
filters={'always': [human_seconds]}),
ScreenColumn('econ', 'ECONN', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('ereq', 'EREQ', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('eresp', 'ERSP', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('dreq', 'DREQ', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('dresp', 'DRSP', 5, 0, 'R',
filters={'ondemand': [human_metric]}),
ScreenColumn('downtime', 'DOWN', 5, 0, 'R',
filters={'always': [human_seconds]}),
]
# Mode: CLI name header xmin xmax align
SCREEN_MODES[5].columns = [
ScreenColumn('cli',
' haproxy command line '
' use ALT-n / ESC-n to escape',
SCREEN_XMIN, 0, 'L'),
]
# ------------------------------------------------------------------------- #
# HELPERS #
# ------------------------------------------------------------------------- #
def log(msg):
sys.stderr.write('%s\n' % msg)
def parse_stat(iterable):
pxcount = svcount = 0
pxstat = {} # {iid: {sid: svstat, ...}, ...}
idx_iid = get_idx('iid')
idx_sid = get_idx('sid')
for line in iterable:
if not line:
continue
if line.startswith(HAPROXY_STAT_COMMENT):
continue # comment
if line.count(HAPROXY_STAT_SEP) < HAPROXY_STAT_NUMFIELDS:
continue # unknown format
csv = line.split(HAPROXY_STAT_SEP, HAPROXY_STAT_NUMFIELDS)
# Skip further parsing?
if svcount > HAPROXY_STAT_MAX_SERVICES:
try:
iid = csv[idx_iid]
iid = int(iid, 10)
except ValueError:
raise RuntimeError(
'garbage proxy identifier: iid="%s" (need %s)' %
(iid, int))
try:
sid = csv[idx_sid]
sid = int(sid, 10)
except ValueError:
raise RuntimeError(
'garbage service identifier: sid="%s" (need %s)' %
(sid, int))
if iid not in pxstat:
pxcount += 1
svcount += 1
elif sid not in pxstat[iid]:
svcount += 1
continue
# Parse stat...
svstat = {} # {field: value, ...}
for idx, field in HAPROXY_STAT_CSV:
field_type, field_name = field
value = csv[idx]
try:
if field_type is int:
if len(value):
value = int(value, 10)
else:
value = 0
elif field_type is not type(value):
value = field_type(value)
except ValueError:
raise RuntimeError('garbage field: %s="%s" (need %s)' % (
field_name, value, field_type))
# Special case
if field_name == 'status' and value == 'no check':
value = '-'
elif field_name == 'check_status' and svstat['status'] == '-':
value = 'none'
svstat[field_name] = value
# Record result...
iid = svstat['iid']
stype = svstat['type']
if stype == 0 or stype == 1: # FRONTEND / BACKEND
id = svstat['svname']
else:
id = svstat['sid']
try:
pxstat[iid][id] = svstat
except KeyError:
pxstat[iid] = { id: svstat }
pxcount += 1
svcount += 1
return pxstat, pxcount, svcount
def parse_info(iterable):
info = {}
for line in iterable:
line = line.strip()
if not line:
continue
for key, regexp in HAPROXY_INFO_RE.iteritems():
match = regexp.match(line)
if match:
info[key] = match.group('value')
break
for key in HAPROXY_INFO_RE.iterkeys():
if not key in info:
raise RuntimeError('missing "%s" in info data' % key)
return info
def get_idx(field):
return filter(lambda x: x[1][1] == field, HAPROXY_STAT_CSV)[0][0]
def get_width(width, xmax, ncols, idx):
# distribute excess space evenly from left to right
if xmax > SCREEN_XMIN:
xdiff = xmax - SCREEN_XMIN
if xdiff <= ncols:
if idx < xdiff:
width += 1
else:
if idx < (xdiff - (xdiff / ncols) * ncols):
width += 1 # compensate rounding
width = width + xdiff / ncols
return width
def get_cell(width, align, value):
s = str(value)
if align == 'L':
s = s.ljust(width)
elif align == 'C':
s = s.center(width)
elif align == 'R':
s = s.rjust(width)
return s
def get_head(mode):
columns = []
for column in mode.columns:
s = column.header
s = get_cell(column.width, column.align, s)
columns.append(s)
return ' '.join(columns)
def get_screenlines(stat):
screenlines = []
for iid, svstats in stat.iteritems():
lines = []
try:
frontend = svstats.pop('FRONTEND')
except KeyError:
frontend = None
try:
backend = svstats.pop('BACKEND')
except KeyError:
backend = None
if frontend:
lines.append(ScreenLine(stat=frontend))
for sid, svstat in sorted(svstats.items()):
lines.append(ScreenLine(stat=svstat))
if backend:
lines.append(ScreenLine(stat=backend))
if not len(lines):
continue
pxname = lines[0].stat['pxname']
screenlines.append(ScreenLine(attr=curses.A_BOLD,
text='>>> %s' % pxname))
screenlines += lines
screenlines.append(ScreenLine())
# remove trailing empty line
if len(screenlines) > 1:
screenlines.pop()
return screenlines
def get_screenline(mode, stat):
cells = []
for column in mode.columns:
value = stat[column.name]
for filter in column.filters['always']:
value = filter(value)
if len(str(value)) > column.width:
for filter in column.filters['ondemand']:
value = filter(value)
value = str(value)
value = trim(value, column.width)
cells.append(get_cell(column.width, column.align, value))
return ' '.join(cells)
# ------------------------------------------------------------------------- #
# CURSES HELPERS #
# ------------------------------------------------------------------------- #
def curses_init():
screen = curses.initscr()
curses.noecho()
curses.nonl()
curses.raw()
# Some terminals don't support different cursor visibilities
try:
curses.curs_set(0)
except CursesError:
pass
# Some terminals don't support the default color palette
try:
curses.start_color()
curses.use_default_colors()
except CursesError:
pass
return screen
def curses_reset(screen):
if not screen:
return
screen.keypad(0)
curses.noraw()
curses.echo()
curses.endwin()
# ------------------------------------------------------------------------- #
# MAIN LOOP #
# ------------------------------------------------------------------------- #
def mainloop(screen, interval):
# Sleep time of each iteration in seconds
scan = 1.0 / 100.0
# Query socket and redraw the screen in the given interval
iterations = interval / scan
i = 0
update_stat = True # Toggle stat update (query socket, parse csv)
update_lines = True # Toggle screen line update (sync with stat data)
update_display = True # Toggle screen update (resize, repaint, refresh)
switch_mode = False # Toggle mode / viewport switch
while True:
# Resize toggled by SIGWINCH?
if screen.resized:
screen.resize()
update_display = True
# Update interval reached...
if i == iterations:
update_stat = True
if 0 < screen.mid < 5:
update_lines = True
update_display = True
i = 0
# Refresh screen?
if update_display:
if update_stat:
screen.update_data()
screen.update_bars()
update_stat = False
if update_lines:
screen.update_lines()
update_lines = False
screen.erase()
screen.draw_head()
screen.draw_info()
screen.draw_cols()
screen.draw_mode()
screen.draw_foot()
screen.refresh()
update_display = False
c = screen.getch()
if c < 0:
time.sleep(scan)
i += 1
continue
# Toggle hotkey footer
if screen.hotkeys:
if c not in (
curses.KEY_F4, # reset weight
curses.KEY_F5, # weight -10
curses.KEY_F6, # weight -1
curses.KEY_F7, # weight +1
curses.KEY_F8, # weight +10
curses.KEY_F9, # enable server
curses.KEY_F10, # disable server
):
screen.hotkeys = False
update_display = True
if c in (
curses.KEY_ENTER,
curses.ascii.CR
):
continue
if c == curses.ascii.ETX:
raise KeyboardInterrupt()
# Mode switch (ALT-n / ESC-n) or toggle (ESC / ESC-ESC)
if c == curses.ascii.ESC:
c = screen.getch()
if c < 0 or c == curses.ascii.ESC:
screen.toggle_mode()
update_display = True
continue
if 0 < c < 256:
c = chr(c)
if c in 'qQHh?12345':
switch_mode = True
# Mode cycle (TAB / BTAB)
elif c == ord('\t'):
screen.cycle_mode(1)
update_display = True
continue
elif c == curses.KEY_BTAB:
screen.cycle_mode(-1)
update_display = True
continue
# Mode switch in non-CLI modes using the number only
elif 0 <= screen.mid < 5 and 0 < c < 256:
c = chr(c)
if c in 'qQHh?12345':
switch_mode = True
if switch_mode:
switch_mode = False
if c in 'qQ':
raise StopIteration()
if c != str(screen.mid) or (c in 'Hh?' and screen.mid != 0):
if c in 'Hh?':
screen.switch_mode(0)
elif c in '12345':
screen.switch_mode(int(c))
# Force screen update with existing data
update_display = True
continue
# -> HELP
if screen.mid == 0:
if c == curses.KEY_UP and screen.help.ypos > 0:
screen.help.mvc(-1)
elif c == curses.KEY_DOWN and \
screen.help.ypos < screen.help.ymax - screen.span:
screen.help.mvc(1)
elif c == curses.KEY_PPAGE and screen.help.ypos > 0:
screen.help.mvc(-10)
elif c == curses.KEY_NPAGE and \
screen.help.ypos < screen.help.ymax - screen.span:
screen.help.mvc(10)
elif c == curses.ascii.SOH or c == curses.KEY_HOME:
screen.help.mvhome()
elif c == curses.ascii.ENQ or c == curses.KEY_END:
screen.help.mvend()
# -> STATUS / TRAFFIC / HTTP / ERRORS
elif 1 <= screen.mid <= 4:
# movements
if c == curses.KEY_UP:
screen.mvc(-1)
elif c == curses.KEY_DOWN:
screen.mvc(1)
elif c == curses.KEY_PPAGE:
screen.mvc(-10)
elif c == curses.KEY_NPAGE:
screen.mvc(10)
elif c == curses.ascii.SOH or c == curses.KEY_HOME:
screen.mvhome()
elif c == curses.ascii.ENQ or c == curses.KEY_END:
screen.mvend()
# actions
elif c in (
curses.KEY_ENTER, # show hotkeys
chr(curses.ascii.CR), # show hotkeys
chr(curses.ascii.SP), # copy & paste identifier
curses.KEY_F4, # reset weight
curses.KEY_F5, # weight -10
curses.KEY_F6, # weight -1
curses.KEY_F7, # weight +1
curses.KEY_F8, # weight +10
curses.KEY_F9, # enable server
curses.KEY_F10, # disable server
):
if screen.data.socket.ro:
continue
if not screen.cstat:
continue
if c == curses.KEY_ENTER or c == chr(curses.ascii.CR):
screen.hotkeys = True
update_display = True
continue
iid = screen.cstat['iid']
sid = screen.cstat['sid']
if iid <= 0 or sid <= 0:
continue
pxname = screen.cstat['pxname']
svname = screen.cstat['svname']
if not pxname or not svname:
continue
notify = False
if c == ' ':
if screen.cli.puts('%s/%s' % (pxname, svname)):
screen.switch_mode(5)
update_display = True
continue
elif c == curses.KEY_F4:
screen.cli.execute_cmdline(
'set weight %s/%s 100%%' % (pxname, svname))
notify = True
elif c == curses.KEY_F5:
curweight = screen.cstat['weight']
if curweight <= 0:
continue
weight = max(0, curweight - 10) # - 10
screen.cli.execute_cmdline(
'set weight %s/%s %d' % (pxname, svname, weight))
notify = True
elif c == curses.KEY_F6:
curweight = screen.cstat['weight']
if curweight <= 0:
continue
weight = max(0, curweight - 1) # - 1
screen.cli.execute_cmdline(
'set weight %s/%s %d' % (pxname, svname, weight))
notify = True
elif c == curses.KEY_F7:
curweight = screen.cstat['weight']
if curweight >= 256:
continue
weight = min(256, curweight + 1) # + 1
screen.cli.execute_cmdline(
'set weight %s/%s %d' % (pxname, svname, weight))
notify = True
elif c == curses.KEY_F8:
curweight = screen.cstat['weight']
if curweight >= 256:
continue
weight = min(256, curweight + 10) # + 10
screen.cli.execute_cmdline(
'set weight %s/%s %d' % (pxname, svname, weight))
notify = True
elif c == curses.KEY_F9:
screen.cli.execute_cmdline(
'enable server %s/%s' % (pxname, svname))
notify = True
elif c == curses.KEY_F10:
screen.cli.execute_cmdline(
'disable server %s/%s' % (pxname, svname))
notify = True
# Refresh the screen indicating pending changes...
if notify:
screen.cstat['message'] = 'updating...'
update_display = True
continue
# -> CLI
elif screen.mid == 5:
# enter
if c == curses.KEY_ENTER or c == curses.ascii.CR:
screen.cli.execute()
# input movements
elif c == curses.KEY_LEFT:
screen.cli.mvc(-1)
elif c == curses.KEY_RIGHT:
screen.cli.mvc(1)
elif c == curses.ascii.SOH or c == curses.KEY_HOME:
screen.cli.mvhome()
elif c == curses.ascii.ENQ or c == curses.KEY_END:
screen.cli.mvend()
# input editing
elif c == curses.ascii.ETB:
pass # TODO (CTRL-W)
elif c == curses.KEY_DC:
screen.cli.delc(1)
elif c == curses.KEY_BACKSPACE or c == curses.ascii.DEL:
screen.cli.delc(-1)
# input history
elif c == curses.KEY_UP:
screen.cli.prev()
elif c == curses.KEY_DOWN:
screen.cli.next()
# output history
elif c == curses.KEY_PPAGE:
screen.cli.mvo(-1)
elif c == curses.KEY_NPAGE:
screen.cli.mvo(1)
elif 0 < c < 256:
screen.cli.putc(chr(c))
# Force screen update with existing data if key was a movement key
if c in (
curses.KEY_UP,
curses.KEY_DOWN,
curses.KEY_PPAGE,
curses.KEY_NPAGE,
) or screen.mid != 5 and c in (
curses.ascii.SOH, curses.KEY_HOME,
curses.ascii.ENQ, curses.KEY_END,
):
update_display = True
time.sleep(scan)
i += 1
if __name__ == '__main__':
from optparse import OptionParser, OptionGroup
version = 'hatop version %s' % __version__
usage = 'Usage: hatop -s SOCKET [OPTIONS]...'
parser = OptionParser(usage=usage, version=version)
opts = OptionGroup(parser, 'Mandatory')
opts.add_option('-s', '--unix-socket', dest='socket',
help='path to the haproxy unix socket')
parser.add_option_group(opts)
opts = OptionGroup(parser, 'Optional')
opts.add_option('-i', '--update-interval', type='int', dest='interval',
help='update interval in seconds (1-30, default: 3)', default=3)
opts.add_option('-m', '--mode', type='int', dest='mode',
help='start in specific mode (1-5, default: 1)', default=1)
opts.add_option('-n', '--read-only', action='store_true', dest='ro',
help='disable the cli and query for stats only')
parser.add_option_group(opts)
opts = OptionGroup(parser, 'Filters',
'Note: All filter options may be given multiple times.')
opts.add_option('-f', '--filter', action='append', dest='stat_filter',
default=[], metavar='FILTER',
help='stat filter in format ""')
opts.add_option('-p', '--proxy', action='append', dest='proxy_filter',
default=[], metavar='PROXY',
help='proxy filter in format ""')
parser.add_option_group(opts)
opts, args = parser.parse_args()
if not 1 <= opts.interval <= 30:
log('invalid update interval: %d' % opts.interval)
sys.exit(1)
if not 1 <= opts.mode <= 5:
log('invalid mode: %d' % opts.mode)
sys.exit(1)
if len(opts.stat_filter) + len(opts.proxy_filter) > 50:
log('filter limit exceeded (50)')
sys.exit(1)
if opts.ro and opts.mode == 5:
log('cli not available in read-only mode')
sys.exit(1)
if not opts.socket:
parser.print_help()
sys.exit(0)
if not os.access(opts.socket, os.R_OK | os.W_OK):
log('insufficient permissions for socket path %s' % opts.socket)
sys.exit(2)
socket = Socket(opts.socket, opts.ro)
data = SocketData(socket)
screen = Screen(data, opts.mode)
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(0))
try:
try:
socket.connect()
screen.setup()
# Register filters
data.register_stat_filter(opts.stat_filter)
data.register_proxy_filter(opts.proxy_filter)
while True:
try:
mainloop(screen, opts.interval)
except StopIteration:
break
except KeyboardInterrupt:
break
except CursesError, e:
screen.reset()
log('curses error: %s, restarting...' % e)
time.sleep(1)
screen.recover()
except ValueError, e:
screen.reset()
log('value error: %s' % e)
sys.exit(1)
except RuntimeError, e:
screen.reset()
log('runtime error: %s' % e)
sys.exit(1)
except SocketError, e:
screen.reset()
log('socket error: %s' % e)
sys.exit(2)
finally:
screen.reset()
socket.close()
sys.exit(0)
# vim: et sw=4 sts=4 ts=4 tw=78 fdn=1 fdm=indent
hatop-0.7.7/doc/ 0000775 0000000 0000000 00000000000 11452621517 0013411 5 ustar 00root root 0000000 0000000 hatop-0.7.7/doc/Makefile 0000664 0000000 0000000 00000006063 11452621517 0015056 0 ustar 00root root 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/HATop.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/HATop.qhc"
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
"run these through (pdf)latex."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
hatop-0.7.7/doc/bugs.rst 0000664 0000000 0000000 00000000331 11452621517 0015100 0 ustar 00root root 0000000 0000000 .. _bugs:
********************
Bugs and suggestions
********************
For now, please contact us directly at bugs@feurix.org. Thanks! :-)
*Please note your exact HAProxy and Python version in the bug report!*
hatop-0.7.7/doc/build/ 0000775 0000000 0000000 00000000000 11452621517 0014510 5 ustar 00root root 0000000 0000000 hatop-0.7.7/doc/build/.gitignore 0000664 0000000 0000000 00000000002 11452621517 0016470 0 ustar 00root root 0000000 0000000 *
hatop-0.7.7/doc/changes.rst 0000664 0000000 0000000 00000000047 11452621517 0015554 0 ustar 00root root 0000000 0000000 .. _changes:
.. include:: ../CHANGES
hatop-0.7.7/doc/conf.py 0000664 0000000 0000000 00000013115 11452621517 0014711 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# HATop documentation build configuration file.
import sys
import time
project = u'HATop'
copyright = u'2009-%s, John Feuerstein' % time.strftime('%Y')
# Import hack to get the current script version from the executable
from imp import load_source
sys.dont_write_bytecode = True
load_source('hatop', '../bin/hatop')
from hatop import __version__ as version, __version__ as release
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'contents'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
html_title = 'HATop: Interactive ncurses client for HAProxy'
# A shorter title for the navigation bar. Default is the same as html_title.
html_short_title = 'HATop'
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'index': 'indexsidebar.html',
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
html_additional_pages = {
'index': 'indexcontent.html',
}
# If false, no module index is generated.
html_use_modindex = False
# If false, no index is generated.
html_use_index = False
# If true, the index is split into individual pages for each letter.
html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'hatopdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
latex_paper_size = 'a4'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'HATop.tex', u'HATop Documentation',
u'John Feuerstein', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
hatop-0.7.7/doc/contents.rst 0000664 0000000 0000000 00000000236 11452621517 0016001 0 ustar 00root root 0000000 0000000 %%%%%%%
HATop
%%%%%%%
.. toctree::
index.rst
changes.rst
readme.rst
install.rst
screenshots.rst
keybinds.rst
license.rst
bugs.rst
hatop-0.7.7/doc/images/ 0000775 0000000 0000000 00000000000 11452621517 0014656 5 ustar 00root root 0000000 0000000 hatop-0.7.7/doc/images/0-help.png 0000664 0000000 0000000 00000031714 11452621517 0016457 0 ustar 00root root 0000000 0000000 PNG
IHDR r 6[ sRGB pHYs ȥ IDATxۖ d/