├── .gitignore ├── CHANGES.rst ├── HACKING ├── INSTALL.rst ├── KEYBINDS ├── LICENSE ├── README.rst ├── bin └── hatop ├── doc ├── Makefile ├── bugs.rst ├── build │ └── .gitignore ├── changes.rst ├── conf.py ├── contents.rst ├── images │ ├── 0-help.png │ ├── 1-status.png │ ├── 2-traffic.png │ ├── 3-http.png │ ├── 4-errors.png │ ├── 5-cli-help.png │ └── 5-cli.png ├── index.rst ├── install.rst ├── keybinds.rst ├── license.rst ├── readme.rst ├── screenshots.rst ├── static │ ├── default.css │ ├── disk.png │ ├── glider.png │ ├── gplv3.png │ └── logo.png └── templates │ ├── indexcontent.html │ ├── indexsidebar.html │ └── layout.html ├── man └── hatop.1 ├── scripts ├── package.sh └── package_deb.sh └── test ├── .gitignore ├── hatop ├── .gitignore ├── README.md ├── configure ├── fetch ├── hatop ├── run └── template │ └── index.html └── sample-socket.py /.gitignore: -------------------------------------------------------------------------------- 1 | scripts/tmp/* 2 | scripts/deb_custom_control 3 | *.py[co] 4 | *.swp 5 | *.tmp 6 | *.~ 7 | .DS_Store 8 | -------------------------------------------------------------------------------- /CHANGES.rst: -------------------------------------------------------------------------------- 1 | ********* 2 | Changelog 3 | ********* 4 | 5 | This is a brief overview of the changes introduced by each version. 6 | 7 | 8 | HATop 0.8 9 | ========= 10 | 11 | HATop is now compatible with Python 3. 12 | 13 | James Hunt has officially taken over maintainership of this project. 14 | Work will continue on GitHub at https://github.com/jhunt/hatop. 15 | 16 | 17 | HATop 0.8.2 18 | ----------- 19 | 20 | :Date: May 21, 2022 21 | 22 | - Bugfix: in CLI mode, pressing the down arrow no longer crashes Python 2.x 23 | 24 | 25 | HATop 0.8.1 26 | ----------- 27 | 28 | :Date: Apr 14, 2021 29 | 30 | - Feature: F1/F2 hot keys now affect ALL backends 31 | 32 | - Feature: New F9/F10 hot keys implement legacy F1/F2 behavior 33 | 34 | 35 | HATop 0.8.0 36 | ----------- 37 | 38 | :Date: Jul 30, 2020 39 | 40 | - Feature: Support for Python3 41 | 42 | - Feature: Bump max services from 100 -> 1000 43 | 44 | - Feature: Support for connecting to HAProxy via a TCP socket. 45 | (Andrew Hayworth) 46 | 47 | 48 | HATop 0.7 49 | ========= 50 | 51 | This is the first public series after reaching a feature complete state. 52 | 53 | 54 | HATop 0.7.7 55 | ----------- 56 | 57 | :Date: Oct 05, 2010 58 | 59 | - Feature: Display hotkey footer when pressing ENTER on selected service. 60 | 61 | - Feature: Use string identifier ("pxname/svname") instead of numerical 62 | identifier ("#iid/#sid") for hotkey actions. 63 | 64 | - Bugfix: Display cursor and focus input if started in CLI mode. 65 | 66 | - Bugfix: Reload stat data if number of proxies or services has changed. 67 | 68 | - Bugfix: Prevent infinite size sync if screen size is larger than supported. 69 | (Jérémy Bonnet) 70 | 71 | - Docs: Add notes to INSTALL for the man page. (James Briggs) 72 | 73 | - Docs: Fix hatop(1) man page and document the new hotkey footer. 74 | 75 | 76 | HATop 0.7.6 77 | ----------- 78 | 79 | :Date: Aug 20, 2010 80 | 81 | - Bugfix: Support terminals lacking different cursor visibilities. 82 | (Matt Behrens) 83 | 84 | - Bugfix: Handle empty or incomplete info and stat data. 85 | 86 | - Bugfix: Handle unknown proxy names with the -p / --proxy filter options. 87 | 88 | - Docs: Add initial hatop(1) man page 89 | 90 | 91 | HATop 0.7.5 92 | ----------- 93 | 94 | :Date: Aug 18, 2010 95 | 96 | - Bugfix: Pressing ENTER on the embedded CLI could result in display 97 | corruption. (Cyril Bonté) 98 | 99 | - Docs: Add common packaging files CHANGES and INSTALL 100 | 101 | - Docs: Add keybind reference in KEYBINDS 102 | 103 | 104 | HATop 0.7.4 105 | ----------- 106 | 107 | :Date: Aug 16, 2010 108 | 109 | - Bugfix: Fix the expected stat CSV format. (Jim Riggs) 110 | 111 | 112 | HATop 0.7.3 113 | ----------- 114 | 115 | :Date: Aug 16, 2010 116 | 117 | - Bugfix: Restore compatibility with Python 2.4 and 2.5. 118 | 119 | 120 | HATop 0.7.2 121 | ----------- 122 | 123 | :Date: Aug 16, 2010 124 | 125 | - Bugfix: Handle socket connections to incompatible HAProxy versions. 126 | 127 | 128 | HATop 0.7.1 129 | ----------- 130 | 131 | :Date: Aug 16, 2010 132 | 133 | - Bugfix: Prevent timeout changes to the internal interactive session used to 134 | query for stats. 135 | 136 | 137 | HATop 0.7.0 138 | ----------- 139 | 140 | :Date: Aug 15, 2010 141 | 142 | - The first public and feature complete version. 143 | 144 | .. vim: tw=78 145 | -------------------------------------------------------------------------------- /HACKING: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2011 John Feuerstein 2 | # HATop hacking... 3 | 4 | Development: https://github.com/jhunt/hatop 5 | 6 | Git: git clone https://github.com/jhunt/hatop.git 7 | 8 | 9 | 10 | *** Screen coordinates: 11 | 12 | xmin (0) xmax (>=78) 13 | | | 14 | | | stat 15 | ymin ----+------------------ header ---------------------| idx 16 | (0) | | 17 | | | 0 18 | | info display | [..] 19 | | | 42 20 | | | 43 21 | hpos ----|------------------ columns --------------------| 44 22 | | | 45 23 | = smin ====|= 0.- cmin ===================================|==== 46 = vmin 24 | ^ | 1 \ | 47 25 | | | 2 | | 48 26 | | | 3 | | 49 27 | | | 4 |-> screen lines | 50 28 | |-> span | 5 | | 51 29 | | | 6 | | 52 30 | | | 7 | stat display | 53 31 | | | 8 | | 54 32 | | | 9 | | 55 33 | | | 10 | | 56 34 | | cpos ----|- 11 | ------------ cursor --------------------|---- 57 - vpos 35 | | | 12 | | 58 36 | | | 13 | | 59 37 | | | 14 | | 60 38 | | | 15 / | 61 39 | = smax ====|= 16'- cmax ===================================|==== 62 - vmax 40 | | | 63 41 | ymax ----+------------------- footer --------------------' [..] 42 | (>=20) 43 | 44 | 45 | Smin/max = Screen position 46 | Cmin/max/pos = Curser position 47 | Vmin/max/pos = Virtual position 48 | 49 | 50 | Dynamic positions: 51 | 52 | smin = hpos + 2 53 | smax = ymax - 2 54 | cmax = smax - smin (or last stat slice from vmin to end of list) 55 | vpos = vmin + cpos 56 | vmax = vmin + cmax 57 | span = smax - smin 58 | 59 | - stat lines represent the whole set of parsed service stats 60 | - screen lines represent a subset of stat lines which are on screen 61 | 62 | 63 | 64 | *** ScreenCLI INPUT coordinates: 65 | 66 | screen.xmin screen.xmax 67 | . . 68 | . . 69 | | | 70 | | | 71 | | |<---------------- ispan ------------------>| | 72 | | | | | 73 | |imin ipos imax| 74 | | | | | | 75 | | [*****************|*************************]-----> input line 76 | | | | | | (at screen.smax) 77 | +-|-----------------|-------------------------|-+ 78 | | | | 79 | [..., ..., .|., ..., ..., ...,|..., ..., ..., ..., ..., |.., ..., ...] ibuf 80 | | | | | | 81 | | ibmin ibpos ibmax | 82 | | | 83 | |<--------------------------- iblen -------------------------------->| 84 | 85 | 86 | Imin/max/pos = Input position (*on screen*) 87 | IBmin/pos/max = Input buffer position 88 | 89 | -------------------------------------------------------------------------------- /INSTALL.rst: -------------------------------------------------------------------------------- 1 | ************ 2 | Installation 3 | ************ 4 | 5 | HATop is written as a single executable python script file called ``hatop``. 6 | 7 | This allows easy distribution and installation. 8 | 9 | :Package maintainers: 10 | 11 | Please use "hatop" for the final package and executable name. 12 | 13 | This allows users on different platforms to find it easily. 14 | 15 | 16 | Requirements 17 | ============ 18 | 19 | **HATop is written in pure Python and has no external dependencies!** 20 | 21 | * `Python 2.4 `_ or later (no Python 3 support planned yet) 22 | * `HAProxy 1.4 `_ or later 23 | 24 | 25 | Installation 26 | ============ 27 | 28 | The installation is simple:: 29 | 30 | $ install -m 755 bin/hatop /usr/local/bin 31 | 32 | $ install -m 644 man/hatop.1 /usr/local/share/man/man1/ 33 | $ gzip /usr/local/share/man/man1/hatop.1 34 | 35 | 36 | Permissions 37 | =========== 38 | 39 | HATop itself can be used by any system user. 40 | 41 | The permission to connect to a given HAProxy instance is controlled 42 | by the file permission of the unix socket file. 43 | 44 | HATop needs ``read`` and ``write`` access (``chmod +rw``) on the socket file. 45 | 46 | The initial socket file permissions can be configured in haproxy.conf using 47 | the ``user``, ``group`` and ``mode`` parameters of the ``stats socket`` option. 48 | 49 | -------------------------------------------------------------------------------- /KEYBINDS: -------------------------------------------------------------------------------- 1 | ***************** 2 | Keybind Reference 3 | ***************** 4 | 5 | Global keybinds 6 | =============== 7 | :: 8 | 9 | Key Action 10 | 11 | Hh? Display this help screen 12 | CTRL-C / Qq Quit 13 | 14 | TAB Cycle mode forwards 15 | SHIFT-TAB Cycle mode backwards 16 | ALT-n / ESC-n Switch to mode n, where n is the numeric mode id 17 | ESC-ESC Jump to previous mode 18 | 19 | ENTER Display hotkey menu for selected service 20 | SPACE Copy and paste selected service identifier to the CLI 21 | 22 | You can scroll the stat views using UP / DOWN / PGUP / PGDOWN / HOME / END. 23 | 24 | 25 | Hotkeys for common administrative actions 26 | ========================================= 27 | :: 28 | 29 | Hotkey Action 30 | F1 Enable server on all backends (return from maintenance mode) 31 | F2 Disable server on all backends (put into maintenance mode) 32 | F3 Drain server on all backends (prepare for maintenance mode, don't allow new connections) 33 | 34 | F4 Restore initial server weight 35 | 36 | F5 Decrease server weight: - 10 37 | F6 Decrease server weight: - 1 38 | F7 Increase server weight: + 1 39 | F8 Increase server weight: + 10 40 | 41 | F9 Enable server on one backend (return from maintenance mode) 42 | F10 Disable server on one backend (put into maintenance mode) 43 | F11 Drain server on one backend (prepare for maintenance mode, don't allow new connections) 44 | 45 | Hotkey actions and server responses are logged on the CLI viewport. 46 | 47 | 48 | Keybinds for the command line interface 49 | ======================================= 50 | :: 51 | 52 | Key Action 53 | 54 | ALT-n / ESC-n escape the shell and display given viewport 55 | 56 | ENTER execute cmdline or display marker if input empty 57 | 58 | UP / DOWN scroll input history up or down 59 | LEFT / RIGHT move input cursor one character to the left or right 60 | HOME / END move input cursor to the beginning or end of line 61 | BACKSPACE / DEL delete one character backwards or forwards 62 | 63 | PGUP / PGDOWN scroll output history up or down 64 | 65 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ************************************************* 2 | HATop - An Interactive ncurses Client for HAProxy 3 | ************************************************* 4 | 5 | HATop is an interactive ncurses client and real-time monitoring, 6 | statistics displaying tool for the HAProxy TCP/HTTP load balancer. 7 | 8 | HATop's appearance is similar to top(1). It supports various modes 9 | for detailed statistics of all configured proxies and services in near 10 | realtime. In addition, it features an interactive CLI for the haproxy 11 | unix socket. This allows administrators to control the given haproxy 12 | instance (change server weight, put servers into maintenance mode, ...) 13 | directly out of hatop and monitor the results immediately. 14 | 15 | *It is important to understand that when multiple haproxy processes are started 16 | on the same socket, any process may pick up the request and thus hatop will 17 | output stats owned solely by that process. The current haproxy-internal 18 | process id is displayed top right.* 19 | 20 | 21 | Installation 22 | ============ 23 | 24 | See ``INSTALL`` or refer to :ref:`install` 25 | 26 | 27 | Command line options 28 | ==================== 29 | 30 | Invoking hatop without options or with ``-h / --help`` results in: 31 | 32 | :: 33 | 34 | $ hatop --help 35 | Usage: hatop (-s SOCKET| -t HOST:PORT) [OPTIONS]... 36 | 37 | Options: 38 | --version show program's version number and exit 39 | -h, --help show this help message and exit 40 | 41 | Mandatory: 42 | -s SOCKET, --unix-socket=SOCKET 43 | path to the haproxy unix socket 44 | -t TCP_SOCKET, --tcp-socket=TCP_SOCKET 45 | address of the haproxy tcp stats socket 46 | 47 | Optional: 48 | -i INTERVAL, --update-interval=INTERVAL 49 | update interval in seconds (1-30, default: 3) 50 | -m MODE, --mode=MODE 51 | start in specific mode (1-5, default: 1) 52 | -n, --read-only disable the cli and query for stats only 53 | 54 | Filters: 55 | Note: All filter options may be given multiple times. 56 | 57 | -f FILTER, --filter=FILTER 58 | stat filter in format " " 59 | -p PROXY, --proxy=PROXY 60 | proxy filter in format "" 61 | 62 | 63 | Display mode reference 64 | ====================== 65 | 66 | See also: :ref:`screenshots` 67 | 68 | :: 69 | 70 | ID Mode Description 71 | 72 | 1 STATUS The default mode with health, session and queue statistics 73 | 2 TRAFFIC Display connection and request rates as well as traffic stats 74 | 3 HTTP Display various statistical information related to HTTP 75 | 4 ERRORS Display health info, various error counters and downtimes 76 | 5 CLI Display embedded command line client for the unix socket 77 | 78 | 79 | Keybind reference 80 | ================= 81 | 82 | See also: :ref:`keybinds` 83 | 84 | :: 85 | 86 | Key Action 87 | 88 | Hh? Display this help screen 89 | CTRL-C / Qq Quit 90 | 91 | TAB Cycle mode forwards 92 | SHIFT-TAB Cycle mode backwards 93 | ALT-n / ESC-n Switch to mode n, where n is the numeric mode id 94 | ESC-ESC Jump to previous mode 95 | 96 | ENTER Display hotkey menu for selected service 97 | SPACE Copy and paste selected service identifier to the CLI 98 | 99 | You can scroll the stat views using ``UP / DOWN / PGUP / PGDOWN / HOME / END``. 100 | 101 | The reverse colored cursor line is used to select a given service instance. 102 | 103 | An unique identifier ``[#/<#sid>]`` of the selected 104 | service is displayed bottom right. 105 | 106 | You can hit ``SPACE`` to copy and paste the identifier in string format 107 | ``pxname/svname`` to the CLI for easy re-use with some commands. 108 | 109 | For example: 110 | 111 | 1. Open the CLI 112 | 2. Type "disable server " 113 | 3. Switch back to some stat view using TAB / SHIFT-TAB 114 | 4. Select the server instance using UP / DOWN 115 | 5. Hit SPACE 116 | 117 | The result is this command line:: 118 | 119 | > disable server / 120 | 121 | Hotkeys for common administrative actions 122 | ----------------------------------------- 123 | :: 124 | 125 | Hotkey Action 126 | F1 Enable server on all backends (return from maintenance mode) 127 | F2 Disable server on all backends (put into maintenance mode) 128 | F3 Drain server on all backends (prepare for maintenance mode, don't allow new connections) 129 | 130 | F4 Restore initial server weight 131 | 132 | F5 Decrease server weight: - 10 133 | F6 Decrease server weight: - 1 134 | F7 Increase server weight: + 1 135 | F8 Increase server weight: + 10 136 | 137 | F9 Enable server on one backend (return from maintenance mode) 138 | F10 Disable server on one backend (put into maintenance mode) 139 | F11 Drain server on one backend (prepare for maintenance mode, don't allow new connections) 140 | 141 | Hotkey actions and server responses are logged on the CLI viewport. 142 | 143 | You can scroll the output on the CLI view using ``PGUP / PGDOWN``. 144 | 145 | A brief keybind reference is logged there directly after startup... 146 | 147 | 148 | Header reference 149 | ================ 150 | 151 | See also: :ref:`screenshots` 152 | 153 | :: 154 | 155 | Node configured name of the haproxy node 156 | Uptime runtime since haproxy was initially started 157 | Pipes pipes are currently used for kernel-based tcp slicing 158 | Procs number of haproxy processes 159 | Tasks number of actice process tasks 160 | Queue number of queued process tasks (run queue) 161 | Proxies number of configured proxies 162 | Services number of configured services 163 | 164 | In multiple modes 165 | ----------------- 166 | :: 167 | 168 | NAME name of the proxy and its services 169 | W configured weight of the service 170 | STATUS service status (UP/DOWN/NOLB/MAINT/MAINT(via)...) 171 | CHECK status of last health check (see status reference below) 172 | 173 | In STATUS mode 174 | -------------- 175 | :: 176 | 177 | ACT server is active (server), number of active servers (backend) 178 | BCK server is backup (server), number of backup servers (backend) 179 | QCUR current queued requests 180 | QMAX max queued requests 181 | SCUR current sessions 182 | SMAX max sessions 183 | SLIM sessions limit 184 | STOT total sessions 185 | 186 | In TRAFFIC mode 187 | --------------- 188 | :: 189 | 190 | LBTOT total number of times a server was selected 191 | RATE number of sessions per second over last elapsed second 192 | RLIM limit on new sessions per second 193 | RMAX max number of new sessions per second 194 | BIN bytes in (IEEE 1541-2002) 195 | BOUT bytes out (IEEE 1541-2002) 196 | 197 | In HTTP mode 198 | ------------ 199 | :: 200 | 201 | RATE HTTP requests per second over last elapsed second 202 | RMAX max number of HTTP requests per second observed 203 | RTOT total number of HTTP requests received 204 | 1xx number of HTTP responses with 1xx code 205 | 2xx number of HTTP responses with 2xx code 206 | 3xx number of HTTP responses with 3xx code 207 | 4xx number of HTTP responses with 4xx code 208 | 5xx number of HTTP responses with 5xx code 209 | ?xx number of HTTP responses with other codes (protocol error) 210 | 211 | In ERRORS mode 212 | -------------- 213 | :: 214 | 215 | CF number of failed checks 216 | CD number of UP->DOWN transitions 217 | CL last status change 218 | ECONN connection errors 219 | EREQ request errors 220 | ERSP response errors 221 | DREQ denied requests 222 | DRSP denied responses 223 | DOWN total downtime 224 | 225 | 226 | Health check status reference 227 | ============================= 228 | :: 229 | 230 | UNK unknown 231 | INI initializing 232 | SOCKERR socket error 233 | L4OK check passed on layer 4, no upper layers testing enabled 234 | L4TMOUT layer 1-4 timeout 235 | L4CON layer 1-4 connection problem, for example 236 | "Connection refused" (tcp rst) or "No route to host" (icmp) 237 | L6OK check passed on layer 6 238 | L6TOUT layer 6 (SSL) timeout 239 | L6RSP layer 6 invalid response - protocol error 240 | L7OK check passed on layer 7 241 | L7OKC check conditionally passed on layer 7, for example 404 with 242 | disable-on-404 243 | L7TOUT layer 7 (HTTP/SMTP) timeout 244 | L7RSP layer 7 invalid response - protocol error 245 | L7STS layer 7 response error, for example HTTP 5xx 246 | 247 | 248 | Authors 249 | ======= 250 | 251 | HATop was originally written by John Feuerstein , 252 | known on GitHub as @feurix. 253 | 254 | As of 2020, however, support for Python 2.x is being phased out 255 | of modern distributions of Linux, the last code interaction on the 256 | upstream repository () is from 257 | over four years ago, and no issue or pull request has been able to 258 | elicit a response from the author. 259 | 260 | As of February 29th (2020), I have forked this repository into my own 261 | GitHub org, at , with the intent 262 | of merging some of the upstream pull requests, and continuing 263 | ongoing maintenance of this tool. 264 | 265 | I have been an avid user of HATop since I first discovered it many 266 | many years ago, and would like to continue to be able to use it 267 | for many many more. 268 | 269 | Contributors 270 | ============ 271 | 272 | The following people have contributed to HATop: 273 | 274 | - Andrew Hayworth 275 | - Cyril Bonté 276 | - James Hunt 277 | - John Feuerstein 278 | - Louis Charreau 279 | - Matt Behrens 280 | -------------------------------------------------------------------------------- /bin/hatop: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # vim:ft=python 3 | # 4 | # Copyright (C) 2011 John Feuerstein 5 | # Copyright (C) 2022 James Hunt 6 | # 7 | # Project URL: https://github.com/jhunt/hatop 8 | # 9 | # This program is free software; you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation; either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU Library General Public License for more details. 18 | # 19 | # You should have received a copy of the GNU General Public License 20 | # along with this program; if not, write to the Free Software 21 | # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 22 | # 23 | '''\ 24 | HATop is an interactive ncurses client for HAProxy 25 | ================================================== 26 | 27 | Display mode reference: 28 | 29 | ID Mode Description 30 | 31 | 1 STATUS The default mode with health, session and queue statistics 32 | 2 TRAFFIC Display connection and request rates as well as traffic stats 33 | 3 HTTP Display various statistical information related to HTTP 34 | 4 ERRORS Display health info, various error counters and downtimes 35 | 5 CLI Display embedded command line client for the unix socket 36 | 37 | Keybind reference: 38 | 39 | Key Action 40 | 41 | Hh? Display this help screen 42 | CTRL-C / Qq Quit 43 | 44 | TAB Cycle mode forwards 45 | SHIFT-TAB Cycle mode backwards 46 | ALT-n / ESC-n Switch to mode n, where n is the numeric mode id 47 | ESC-ESC Jump to previous mode 48 | 49 | ENTER Display hotkey menu for selected service 50 | SPACE Copy and paste selected service identifier to the CLI 51 | 52 | You can scroll the stat views using UP / DOWN / PGUP / PGDOWN / HOME / END. 53 | 54 | The reverse colored cursor line is used to select a given service instance. 55 | 56 | Some common administrative actions have hotkeys: 57 | 58 | Hotkey Action 59 | 60 | F1 Enable server on all backends (return from maintenance mode) 61 | F2 Disable server on all backends (put into maintenance mode) 62 | F3 Drain server on all backends (prepare for maintenance mode, don't allow new connections) 63 | 64 | F4 Restore initial server weight 65 | 66 | F5 Decrease server weight: - 10 67 | F6 Decrease server weight: - 1 68 | F7 Increase server weight: + 1 69 | F8 Increase server weight: + 10 70 | 71 | F9 Enable server on one backend (return from maintenance mode) 72 | F10 Disable server on one backend (put into maintenance mode) 73 | F11 Drain server on one backend (prepare for maintenance mode, don't allow new connections) 74 | 75 | Hotkey actions and server responses are logged on the CLI viewport. 76 | You can scroll the output on the CLI view using PGUP / PGDOWN. 77 | 78 | Header reference: 79 | 80 | Node configured name of the haproxy node 81 | Uptime runtime since haproxy was initially started 82 | Pipes pipes are currently used for kernel-based tcp slicing 83 | Procs number of haproxy processes 84 | Tasks number of actice process tasks 85 | Queue number of queued process tasks (run queue) 86 | Proxies number of configured proxies 87 | Services number of configured services 88 | 89 | In multiple modes: 90 | 91 | NAME name of the proxy and his services 92 | W configured weight of the service 93 | STATUS service status (UP/DOWN/NOLB/MAINT/MAINT(via)...) 94 | CHECK status of last health check (see status reference below) 95 | 96 | In STATUS mode: 97 | 98 | ACT server is active (server), number of active servers (backend) 99 | BCK server is backup (server), number of backup servers (backend) 100 | QCUR current queued requests 101 | QMAX max queued requests 102 | SCUR current sessions 103 | SMAX max sessions 104 | SLIM sessions limit 105 | STOT total sessions 106 | 107 | In TRAFFIC mode: 108 | 109 | LBTOT total number of times a server was selected 110 | RATE number of sessions per second over last elapsed second 111 | RLIM limit on new sessions per second 112 | RMAX max number of new sessions per second 113 | BIN bytes in (IEEE 1541-2002) 114 | BOUT bytes out (IEEE 1541-2002) 115 | 116 | In HTTP mode: 117 | 118 | RATE HTTP requests per second over last elapsed second 119 | RMAX max number of HTTP requests per second observed 120 | RTOT total number of HTTP requests received 121 | 1xx number of HTTP responses with 1xx code 122 | 2xx number of HTTP responses with 2xx code 123 | 3xx number of HTTP responses with 3xx code 124 | 4xx number of HTTP responses with 4xx code 125 | 5xx number of HTTP responses with 5xx code 126 | ?xx number of HTTP responses with other codes (protocol error) 127 | 128 | In ERRORS mode: 129 | 130 | CF number of failed checks 131 | CD number of UP->DOWN transitions 132 | CL last status change 133 | ECONN connection errors 134 | EREQ request errors 135 | ERSP response errors 136 | DREQ denied requests 137 | DRSP denied responses 138 | DOWN total downtime 139 | 140 | Health check status reference: 141 | 142 | UNK unknown 143 | INI initializing 144 | SOCKERR socket error 145 | L4OK check passed on layer 4, no upper layers testing enabled 146 | L4TMOUT layer 1-4 timeout 147 | L4CON layer 1-4 connection problem, for example 148 | "Connection refused" (tcp rst) or "No route to host" (icmp) 149 | L6OK check passed on layer 6 150 | L6TOUT layer 6 (SSL) timeout 151 | L6RSP layer 6 invalid response - protocol error 152 | L7OK check passed on layer 7 153 | L7OKC check conditionally passed on layer 7, for example 404 with 154 | disable-on-404 155 | L7TOUT layer 7 (HTTP/SMTP) timeout 156 | L7RSP layer 7 invalid response - protocol error 157 | L7STS layer 7 response error, for example HTTP 5xx 158 | ''' 159 | __author__ = 'John Feuerstein ' 160 | __copyright__ = 'Copyright (C) 2011 %s' % __author__ 161 | __license__ = 'GNU GPLv3' 162 | __version__ = '0.8.3' 163 | 164 | import fcntl 165 | import os 166 | import re 167 | import signal 168 | import socket 169 | import struct 170 | import sys 171 | import time 172 | import tty 173 | 174 | import curses 175 | import curses.ascii 176 | 177 | from socket import error as SocketError 178 | from _curses import error as CursesError 179 | 180 | from collections import deque 181 | from textwrap import TextWrapper 182 | 183 | # ------------------------------------------------------------------------- # 184 | # GLOBALS # 185 | # ------------------------------------------------------------------------- # 186 | 187 | # Settings of interactive command session over the unix-socket 188 | HAPROXY_CLI_BUFSIZE = 4096 189 | HAPROXY_CLI_TIMEOUT = 60 190 | HAPROXY_CLI_PROMPT = '> ' 191 | HAPROXY_CLI_CMD_SEP = ';' 192 | HAPROXY_CLI_CMD_TIMEOUT = 1 193 | HAPROXY_CLI_MAXLINES = 1000 194 | 195 | # Settings of the embedded CLI 196 | CLI_MAXLINES = 1000 197 | CLI_MAXHIST = 100 198 | CLI_INPUT_LIMIT = 200 199 | CLI_INPUT_RE = re.compile(r'[a-zA-Z0-9_:\.\-\+; /#%]') 200 | CLI_INPUT_DENY_CMD = ['prompt', 'set timeout cli', 'quit'] 201 | 202 | # Note: Only the last 3 lines are visible instantly on 80x25 203 | CLI_HELP_TEXT = '''\ 204 | Welcome on the embedded interactive HAProxy shell! 205 | 206 | Type `help' to get a command reference 207 | ''' 208 | 209 | # Screen setup 210 | SCREEN_XMIN = 78 211 | SCREEN_YMIN = 20 212 | SCREEN_XMAX = 200 213 | SCREEN_YMAX = 100 214 | SCREEN_HPOS = 11 215 | 216 | HAPROXY_INFO_RE = { 217 | 'software_name': re.compile(r'^Name:\s*(?P\S+)'), 218 | 'software_version': re.compile(r'^Version:\s*(?P\S+)'), 219 | 'software_release': re.compile(r'^Release_date:\s*(?P\S+)'), 220 | 'nproc': re.compile(r'^Nbproc:\s*(?P\d+)'), 221 | 'procn': re.compile(r'^Process_num:\s*(?P\d+)'), 222 | 'pid': re.compile(r'^Pid:\s*(?P\d+)'), 223 | 'uptime': re.compile(r'^Uptime:\s*(?P[\S ]+)$'), 224 | 'maxconn': re.compile(r'^Maxconn:\s*(?P\d+)'), 225 | 'curconn': re.compile(r'^CurrConns:\s*(?P\d+)'), 226 | 'maxpipes': re.compile(r'^Maxpipes:\s*(?P\d+)'), 227 | 'curpipes': re.compile(r'^PipesUsed:\s*(?P\d+)'), 228 | 'tasks': re.compile(r'^Tasks:\s*(?P\d+)'), 229 | 'runqueue': re.compile(r'^Run_queue:\s*(?P\d+)'), 230 | 'node': re.compile(r'^node:\s*(?P\S+)'), 231 | } 232 | 233 | HAPROXY_STAT_MAX_SERVICES = 1000 234 | HAPROXY_STAT_LIMIT_WARNING = '''\ 235 | Warning: You have reached the stat parser limit! (%d) 236 | Use --filter to parse specific service stats only. 237 | ''' % HAPROXY_STAT_MAX_SERVICES 238 | HAPROXY_STAT_FILTER_RE = re.compile( 239 | r'^(?P-?\d+)\s+(?P-?\d+)\s+(?P-?\d+)$') 240 | HAPROXY_STAT_PROXY_FILTER_RE = re.compile( 241 | r'^(?P[a-zA-Z0-9_:\.\-]+)$') 242 | HAPROXY_STAT_COMMENT = '#' 243 | HAPROXY_STAT_SEP = ',' 244 | HAPROXY_STAT_CSV = [ 245 | # Note: Fields must be listed in correct order, as described in: 246 | # http://haproxy.1wt.eu/download/1.4/doc/configuration.txt [9.1] 247 | 248 | # TYPE FIELD 249 | 250 | (str, 'pxname'), # proxy name 251 | (str, 'svname'), # service name (FRONTEND / BACKEND / name) 252 | (int, 'qcur'), # current queued requests 253 | (int, 'qmax'), # max queued requests 254 | (int, 'scur'), # current sessions 255 | (int, 'smax'), # max sessions 256 | (int, 'slim'), # sessions limit 257 | (int, 'stot'), # total sessions 258 | (int, 'bin'), # bytes in 259 | (int, 'bout'), # bytes out 260 | (int, 'dreq'), # denied requests 261 | (int, 'dresp'), # denied responses 262 | (int, 'ereq'), # request errors 263 | (int, 'econ'), # connection errors 264 | (int, 'eresp'), # response errors (among which srv_abrt) 265 | (int, 'wretr'), # retries (warning) 266 | (int, 'wredis'), # redispatches (warning) 267 | (str, 'status'), # status (UP/DOWN/NOLB/MAINT/MAINT(via)...) 268 | (int, 'weight'), # server weight (server), total weight (backend) 269 | (int, 'act'), # server is active (server), 270 | # number of active servers (backend) 271 | (int, 'bck'), # server is backup (server), 272 | # number of backup servers (backend) 273 | (int, 'chkfail'), # number of failed checks 274 | (int, 'chkdown'), # number of UP->DOWN transitions 275 | (int, 'lastchg'), # last status change (in seconds) 276 | (int, 'downtime'), # total downtime (in seconds) 277 | (int, 'qlimit'), # queue limit 278 | (int, 'pid'), # process id 279 | (int, 'iid'), # unique proxy id 280 | (int, 'sid'), # service id (unique inside a proxy) 281 | (int, 'throttle'), # warm up status 282 | (int, 'lbtot'), # total number of times a server was selected 283 | (str, 'tracked'), # id of proxy/server if tracking is enabled 284 | (int, 'type'), # (0=frontend, 1=backend, 2=server, 3=socket) 285 | (int, 'rate'), # number of sessions per second 286 | # over the last elapsed second 287 | (int, 'rate_lim'), # limit on new sessions per second 288 | (int, 'rate_max'), # max number of new sessions per second 289 | (str, 'check_status'), # status of last health check 290 | (int, 'check_code'), # layer5-7 code, if available 291 | (int, 'check_duration'), # time in ms took to finish last health check 292 | (int, 'hrsp_1xx'), # http responses with 1xx code 293 | (int, 'hrsp_2xx'), # http responses with 2xx code 294 | (int, 'hrsp_3xx'), # http responses with 3xx code 295 | (int, 'hrsp_4xx'), # http responses with 4xx code 296 | (int, 'hrsp_5xx'), # http responses with 5xx code 297 | (int, 'hrsp_other'), # http responses with other codes (protocol error) 298 | (str, 'hanafail'), # failed health checks details 299 | (int, 'req_rate'), # HTTP requests per second 300 | (int, 'req_rate_max'), # max number of HTTP requests per second 301 | (int, 'req_tot'), # total number of HTTP requests received 302 | (int, 'cli_abrt'), # number of data transfers aborted by client 303 | (int, 'srv_abrt'), # number of data transfers aborted by server 304 | ] 305 | HAPROXY_STAT_NUMFIELDS = len(HAPROXY_STAT_CSV) 306 | HAPROXY_STAT_CSV = [(k, v) for k, v in enumerate(HAPROXY_STAT_CSV)] 307 | 308 | # All big numeric values on the screen are prefixed using the metric prefix 309 | # set, while everything byte related is prefixed using binary prefixes. 310 | # Note: If a non-byte numeric value fits into the field, we skip prefixing. 311 | PREFIX_BINARY = { 312 | 1024: 'K', 313 | 1024**2: 'M', 314 | } 315 | PREFIX_METRIC = { 316 | 1000: 'k', 317 | 1000**2: 'M', 318 | 1000**3: 'G', 319 | } 320 | PREFIX_TIME = { 321 | 60: 'm', 322 | 60*60: 'h', 323 | 60*60*24:'d', 324 | } 325 | 326 | # ------------------------------------------------------------------------- # 327 | # CLASS DEFINITIONS # 328 | # ------------------------------------------------------------------------- # 329 | 330 | # Use bounded length deque if available (Python 2.6+) 331 | try: 332 | deque(maxlen=0) 333 | 334 | class RingBuffer(deque): 335 | 336 | def __init__(self, maxlen): 337 | assert maxlen > 0 338 | deque.__init__(self, maxlen=maxlen) 339 | 340 | except TypeError: 341 | 342 | class RingBuffer(deque): 343 | 344 | def __init__(self, maxlen): 345 | assert maxlen > 0 346 | deque.__init__(self) 347 | self.maxlen = maxlen 348 | 349 | def append(self, item): 350 | if len(self) == self.maxlen: 351 | self.popleft() 352 | deque.append(self, item) 353 | 354 | def appendleft(self, item): 355 | if len(self) == self.maxlen: 356 | self.popright() 357 | deque.appendleft(self, item) 358 | 359 | def extend(self, iterable): 360 | for item in iterable: 361 | self.append(item) 362 | 363 | def extendleft(self, iterable): 364 | for item in iterable: 365 | self.appendleft(item) 366 | 367 | 368 | class Socket: 369 | 370 | def __init__(self, path, readonly=False, tcp=False): 371 | self.path = path 372 | self.ro = readonly 373 | self.tcp = tcp 374 | if not self.tcp: 375 | self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 376 | else: 377 | self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 378 | 379 | def _recv(self): 380 | # socket.recv() wrapper raising SocketError if we receive 381 | # EOF before seeing the interactive socket prompt. 382 | data = self._socket.recv(HAPROXY_CLI_BUFSIZE) 383 | if not data: 384 | raise SocketError('error while waiting for prompt') 385 | return data.decode() 386 | 387 | def connect(self): 388 | # Initialize socket connection 389 | self._socket.settimeout(HAPROXY_CLI_CMD_TIMEOUT) 390 | if self.tcp: 391 | host, port = self.path.split(":") 392 | self._socket.connect((host, int(port))) 393 | else: 394 | self._socket.connect(self.path) 395 | 396 | # Enter the interactive socket mode. This requires HAProxy 1.4+ and 397 | # allows us to error out early if connected to an older version. 398 | try: 399 | self.send(b'prompt') 400 | self.wait() 401 | self.send(b'set timeout cli %d' % HAPROXY_CLI_TIMEOUT) 402 | self.wait() 403 | except SocketError: 404 | raise SocketError('error while initializing interactive mode') 405 | 406 | def close(self): 407 | try: 408 | self.send(b'quit') 409 | except: 410 | pass 411 | try: 412 | self._socket.close() 413 | except: 414 | pass 415 | 416 | def send(self, cmdline): 417 | self._socket.sendall(b'%s\n' % cmdline) 418 | 419 | def wait(self): 420 | # Wait for the prompt and discard data. 421 | rbuf = '' 422 | while not rbuf.endswith(HAPROXY_CLI_PROMPT): 423 | data = self._recv() 424 | rbuf = rbuf[-(len(HAPROXY_CLI_PROMPT)-1):] + data 425 | 426 | def recv(self): 427 | # Receive lines until HAPROXY_CLI_MAXLINES or the prompt is reached. 428 | # If the prompt was still not found, discard data and wait for it. 429 | linecount = 0 430 | rbuf = '' 431 | while not rbuf.endswith(HAPROXY_CLI_PROMPT): 432 | 433 | if linecount == HAPROXY_CLI_MAXLINES: 434 | data = self._recv() 435 | rbuf = rbuf[-(len(HAPROXY_CLI_PROMPT)-1):] + data 436 | continue 437 | 438 | data = self._recv() 439 | rbuf += data 440 | 441 | while linecount < HAPROXY_CLI_MAXLINES and '\n' in rbuf: 442 | line, rbuf = rbuf.split('\n', 1) 443 | linecount += 1 444 | yield line 445 | 446 | 447 | class SocketData: 448 | 449 | def __init__(self, socket): 450 | self.socket = socket 451 | self.pxcount = 0 452 | self.svcount = 0 453 | self.info = {} 454 | self.stat = {} 455 | self._filters = set() 456 | 457 | def register_stat_filter(self, stat_filter): 458 | 459 | # Validate and register filters 460 | stat_filter_set = set(stat_filter) 461 | for filter in stat_filter_set: 462 | match = HAPROXY_STAT_FILTER_RE.match(filter) 463 | if not match: 464 | raise ValueError('invalid stat filter: %s' % filter) 465 | self._filters.add(( 466 | int(match.group('iid'), 10), 467 | int(match.group('type'), 10), 468 | int(match.group('sid'), 10), 469 | )) 470 | 471 | def register_proxy_filter(self, proxy_filter): 472 | 473 | # Validate filters 474 | proxy_filter_set = set(proxy_filter) 475 | for filter in proxy_filter_set: 476 | if not HAPROXY_STAT_PROXY_FILTER_RE.match(filter): 477 | raise ValueError('invalid proxy filter: %s' % filter) 478 | 479 | # Convert proxy filters into more efficient stat filters 480 | self.socket.send(b'show stat') 481 | pxstat, pxcount, svcount = parse_stat(self.socket.recv()) 482 | 483 | proxy_iid_map = {} # {pxname: iid, ...} 484 | 485 | for pxname in proxy_filter_set: 486 | for iid in pxstat: 487 | for sid in pxstat[iid]: 488 | if pxstat[iid][sid]['pxname'] == pxname: 489 | proxy_iid_map[pxname] = iid 490 | break 491 | if pxname in proxy_iid_map: 492 | break 493 | 494 | for pxname in proxy_filter_set: 495 | if not pxname in proxy_iid_map: 496 | raise RuntimeError('proxy not found: %s' % pxname) 497 | 498 | # Register filters 499 | for iid in proxy_iid_map.values(): 500 | self._filters.add((iid, -1, -1)) 501 | 502 | def update_info(self): 503 | self.socket.send(b'show info') 504 | iterable = self.socket.recv() 505 | self.info = parse_info(iterable) 506 | 507 | def update_stat(self): 508 | # Store current data 509 | pxcount_old = self.pxcount 510 | svcount_old = self.svcount 511 | stat_old = self.stat 512 | 513 | # Reset current data 514 | self.pxcount = 0 515 | self.svcount = 0 516 | self.stat = {} 517 | 518 | if self._filters: 519 | for filter in self._filters: 520 | self.socket.send(b'show stat %d %d %d' % filter) 521 | filter_stat, filter_pxcount, filter_svcount = \ 522 | parse_stat(self.socket.recv()) 523 | 524 | if filter_pxcount == 0: 525 | raise RuntimeError('stale stat filter: %d %d %d' % filter) 526 | 527 | self.pxcount += filter_pxcount 528 | self.svcount += filter_svcount 529 | self.stat.update(filter_stat) 530 | else: 531 | self.socket.send(b'show stat') 532 | self.stat, self.pxcount, self.svcount = \ 533 | parse_stat(self.socket.recv()) 534 | 535 | if self.pxcount == 0: 536 | raise RuntimeWarning('no stat data available') 537 | 538 | # Warn if the HAProxy configuration has changed on-the-fly 539 | pxdiff = 0 540 | svdiff = 0 541 | 542 | if self.pxcount < pxcount_old: 543 | pxdiff -= pxcount_old - self.pxcount 544 | if pxcount_old > 0 and self.pxcount > pxcount_old: 545 | pxdiff += self.pxcount - pxcount_old 546 | if self.svcount < svcount_old: 547 | svdiff -= svcount_old - self.svcount 548 | if svcount_old > 0 and self.svcount > svcount_old: 549 | svdiff += self.svcount - svcount_old 550 | 551 | if pxdiff != 0 or svdiff != 0: 552 | raise RuntimeWarning( 553 | 'config changed: proxy %+d, service %+d ' 554 | '(reloading...)' % (pxdiff, svdiff)) 555 | 556 | 557 | class ScreenCLI: 558 | 559 | def __init__(self, screen): 560 | self.screen = screen 561 | 562 | # Output 563 | self.obuf = RingBuffer(CLI_MAXLINES) 564 | self.ypos = 0 565 | self.wrapper = TextWrapper() 566 | self.screenlines = [] 567 | 568 | # Input 569 | self.ihist = RingBuffer(CLI_MAXHIST) 570 | self.ibuf = [] 571 | self.ibpos = 0 572 | self.ibmin = 0 573 | 574 | 575 | # INPUT 576 | @property 577 | def imin(self): 578 | return self.screen.xmin + 2 579 | 580 | @property 581 | def imax(self): 582 | return self.screen.xmax - 4 583 | 584 | @property 585 | def ispan(self): 586 | return self.imax - self.imin 587 | 588 | @property 589 | def ipos(self): 590 | return self.ibpos - self.ibmin 591 | 592 | @property 593 | def ibmax(self): 594 | return self.ibmin + self.ispan 595 | 596 | @property 597 | def iblen(self): 598 | return len(self.ibuf) 599 | 600 | @property 601 | def cmdline(self): 602 | return ''.join(self.ibuf) 603 | 604 | # OUTPUT 605 | @property 606 | def ospan(self): 607 | return self.screen.span - 1 608 | 609 | 610 | def setup(self): 611 | self.ipad = curses.newpad(1, SCREEN_XMAX) # input 612 | self.opad = curses.newpad(SCREEN_YMAX, SCREEN_XMAX) # output 613 | 614 | # Display initial help text... 615 | self.obuf.extend(CLI_HELP_TEXT.split('\n')) 616 | self.update_screenlines() 617 | 618 | def start(self): 619 | try: 620 | curses.curs_set(1) 621 | except CursesError: 622 | pass 623 | self.draw_output() 624 | self.draw_input() 625 | 626 | def stop(self): 627 | try: 628 | curses.curs_set(0) 629 | except CursesError: 630 | pass 631 | 632 | def update_screenlines(self): 633 | self.wrapper.width = self.screen.xmax 634 | self.screenlines = [] 635 | for line in self.obuf: 636 | if len(line) > self.wrapper.width: 637 | self.screenlines.extend(self.wrapper.wrap(line)) 638 | else: 639 | self.screenlines.append(line) 640 | self.ypos = len(self.screenlines) 641 | 642 | def reset_input(self): 643 | self.ibuf = [] 644 | self.ibpos = 0 645 | self.ibmin = 0 646 | 647 | def refresh_input(self, sync=False): 648 | if sync: 649 | refresh = self.ipad.refresh 650 | else: 651 | refresh = self.ipad.noutrefresh 652 | 653 | refresh(0, 0, 654 | self.screen.smax, self.screen.xmin, 655 | self.screen.smax, self.screen.xmax - 1) 656 | 657 | def refresh_output(self, sync=False): 658 | if sync: 659 | refresh = self.opad.refresh 660 | else: 661 | refresh = self.opad.noutrefresh 662 | 663 | refresh(0, 0, 664 | self.screen.smin, self.screen.xmin, 665 | self.screen.smax - 2, self.screen.xmax - 1) 666 | 667 | def draw_input(self): 668 | self.ipad.clear() 669 | self.ipad.addstr(0, 0, '> ', curses.A_BOLD) 670 | self.ipad.addstr(0, 2, ''.join(self.ibuf[self.ibmin:self.ibmax])) 671 | 672 | # Mark input lines longer than the visible input span 673 | if self.ibmin > 0: 674 | self.ipad.addstr(0, self.imin - 1, '<') 675 | if self.iblen > self.ibmax: 676 | self.ipad.addstr(0, self.imax, '>') 677 | 678 | self.ipad.move(0, self.imin + self.ipos) 679 | 680 | def draw_output(self): 681 | self.opad.clear() 682 | vmin = max(0, self.ypos - self.ospan) 683 | vmax = vmin + self.ospan 684 | lines = self.screenlines[vmin:vmax] 685 | self.opad.addstr(0, 0, '\n'.join(lines)) 686 | 687 | # INPUT 688 | def prev(self): 689 | if len(self.ihist) == 0: 690 | return 691 | if len(self.ibuf) == 0: 692 | self.ibuf = list(self.ihist[-1]) 693 | self.mvend() 694 | return 695 | if self.ibuf != self.ihist[-1]: 696 | self.ihist.append(self.ibuf) 697 | self.ihist.rotate(1) 698 | self.ibuf = list(self.ihist[-1]) 699 | self.mvend() 700 | 701 | def post(self): 702 | if len(self.ihist) == 0: 703 | return 704 | self.ihist.rotate(-1) 705 | self.ibuf = list(self.ihist[-1]) 706 | self.mvend() 707 | 708 | def puts(self, s): 709 | s = list(s) 710 | if len(self.ibuf) + len(s) >= CLI_INPUT_LIMIT: 711 | return 712 | for c in s: 713 | if not CLI_INPUT_RE.match(c): 714 | return 715 | 716 | if self.ibpos < self.iblen: 717 | self.ibuf = self.ibuf[:self.ibpos] + s + self.ibuf[self.ibpos:] 718 | else: 719 | self.ibuf.extend(s) 720 | 721 | self.mvc(len(s)) 722 | return True 723 | 724 | def putc(self, c): 725 | if len(self.ibuf) == CLI_INPUT_LIMIT: 726 | return 727 | if not CLI_INPUT_RE.match(c): 728 | return 729 | 730 | if self.ibpos < self.iblen: 731 | self.ibuf.insert(self.ibpos, c) 732 | else: 733 | self.ibuf.append(c) 734 | 735 | self.mvc(1) 736 | 737 | def delc(self, n): 738 | if n == 0 or self.iblen == 0: 739 | return 740 | 741 | # Delete LEFT 742 | elif n < 0 and self.ibpos >= 1: 743 | self.ibuf.pop(self.ibpos - 1) 744 | self.mvc(-1) 745 | 746 | # Delete RIGHT 747 | elif n > 0 and self.ibpos < self.iblen: 748 | self.ibuf.pop(self.ibpos) 749 | self.draw_input() 750 | self.refresh_input(sync=True) 751 | 752 | def mvhome(self): 753 | self.ibmin = 0 754 | self.ibpos = 0 755 | self.draw_input() 756 | self.refresh_input(sync=True) 757 | 758 | def mvend(self): 759 | self.ibmin = max(0, self.iblen - self.ispan) 760 | self.ibpos = self.iblen 761 | self.draw_input() 762 | self.refresh_input(sync=True) 763 | 764 | def mvc(self, n): 765 | if n == 0: 766 | return 767 | 768 | # Move LEFT 769 | if n < 0: 770 | self.ibpos = max(0, self.ibpos + n) 771 | if self.ibpos < self.ibmin: 772 | self.ibmin = self.ibpos 773 | 774 | # Move RIGHT 775 | elif n > 0: 776 | self.ibpos = min(self.iblen, self.ibpos + n) 777 | if self.ibpos > self.ibmax: 778 | self.ibmin += n 779 | 780 | self.draw_input() 781 | self.refresh_input(sync=True) 782 | 783 | # OUTPUT 784 | def mvo(self, n): 785 | if n == 0: 786 | return 787 | 788 | # Move UP 789 | if n < 0 and self.ypos > self.ospan: 790 | self.ypos = max(self.ospan, self.ypos + n) 791 | 792 | # Move DOWN 793 | elif n > 0 and self.ypos < len(self.screenlines): 794 | self.ypos = min(len(self.screenlines), self.ypos + n) 795 | 796 | self.draw_output() 797 | self.refresh_output(sync=True) 798 | 799 | def execute(self): 800 | 801 | # Nothing to do... print marker line instead. 802 | if self.iblen == 0: 803 | self.obuf.append('- %s %s' % (time.ctime(), '-' * 50)) 804 | self.obuf.append('') 805 | self.update_screenlines() 806 | self.draw_output() 807 | self.refresh_output(sync=True) 808 | self.refresh_input(sync=True) 809 | return 810 | 811 | # Validate each command on the command line 812 | cmds = [cmd.strip() for cmd in 813 | self.cmdline.split(HAPROXY_CLI_CMD_SEP)] 814 | 815 | for pattern in CLI_INPUT_DENY_CMD: 816 | for cmd in cmds: 817 | if re.match(r'^\s*%s(?:\s|$)' % pattern, cmd): 818 | self.obuf.append('* command not allowed: %s' % cmd) 819 | self.obuf.append('') 820 | self.update_screenlines() 821 | self.draw_output() 822 | self.refresh_output(sync=True) 823 | self.refresh_input(sync=True) 824 | return 825 | 826 | self.execute_cmdline(self.cmdline) 827 | 828 | self.draw_output() 829 | self.refresh_output(sync=True) 830 | 831 | self.ihist.append(self.ibuf) 832 | self.reset_input() 833 | self.draw_input() 834 | self.refresh_input(sync=True) 835 | 836 | def execute_cmdline(self, cmdline): 837 | self.obuf.append('* %s' % time.ctime()) 838 | self.obuf.append('> %s' % cmdline) 839 | self.screen.data.socket.send(cmdline.encode()) 840 | self.obuf.extend(self.screen.data.socket.recv()) 841 | self.update_screenlines() 842 | 843 | 844 | class Screen: 845 | 846 | def __init__(self, data, mid=1): 847 | self.data = data 848 | self.modes = SCREEN_MODES 849 | self.sb_conn = StatusBar() 850 | self.sb_pipe = StatusBar() 851 | self.lines = [] 852 | self.screen = None 853 | self.xmin = 0 854 | self.xmax = SCREEN_XMIN 855 | self.ymin = 0 856 | self.ymax = SCREEN_YMIN 857 | self.vmin = 0 858 | self.cmin = 0 859 | self.cpos = 0 860 | self.hpos = SCREEN_HPOS 861 | self.help = ScreenHelp(self) 862 | self.cli = ScreenCLI(self) 863 | 864 | self._pmid = mid # previous mode id 865 | self._cmid = mid # current mode id 866 | self._mode = self.modes[mid] 867 | 868 | # Display state 869 | self.active = False 870 | 871 | # Assume a dumb TTY, setup() will detect smart features. 872 | self.dumbtty = True 873 | 874 | # Toggled by the SIGWINCH handler... 875 | # Note: Defaults to true to force the initial size sync. 876 | self._resized = True 877 | 878 | # Display given exceptions on screen 879 | self.exceptions = [] 880 | 881 | # Show cursor line? 882 | self.cursor = True 883 | 884 | # Show hotkeys? 885 | self.hotkeys = False 886 | 887 | def _sigwinchhandler(self, signum, frame): 888 | self._resized = True 889 | 890 | @property 891 | def resized(self): 892 | if self.dumbtty: 893 | ymax, xmax = self.getmaxyx() 894 | return ymax != self.ymax or xmax != self.xmax 895 | else: 896 | return self._resized 897 | 898 | @property 899 | def mid(self): 900 | return self._cmid 901 | 902 | @property 903 | def mode(self): 904 | return self._mode 905 | 906 | @property 907 | def ncols(self): 908 | return self.xmax - self.xmin 909 | 910 | @property 911 | def smin(self): 912 | return self.hpos + 2 913 | 914 | @property 915 | def smax(self): 916 | return self.ymax - 3 917 | 918 | @property 919 | def span(self): 920 | return self.smax - self.smin 921 | 922 | @property 923 | def cmax(self): 924 | return min(self.span, len(self.lines) - 1) 925 | 926 | @property 927 | def cstat(self): 928 | return self.lines[self.vpos].stat 929 | 930 | @property 931 | def vpos(self): 932 | return self.vmin + self.cpos 933 | 934 | @property 935 | def vmax(self): 936 | return min(self.vmin + self.span, len(self.lines) - 1) 937 | 938 | @property 939 | def screenlines(self): 940 | return enumerate(self.lines[self.vmin:self.vmax + 1]) 941 | 942 | # Proxies 943 | def getch(self, *args, **kwargs): 944 | return self.screen.getch(*args, **kwargs) 945 | def hline(self, *args, **kwargs): 946 | return self.screen.hline(*args, **kwargs) 947 | def addstr(self, *args, **kwargs): 948 | return self.screen.addstr(*args, **kwargs) 949 | 950 | def setup(self): 951 | self.screen = curses_init() 952 | self.screen.keypad(1) 953 | self.screen.nodelay(1) 954 | self.screen.idlok(1) 955 | self.screen.move(0, 0) 956 | curses.def_prog_mode() 957 | self.help.setup() 958 | self.cli.setup() 959 | 960 | # Register some terminal resizing magic if supported... 961 | if hasattr(curses, 'resize_term') and hasattr(signal, 'SIGWINCH'): 962 | self.dumbtty = False 963 | signal.signal(signal.SIGWINCH, self._sigwinchhandler) 964 | 965 | # If we came this far the display is active 966 | self.active = True 967 | 968 | def getmaxyx(self): 969 | ymax, xmax = self.screen.getmaxyx() 970 | xmax = min(xmax, SCREEN_XMAX) 971 | ymax = min(ymax, SCREEN_YMAX) 972 | return ymax, xmax 973 | 974 | def resize(self): 975 | if not self.dumbtty: 976 | self.clear() 977 | size = fcntl.ioctl(0, tty.TIOCGWINSZ, '12345678') 978 | size = struct.unpack('4H', size) 979 | curses.resize_term(size[0], size[1]) 980 | 981 | ymax, xmax = self.getmaxyx() 982 | 983 | if xmax < SCREEN_XMIN or ymax < SCREEN_YMIN: 984 | raise RuntimeError( 985 | 'screen too small, need at least %dx%d' 986 | % (SCREEN_XMIN, SCREEN_YMIN)) 987 | if ymax == self.ymax and xmax == self.xmax: 988 | self._resized = False 989 | return 990 | if xmax != self.xmax: 991 | self.xmax = xmax 992 | if ymax != self.ymax: 993 | self.ymax = ymax 994 | 995 | self.mode.sync(self) 996 | 997 | # Force re-wrapping of the screenlines in CLI mode 998 | if self.mid == 5: 999 | self.cli.update_screenlines() 1000 | self.cli.draw_output() 1001 | 1002 | self._resized = False 1003 | 1004 | def reset(self): 1005 | if not self.active: 1006 | return 1007 | curses_reset(self.screen) 1008 | 1009 | def recover(self): 1010 | curses.reset_prog_mode() 1011 | 1012 | def refresh(self): 1013 | self.screen.noutrefresh() 1014 | 1015 | if self.mid == 0: 1016 | self.help.refresh() 1017 | elif self.mid == 5: 1018 | self.cli.refresh_output() 1019 | self.cli.refresh_input() 1020 | 1021 | curses.doupdate() 1022 | 1023 | def clear(self): 1024 | # Note: Forces the whole screen to be repainted upon refresh() 1025 | self.screen.clear() 1026 | 1027 | def erase(self): 1028 | self.screen.erase() 1029 | 1030 | def switch_mode(self, mid): 1031 | if mid == 5 and self.data.socket.ro: 1032 | return # noop 1033 | 1034 | mode = self.modes[mid] 1035 | mode.sync(self) 1036 | 1037 | if self.mid != 5 and mid == 5: 1038 | self.cli.start() 1039 | elif self.mid == 5 and mid != 5: 1040 | self.cli.stop() 1041 | 1042 | self._pmid = self._cmid 1043 | self._cmid, self._mode = mid, mode 1044 | 1045 | def toggle_mode(self): 1046 | if self._pmid == self._cmid: 1047 | return 1048 | self.switch_mode(self._pmid) 1049 | 1050 | def cycle_mode(self, n): 1051 | if n == 0: 1052 | return 1053 | 1054 | if self.data.socket.ro: 1055 | border = 4 1056 | else: 1057 | border = 5 1058 | 1059 | if self._cmid == 0: 1060 | self.switch_mode(1) 1061 | elif n < 0 and self._cmid == 1: 1062 | self.switch_mode(border) 1063 | elif n > 0 and self._cmid == border: 1064 | self.switch_mode(1) 1065 | else: 1066 | self.switch_mode(self._cmid + n) 1067 | 1068 | def update_data(self): 1069 | self.data.update_info() 1070 | try: 1071 | self.data.update_stat() 1072 | except RuntimeWarning as x: 1073 | self.exceptions.append(x) 1074 | 1075 | def update_bars(self): 1076 | self.sb_conn.update_max(int(self.data.info['maxconn'], 10)) 1077 | self.sb_conn.update_cur(int(self.data.info['curconn'], 10)) 1078 | self.sb_pipe.update_max(int(self.data.info['maxpipes'], 10)) 1079 | self.sb_pipe.update_cur(int(self.data.info['curpipes'], 10)) 1080 | 1081 | def update_lines(self): 1082 | # Display non-fatal exceptions on screen 1083 | if self.exceptions: 1084 | self.mvhome() 1085 | self.lines = [] 1086 | self.cursor = False 1087 | for x in self.exceptions: 1088 | for line in str(x).splitlines(): 1089 | line = line.center(SCREEN_XMIN) 1090 | self.lines.append(ScreenLine(text=line)) 1091 | self.exceptions = [] 1092 | return 1093 | 1094 | # Reset cursor visibility 1095 | if not self.cursor: 1096 | self.cursor = True 1097 | 1098 | # Update screen lines 1099 | self.lines = get_screenlines(self.data.stat) 1100 | if self.data.svcount >= HAPROXY_STAT_MAX_SERVICES: 1101 | self.lines.append(ScreenLine()) 1102 | for line in HAPROXY_STAT_LIMIT_WARNING.splitlines(): 1103 | self.lines.append(ScreenLine(text=line)) 1104 | 1105 | def draw_line(self, ypos, xpos=0, text=None, 1106 | attr=curses.A_REVERSE): 1107 | self.hline(ypos, self.xmin, ' ', self.xmax, attr) 1108 | if text: 1109 | self.addstr(ypos, self.xmin + xpos, text, attr) 1110 | 1111 | def draw_head(self): 1112 | self.draw_line(self.ymin) 1113 | attr = curses.A_REVERSE | curses.A_BOLD 1114 | self.addstr(self.ymin, self.xmin, 1115 | time.ctime().rjust(self.xmax - 1), attr) 1116 | self.addstr(self.ymin, self.xmin + 1, 1117 | 'HATop version ' + __version__, attr) 1118 | 1119 | def draw_info(self): 1120 | self.addstr(self.ymin + 2, self.xmin + 2, 1121 | '%s Version: %s (released: %s)' % ( 1122 | self.data.info['software_name'], 1123 | self.data.info['software_version'], 1124 | self.data.info['software_release'], 1125 | ), curses.A_BOLD) 1126 | self.addstr(self.ymin + 2, self.xmin + 56, 1127 | 'PID: %d (proc %d)' % ( 1128 | int(self.data.info['pid'], 10), 1129 | int(self.data.info['procn'], 10), 1130 | ), curses.A_BOLD) 1131 | self.addstr(self.ymin + 4, self.xmin + 2, 1132 | ' Node: %s (uptime %s)' % ( 1133 | self.data.info['node'] or 'unknown', 1134 | self.data.info['uptime'], 1135 | )) 1136 | self.addstr(self.ymin + 6, self.xmin + 2, 1137 | ' Pipes: %s' % self.sb_pipe) 1138 | self.addstr(self.ymin + 7, self.xmin + 2, 1139 | 'Connections: %s' % self.sb_conn) 1140 | self.addstr(self.ymin + 9, self.xmin + 2, 1141 | 'Procs: %3d Tasks: %5d Queue: %5d ' 1142 | 'Proxies: %3d Services: %4d' % ( 1143 | int(self.data.info['nproc'], 10), 1144 | int(self.data.info['tasks'], 10), 1145 | int(self.data.info['runqueue'], 10), 1146 | self.data.pxcount, 1147 | self.data.svcount, 1148 | )) 1149 | 1150 | def draw_cols(self): 1151 | self.draw_line(self.hpos, text=self.mode.head, 1152 | attr=curses.A_REVERSE | curses.A_BOLD) 1153 | 1154 | def draw_foot(self): 1155 | xpos = self.xmin 1156 | ypos = self.ymax - 1 1157 | self.draw_line(ypos) 1158 | attr_active = curses.A_BOLD 1159 | attr_inactive = curses.A_BOLD | curses.A_REVERSE 1160 | 1161 | # HOTKEYS 1162 | if (self.hotkeys and 1163 | 0 < self.mid < 5 and 1164 | self.cstat and 1165 | self.cstat['iid'] > 0 and 1166 | self.cstat['sid'] > 0): 1167 | self.draw_line(ypos) 1168 | self.addstr(ypos, 1, 'HOTKEYS:', 1169 | curses.A_BOLD | curses.A_REVERSE) 1170 | self.addstr(ypos, 11, 1171 | 'F1=ENABLE F2=DISABLE F3=DRAIN ' 1172 | 'F4=W-RESET ' 1173 | 'F5=W-10 F6=W-1 F7=W+1 F8=W+10 ' 1174 | 'F9=ENABLE (HERE) F10=DISABLE (HERE) F11=DRAIN (HERE)', 1175 | curses.A_NORMAL | curses.A_REVERSE) 1176 | return 1177 | 1178 | # VIEWPORTS 1179 | for mid, mode in enumerate(self.modes): 1180 | if mid == 0: 1181 | continue 1182 | if mid == 5 and self.data.socket.ro: 1183 | continue 1184 | if mid == self.mid: 1185 | attr = attr_active 1186 | else: 1187 | attr = attr_inactive 1188 | 1189 | s = ' %d-%s ' % (mid, mode.name) 1190 | self.addstr(ypos, xpos, s, attr) 1191 | xpos += len(s) 1192 | 1193 | if 0 < self.mid < 5 and self.cstat: 1194 | if self.cstat['iid'] > 0 and self.cstat['sid'] > 0: 1195 | if self.data.socket.ro: 1196 | s = 'READ-ONLY [#%d/#%d]' % ( 1197 | self.cstat['iid'], self.cstat['sid']) 1198 | else: 1199 | s = 'ENTER=MENU SPACE=SEL [#%d/#%d]' % ( 1200 | self.cstat['iid'], self.cstat['sid']) 1201 | else: 1202 | if self.data.socket.ro: 1203 | s = 'READ-ONLY [#%d/#%d]' % ( 1204 | self.cstat['iid'], self.cstat['sid']) 1205 | else: 1206 | s = '[#%d/#%d]' % ( 1207 | self.cstat['iid'], self.cstat['sid']) 1208 | elif self.mid == 5: 1209 | s = 'PGUP/PGDOWN=SCROLL' 1210 | else: 1211 | s = 'UP/DOWN=SCROLL H=HELP Q=QUIT' 1212 | self.addstr(ypos, self.xmax - len(s) - 1, s, attr_inactive) 1213 | 1214 | def draw_stat(self): 1215 | for idx, line in self.screenlines: 1216 | if self.cursor and idx == self.cpos: 1217 | attr = line.attr | curses.A_REVERSE 1218 | else: 1219 | attr = line.attr 1220 | if not line.stat: 1221 | screenline = get_cell(self.xmax, 'L', line.text) 1222 | elif 'message' in line.stat: 1223 | screenline = get_cell(self.xmax, 'L', line.stat['message']) 1224 | else: 1225 | screenline = get_screenline(self.mode, line.stat) 1226 | self.addstr(self.smin + idx, self.xmin, screenline, attr) 1227 | 1228 | def draw_mode(self): 1229 | if self.mid == 0: 1230 | self.help.draw() 1231 | elif self.mid == 5 and self._pmid == self._cmid: 1232 | self.cli.start() # initial mid was 5 1233 | elif 0 < self.mid < 5: 1234 | self.draw_stat() 1235 | 1236 | def mvc(self, n): 1237 | if n == 0: 1238 | return 1239 | 1240 | # Move DOWN 1241 | if n > 0: 1242 | # move cursor 1243 | if self.cpos < self.cmax: 1244 | self.cpos = min(self.cmax, self.cpos + n) 1245 | return 1246 | # move screenlines 1247 | maxvmin = max(0, len(self.lines) - self.span - 1) 1248 | if self.cpos == self.cmax and self.vmin < maxvmin: 1249 | self.vmin = min(maxvmin, self.vmin + n) 1250 | 1251 | # Move UP 1252 | elif n < 0: # UP 1253 | # move cursor 1254 | if self.cpos > self.cmin: 1255 | self.cpos = max(self.cmin, self.cpos + n) 1256 | return 1257 | # move screenlines 1258 | if self.cpos == self.cmin and self.vmin > 0: 1259 | self.vmin = max(0, self.vmin + n) 1260 | 1261 | def mvhome(self): 1262 | # move cursor 1263 | if self.cpos != self.cmin: 1264 | self.cpos = self.cmin 1265 | # move screenlines 1266 | if self.vmin != 0: 1267 | self.vmin = 0 1268 | 1269 | def mvend(self): 1270 | # move cursor 1271 | if self.cpos != self.cmax: 1272 | self.cpos = self.cmax 1273 | # move screenlines 1274 | maxvmin = max(0, len(self.lines) - self.span - 1) 1275 | if self.vmin != maxvmin: 1276 | self.vmin = maxvmin 1277 | 1278 | 1279 | class ScreenHelp: 1280 | 1281 | def __init__(self, screen): 1282 | self.screen = screen 1283 | self.xmin = screen.xmin + 1 1284 | self.xmax = screen.xmax 1285 | self.ymin = 0 1286 | self.ymax = __doc__.count('\n') 1287 | self.xpos = 0 1288 | self.ypos = 0 1289 | 1290 | def setup(self): 1291 | self.pad = curses.newpad(self.ymax + 1, self.xmax + 1) 1292 | 1293 | def addstr(self, *args, **kwargs): 1294 | return self.pad.addstr(*args, **kwargs) 1295 | 1296 | def refresh(self): 1297 | self.pad.noutrefresh( 1298 | self.ypos, self.xpos, 1299 | self.screen.smin, self.xmin, 1300 | self.screen.smax, self.xmax - 2) 1301 | 1302 | def draw(self): 1303 | self.addstr(0, 0, __doc__) 1304 | 1305 | def mvc(self, n): 1306 | if n == 0: 1307 | return 1308 | 1309 | # Move DOWN 1310 | if n > 0: 1311 | self.ypos = min(self.ymax - self.screen.span, self.ypos + n) 1312 | 1313 | # Move UP 1314 | elif n < 0: 1315 | self.ypos = max(self.ymin, self.ypos + n) 1316 | 1317 | def mvhome(self): 1318 | self.ypos = self.ymin 1319 | 1320 | def mvend(self): 1321 | self.ypos = self.ymax - self.screen.span 1322 | 1323 | 1324 | class ScreenMode: 1325 | 1326 | def __init__(self, name): 1327 | self.name = name 1328 | self.columns = [] 1329 | 1330 | @property 1331 | def head(self): 1332 | return get_head(self) 1333 | 1334 | def sync(self, screen): 1335 | for idx, column in enumerate(self.columns): 1336 | column.width = get_width(column.minwidth, screen.xmax, 1337 | len(self.columns), idx) 1338 | 1339 | 1340 | class ScreenColumn: 1341 | 1342 | def __init__(self, name, header, minwidth, maxwidth, align, filters={}): 1343 | self.name = name 1344 | self.header = header 1345 | self.align = align 1346 | self.minwidth = minwidth 1347 | self.maxwidth = maxwidth 1348 | self.width = minwidth 1349 | self.filters = {'always': [], 'ondemand': []} 1350 | self.filters.update(filters) 1351 | 1352 | def get_width(self): 1353 | return self._width 1354 | 1355 | def set_width(self, n): 1356 | if self.maxwidth: 1357 | self._width = min(self.maxwidth, n) 1358 | self._width = max(self.minwidth, n) 1359 | 1360 | width = property(get_width, set_width) 1361 | 1362 | 1363 | class ScreenLine: 1364 | 1365 | def __init__(self, stat=None, text='', attr=0): 1366 | self.stat = stat 1367 | self.text = text 1368 | self.attr = attr 1369 | 1370 | 1371 | class StatusBar: 1372 | 1373 | def __init__(self, width=60, min=0, max=100, status=True): 1374 | self.width = width 1375 | self.curval = min 1376 | self.minval = min 1377 | self.maxval = max 1378 | self.status = status 1379 | self.prepend = '[' 1380 | self.append = ']' 1381 | self.usedchar = '|' 1382 | self.freechar = ' ' 1383 | 1384 | def __str__(self): 1385 | if self.status: 1386 | status = '%d/%d' % (self.curval, self.maxval) 1387 | 1388 | space = self.width - len(self.prepend) - len(self.append) 1389 | span = self.maxval - self.minval 1390 | 1391 | if span: 1392 | used = min(float(self.curval) / float(span), 1.0) 1393 | else: 1394 | used = 0.0 1395 | free = 1.0 - used 1396 | 1397 | # 100% equals full bar width, ignoring status text within the bar 1398 | bar = self.prepend 1399 | bar += self.usedchar * int(space * used) 1400 | bar += self.freechar * int(space * free) 1401 | if self.status: 1402 | bar = bar[:(self.width - len(status) - len(self.append))] 1403 | bar += status 1404 | bar += self.append 1405 | 1406 | return bar 1407 | 1408 | def update_cur(self, value): 1409 | value = min(self.maxval, value) 1410 | value = max(self.minval, value) 1411 | self.curval = value 1412 | 1413 | def update_max(self, value): 1414 | if value >= self.minval: 1415 | self.maxval = value 1416 | else: 1417 | self.maxval = self.minval 1418 | 1419 | # ------------------------------------------------------------------------- # 1420 | # DISPLAY FILTERS # 1421 | # ------------------------------------------------------------------------- # 1422 | 1423 | def human_seconds(numeric): 1424 | for minval, prefix in sorted(list(PREFIX_TIME.items()), reverse=True): 1425 | if (numeric//minval): 1426 | return '{}{}'.format(numeric//minval, prefix) 1427 | return '{}s'.format(numeric) 1428 | 1429 | def human_metric(numeric): 1430 | for minval, prefix in sorted(list(PREFIX_METRIC.items()), reverse=True): 1431 | if (numeric//minval): 1432 | return '{}{}'.format(numeric//minval, prefix) 1433 | return '{}'.format(numeric) 1434 | 1435 | def human_binary(numeric): 1436 | for minval, prefix in sorted(list(PREFIX_BINARY.items()), reverse=True): 1437 | if (numeric//minval): 1438 | return '{:.2f}{}'.format(numeric/minval, prefix) 1439 | return '{}B'.format(numeric) 1440 | 1441 | def trim(string, length): 1442 | if len(string) <= length: 1443 | return string 1444 | if length == 1: 1445 | return string[0] 1446 | if length > 5: 1447 | return '..{}'.format(string[-(length-2):]) 1448 | return '...' 1449 | 1450 | # ------------------------------------------------------------------------- # 1451 | # SCREEN LAYOUT # 1452 | # ------------------------------------------------------------------------- # 1453 | 1454 | SCREEN_MODES = [ 1455 | ScreenMode('HELP'), 1456 | ScreenMode('STATUS'), 1457 | ScreenMode('TRAFFIC'), 1458 | ScreenMode('HTTP'), 1459 | ScreenMode('ERRORS'), 1460 | ScreenMode('CLI'), 1461 | ] 1462 | 1463 | # Mode: HELP name header xmin xmax align 1464 | SCREEN_MODES[0].columns = [ 1465 | ScreenColumn('help', ' HATop Online Help ', 1466 | SCREEN_XMIN, 0, 'L'), 1467 | ] 1468 | 1469 | # Mode: STATUS name header xmin xmax align 1470 | SCREEN_MODES[1].columns = [ 1471 | ScreenColumn('svname', 'NAME', 10, 50, 'L'), 1472 | ScreenColumn('weight', 'W', 4, 6, 'R'), 1473 | ScreenColumn('status', 'STATUS', 6, 10, 'L'), 1474 | ScreenColumn('check_status', 'CHECK', 7, 20, 'L'), 1475 | ScreenColumn('act', 'ACT', 3, 0, 'R', 1476 | filters={'ondemand': [human_metric]}), 1477 | ScreenColumn('bck', 'BCK', 3, 0, 'R', 1478 | filters={'ondemand': [human_metric]}), 1479 | ScreenColumn('qcur', 'QCUR', 5, 0, 'R', 1480 | filters={'ondemand': [human_metric]}), 1481 | ScreenColumn('qmax', 'QMAX', 5, 0, 'R', 1482 | filters={'ondemand': [human_metric]}), 1483 | ScreenColumn('scur', 'SCUR', 6, 0, 'R', 1484 | filters={'ondemand': [human_metric]}), 1485 | ScreenColumn('smax', 'SMAX', 6, 0, 'R', 1486 | filters={'ondemand': [human_metric]}), 1487 | ScreenColumn('slim', 'SLIM', 6, 0, 'R', 1488 | filters={'ondemand': [human_metric]}), 1489 | ScreenColumn('stot', 'STOT', 6, 0, 'R', 1490 | filters={'ondemand': [human_metric]}), 1491 | ] 1492 | 1493 | # Mode: TRAFFIC name header xmin xmax align 1494 | SCREEN_MODES[2].columns = [ 1495 | ScreenColumn('svname', 'NAME', 10, 50, 'L'), 1496 | ScreenColumn('weight', 'W', 4, 6, 'R'), 1497 | ScreenColumn('status', 'STATUS', 6, 10, 'L'), 1498 | ScreenColumn('lbtot', 'LBTOT', 8, 0, 'R', 1499 | filters={'ondemand': [human_metric]}), 1500 | ScreenColumn('rate', 'RATE', 6, 0, 'R', 1501 | filters={'ondemand': [human_metric]}), 1502 | ScreenColumn('rate_lim', 'RLIM', 6, 0, 'R', 1503 | filters={'ondemand': [human_metric]}), 1504 | ScreenColumn('rate_max', 'RMAX', 6, 0, 'R', 1505 | filters={'ondemand': [human_metric]}), 1506 | ScreenColumn('bin', 'BIN', 12, 0, 'R', 1507 | filters={'always': [human_binary]}), 1508 | ScreenColumn('bout', 'BOUT', 12, 0, 'R', 1509 | filters={'always': [human_binary]}), 1510 | ] 1511 | 1512 | # Mode: HTTP name header xmin xmax align 1513 | SCREEN_MODES[3].columns = [ 1514 | ScreenColumn('svname', 'NAME', 10, 50, 'L'), 1515 | ScreenColumn('weight', 'W', 4, 6, 'R'), 1516 | ScreenColumn('status', 'STATUS', 6, 10, 'L'), 1517 | ScreenColumn('req_rate', 'RATE', 5, 0, 'R', 1518 | filters={'ondemand': [human_metric]}), 1519 | ScreenColumn('req_rate_max', 'RMAX', 5, 0, 'R', 1520 | filters={'ondemand': [human_metric]}), 1521 | ScreenColumn('req_tot', 'RTOT', 7, 0, 'R', 1522 | filters={'ondemand': [human_metric]}), 1523 | ScreenColumn('hrsp_1xx', '1xx', 5, 0, 'R', 1524 | filters={'ondemand': [human_metric]}), 1525 | ScreenColumn('hrsp_2xx', '2xx', 5, 0, 'R', 1526 | filters={'ondemand': [human_metric]}), 1527 | ScreenColumn('hrsp_3xx', '3xx', 5, 0, 'R', 1528 | filters={'ondemand': [human_metric]}), 1529 | ScreenColumn('hrsp_4xx', '4xx', 5, 0, 'R', 1530 | filters={'ondemand': [human_metric]}), 1531 | ScreenColumn('hrsp_5xx', '5xx', 5, 0, 'R', 1532 | filters={'ondemand': [human_metric]}), 1533 | ScreenColumn('hrsp_other', '?xx', 5, 0, 'R', 1534 | filters={'ondemand': [human_metric]}), 1535 | ] 1536 | 1537 | # Mode: ERRORS name header xmin xmax align 1538 | SCREEN_MODES[4].columns = [ 1539 | ScreenColumn('svname', 'NAME', 10, 50, 'L'), 1540 | ScreenColumn('weight', 'W', 4, 6, 'R'), 1541 | ScreenColumn('status', 'STATUS', 6, 10, 'L'), 1542 | ScreenColumn('check_status', 'CHECK', 7, 20, 'L'), 1543 | ScreenColumn('chkfail', 'CF', 3, 0, 'R', 1544 | filters={'ondemand': [human_metric]}), 1545 | ScreenColumn('chkdown', 'CD', 3, 0, 'R', 1546 | filters={'ondemand': [human_metric]}), 1547 | ScreenColumn('lastchg', 'CL', 3, 0, 'R', 1548 | filters={'always': [human_seconds]}), 1549 | ScreenColumn('econ', 'ECONN', 5, 0, 'R', 1550 | filters={'ondemand': [human_metric]}), 1551 | ScreenColumn('ereq', 'EREQ', 5, 0, 'R', 1552 | filters={'ondemand': [human_metric]}), 1553 | ScreenColumn('eresp', 'ERSP', 5, 0, 'R', 1554 | filters={'ondemand': [human_metric]}), 1555 | ScreenColumn('dreq', 'DREQ', 5, 0, 'R', 1556 | filters={'ondemand': [human_metric]}), 1557 | ScreenColumn('dresp', 'DRSP', 5, 0, 'R', 1558 | filters={'ondemand': [human_metric]}), 1559 | ScreenColumn('downtime', 'DOWN', 5, 0, 'R', 1560 | filters={'always': [human_seconds]}), 1561 | ] 1562 | 1563 | # Mode: CLI name header xmin xmax align 1564 | SCREEN_MODES[5].columns = [ 1565 | ScreenColumn('cli', 1566 | ' haproxy command line ' 1567 | ' use ALT-n / ESC-n to escape', 1568 | SCREEN_XMIN, 0, 'L'), 1569 | ] 1570 | 1571 | # ------------------------------------------------------------------------- # 1572 | # HELPERS # 1573 | # ------------------------------------------------------------------------- # 1574 | 1575 | def log(msg): 1576 | sys.stderr.write('%s\n' % msg) 1577 | 1578 | def parse_stat(iterable): 1579 | pxcount = svcount = 0 1580 | pxstat = {} # {iid: {sid: svstat, ...}, ...} 1581 | 1582 | idx_iid = get_idx('iid') 1583 | idx_sid = get_idx('sid') 1584 | 1585 | for line in iterable: 1586 | if not line: 1587 | continue 1588 | if line.startswith(HAPROXY_STAT_COMMENT): 1589 | continue # comment 1590 | if line.count(HAPROXY_STAT_SEP) < HAPROXY_STAT_NUMFIELDS: 1591 | continue # unknown format 1592 | 1593 | csv = line.split(HAPROXY_STAT_SEP, HAPROXY_STAT_NUMFIELDS) 1594 | 1595 | # Skip further parsing? 1596 | if svcount > HAPROXY_STAT_MAX_SERVICES: 1597 | try: 1598 | iid = csv[idx_iid] 1599 | iid = int(iid, 10) 1600 | except ValueError: 1601 | raise RuntimeError( 1602 | 'garbage proxy identifier: iid="%s" (need %s)' % 1603 | (iid, int)) 1604 | try: 1605 | sid = csv[idx_sid] 1606 | sid = int(sid, 10) 1607 | except ValueError: 1608 | raise RuntimeError( 1609 | 'garbage service identifier: sid="%s" (need %s)' % 1610 | (sid, int)) 1611 | if iid not in pxstat: 1612 | pxcount += 1 1613 | svcount += 1 1614 | elif sid not in pxstat[iid]: 1615 | svcount += 1 1616 | continue 1617 | 1618 | # Parse stat... 1619 | svstat = {} # {field: value, ...} 1620 | 1621 | for idx, field in HAPROXY_STAT_CSV: 1622 | field_type, field_name = field 1623 | value = csv[idx] 1624 | 1625 | try: 1626 | if field_type is int: 1627 | if len(value): 1628 | value = int(value, 10) 1629 | else: 1630 | value = 0 1631 | elif field_type is not type(value): 1632 | value = field_type(value) 1633 | except ValueError: 1634 | raise RuntimeError('garbage field: %s="%s" (need %s)' % ( 1635 | field_name, value, field_type)) 1636 | 1637 | # Special case 1638 | if field_name == 'status' and value == 'no check': 1639 | value = '-' 1640 | elif field_name == 'check_status' and svstat['status'] == '-': 1641 | value = 'none' 1642 | 1643 | svstat[field_name] = value 1644 | 1645 | # Record result... 1646 | iid = svstat['iid'] 1647 | stype = svstat['type'] 1648 | 1649 | if stype == 0 or stype == 1: # FRONTEND / BACKEND 1650 | id = svstat['svname'] 1651 | else: 1652 | id = svstat['sid'] 1653 | 1654 | try: 1655 | pxstat[iid][id] = svstat 1656 | except KeyError: 1657 | pxstat[iid] = { id: svstat } 1658 | pxcount += 1 1659 | svcount += 1 1660 | 1661 | return pxstat, pxcount, svcount 1662 | 1663 | def parse_info(iterable): 1664 | info = {} 1665 | for line in iterable: 1666 | line = line.strip() 1667 | if not line: 1668 | continue 1669 | for key, regexp in HAPROXY_INFO_RE.items(): 1670 | match = regexp.match(line) 1671 | if match: 1672 | info[key] = match.group('value') 1673 | break 1674 | 1675 | for key in HAPROXY_INFO_RE.keys(): 1676 | if not key in info: 1677 | raise RuntimeError('missing "%s" in info data' % key) 1678 | 1679 | return info 1680 | 1681 | def get_idx(field): 1682 | return [x for x in HAPROXY_STAT_CSV if x[1][1] == field][0][0] 1683 | 1684 | def get_width(width, xmax, ncols, idx): 1685 | # distribute excess space evenly from left to right 1686 | if xmax > SCREEN_XMIN: 1687 | xdiff = xmax - SCREEN_XMIN 1688 | if xdiff <= ncols: 1689 | if idx < xdiff: 1690 | width += 1 1691 | else: 1692 | if idx < (xdiff - (xdiff / ncols) * ncols): 1693 | width += 1 # compensate rounding 1694 | width = width + xdiff // ncols 1695 | return width 1696 | 1697 | def get_cell(width, align, value): 1698 | s = str(value) 1699 | if align == 'L': 1700 | s = s.ljust(width) 1701 | elif align == 'C': 1702 | s = s.center(width) 1703 | elif align == 'R': 1704 | s = s.rjust(width) 1705 | return s 1706 | 1707 | def get_head(mode): 1708 | columns = [] 1709 | for column in mode.columns: 1710 | s = column.header 1711 | s = get_cell(column.width, column.align, s) 1712 | columns.append(s) 1713 | return ' '.join(columns) 1714 | 1715 | def get_screenlines(stat): 1716 | screenlines = [] 1717 | 1718 | for iid, svstats in stat.items(): 1719 | lines = [] 1720 | 1721 | try: 1722 | frontend = svstats.pop('FRONTEND') 1723 | except KeyError: 1724 | frontend = None 1725 | try: 1726 | backend = svstats.pop('BACKEND') 1727 | except KeyError: 1728 | backend = None 1729 | 1730 | if frontend: 1731 | lines.append(ScreenLine(stat=frontend)) 1732 | 1733 | for sid, svstat in sorted(svstats.items()): 1734 | lines.append(ScreenLine(stat=svstat)) 1735 | 1736 | if backend: 1737 | lines.append(ScreenLine(stat=backend)) 1738 | 1739 | if not len(lines): 1740 | continue 1741 | 1742 | pxname = lines[0].stat['pxname'] 1743 | screenlines.append(ScreenLine(attr=curses.A_BOLD, 1744 | text='>>> %s' % pxname)) 1745 | screenlines += lines 1746 | screenlines.append(ScreenLine()) 1747 | 1748 | # remove trailing empty line 1749 | if len(screenlines) > 1: 1750 | screenlines.pop() 1751 | 1752 | return screenlines 1753 | 1754 | def get_screenline(mode, stat): 1755 | cells = [] 1756 | for column in mode.columns: 1757 | value = stat[column.name] 1758 | 1759 | for filter in column.filters['always']: 1760 | value = filter(value) 1761 | 1762 | if len(str(value)) > column.width: 1763 | for filter in column.filters['ondemand']: 1764 | value = filter(value) 1765 | 1766 | value = str(value) 1767 | value = trim(value, column.width) 1768 | cells.append(get_cell(column.width, column.align, value)) 1769 | 1770 | return ' '.join(cells) 1771 | 1772 | # ------------------------------------------------------------------------- # 1773 | # CURSES HELPERS # 1774 | # ------------------------------------------------------------------------- # 1775 | 1776 | def curses_init(): 1777 | screen = curses.initscr() 1778 | curses.noecho() 1779 | curses.nonl() 1780 | curses.raw() 1781 | 1782 | # Some terminals don't support different cursor visibilities 1783 | try: 1784 | curses.curs_set(0) 1785 | except CursesError: 1786 | pass 1787 | 1788 | # Some terminals don't support the default color palette 1789 | try: 1790 | curses.start_color() 1791 | curses.use_default_colors() 1792 | except CursesError: 1793 | pass 1794 | 1795 | return screen 1796 | 1797 | def curses_reset(screen): 1798 | if not screen: 1799 | return 1800 | screen.keypad(0) 1801 | curses.noraw() 1802 | curses.echo() 1803 | curses.endwin() 1804 | 1805 | # ------------------------------------------------------------------------- # 1806 | # MAIN LOOP # 1807 | # ------------------------------------------------------------------------- # 1808 | 1809 | def mainloop(screen, interval): 1810 | # Sleep time of each iteration in seconds 1811 | scan = 1.0 / 100.0 1812 | # Query socket and redraw the screen in the given interval 1813 | iterations = interval / scan 1814 | 1815 | i = 0 1816 | update_stat = True # Toggle stat update (query socket, parse csv) 1817 | update_lines = True # Toggle screen line update (sync with stat data) 1818 | update_display = True # Toggle screen update (resize, repaint, refresh) 1819 | switch_mode = False # Toggle mode / viewport switch 1820 | 1821 | while True: 1822 | 1823 | # Resize toggled by SIGWINCH? 1824 | if screen.resized: 1825 | screen.resize() 1826 | update_display = True 1827 | 1828 | # Update interval reached... 1829 | if i == iterations: 1830 | update_stat = True 1831 | if 0 < screen.mid < 5: 1832 | update_lines = True 1833 | update_display = True 1834 | i = 0 1835 | 1836 | # Refresh screen? 1837 | if update_display: 1838 | 1839 | if update_stat: 1840 | screen.update_data() 1841 | screen.update_bars() 1842 | update_stat = False 1843 | 1844 | if update_lines: 1845 | screen.update_lines() 1846 | update_lines = False 1847 | 1848 | screen.erase() 1849 | screen.draw_head() 1850 | screen.draw_info() 1851 | screen.draw_cols() 1852 | screen.draw_mode() 1853 | screen.draw_foot() 1854 | screen.refresh() 1855 | 1856 | update_display = False 1857 | 1858 | c = screen.getch() 1859 | 1860 | if c < 0: 1861 | time.sleep(scan) 1862 | i += 1 1863 | continue 1864 | 1865 | # Toggle hotkey footer 1866 | if screen.hotkeys: 1867 | if c not in ( 1868 | curses.KEY_F1, # enable server on all backends 1869 | curses.KEY_F2, # disable server on all backends 1870 | curses.KEY_F3, # drain server on all backends 1871 | curses.KEY_F4, # reset weight 1872 | curses.KEY_F5, # weight -10 1873 | curses.KEY_F6, # weight -1 1874 | curses.KEY_F7, # weight +1 1875 | curses.KEY_F8, # weight +10 1876 | curses.KEY_F9, # enable server on one backend 1877 | curses.KEY_F10, # disable server on one backend 1878 | curses.KEY_F11, # drain server on one backend 1879 | ): 1880 | screen.hotkeys = False 1881 | update_display = True 1882 | if c in ( 1883 | curses.KEY_ENTER, 1884 | curses.ascii.CR 1885 | ): 1886 | continue 1887 | 1888 | if c == curses.ascii.ETX: 1889 | raise KeyboardInterrupt() 1890 | 1891 | # Mode switch (ALT-n / ESC-n) or toggle (ESC / ESC-ESC) 1892 | if c == curses.ascii.ESC: 1893 | c = screen.getch() 1894 | if c < 0 or c == curses.ascii.ESC: 1895 | screen.toggle_mode() 1896 | update_display = True 1897 | continue 1898 | if 0 < c < 256: 1899 | c = chr(c) 1900 | if c in 'qQHh?12345': 1901 | switch_mode = True 1902 | 1903 | # Mode cycle (TAB / BTAB) 1904 | elif c == ord('\t'): 1905 | screen.cycle_mode(1) 1906 | update_display = True 1907 | continue 1908 | elif c == curses.KEY_BTAB: 1909 | screen.cycle_mode(-1) 1910 | update_display = True 1911 | continue 1912 | 1913 | # Mode switch in non-CLI modes using the number only 1914 | elif 0 <= screen.mid < 5 and 0 < c < 256: 1915 | c = chr(c) 1916 | if c in 'qQHh?12345': 1917 | switch_mode = True 1918 | 1919 | if switch_mode: 1920 | switch_mode = False 1921 | if c in 'qQ': 1922 | raise StopIteration() 1923 | if c != str(screen.mid) or (c in 'Hh?' and screen.mid != 0): 1924 | if c in 'Hh?': 1925 | screen.switch_mode(0) 1926 | elif c in '12345': 1927 | screen.switch_mode(int(c)) 1928 | 1929 | # Force screen update with existing data 1930 | update_display = True 1931 | continue 1932 | 1933 | # -> HELP 1934 | if screen.mid == 0: 1935 | if c == curses.KEY_UP and screen.help.ypos > 0: 1936 | screen.help.mvc(-1) 1937 | elif c == curses.KEY_DOWN and \ 1938 | screen.help.ypos < screen.help.ymax - screen.span: 1939 | screen.help.mvc(1) 1940 | elif c == curses.KEY_PPAGE and screen.help.ypos > 0: 1941 | screen.help.mvc(-10) 1942 | elif c == curses.KEY_NPAGE and \ 1943 | screen.help.ypos < screen.help.ymax - screen.span: 1944 | screen.help.mvc(10) 1945 | elif c == curses.ascii.SOH or c == curses.KEY_HOME: 1946 | screen.help.mvhome() 1947 | elif c == curses.ascii.ENQ or c == curses.KEY_END: 1948 | screen.help.mvend() 1949 | 1950 | # -> STATUS / TRAFFIC / HTTP / ERRORS 1951 | elif 1 <= screen.mid <= 4: 1952 | 1953 | # movements 1954 | if c == curses.KEY_UP: 1955 | screen.mvc(-1) 1956 | elif c == curses.KEY_DOWN: 1957 | screen.mvc(1) 1958 | elif c == curses.KEY_PPAGE: 1959 | screen.mvc(-10) 1960 | elif c == curses.KEY_NPAGE: 1961 | screen.mvc(10) 1962 | elif c == curses.ascii.SOH or c == curses.KEY_HOME: 1963 | screen.mvhome() 1964 | elif c == curses.ascii.ENQ or c == curses.KEY_END: 1965 | screen.mvend() 1966 | 1967 | # actions 1968 | elif c in ( 1969 | curses.KEY_ENTER, # show hotkeys 1970 | chr(curses.ascii.CR), # show hotkeys 1971 | chr(curses.ascii.SP), # copy & paste identifier 1972 | curses.KEY_F1, # enable server on all backends 1973 | curses.KEY_F2, # disable server on all backends 1974 | curses.KEY_F3, # drain server on all backends 1975 | curses.KEY_F4, # reset weight 1976 | curses.KEY_F5, # weight -10 1977 | curses.KEY_F6, # weight -1 1978 | curses.KEY_F7, # weight +1 1979 | curses.KEY_F8, # weight +10 1980 | curses.KEY_F9, # enable server on one backend 1981 | curses.KEY_F10, # disable server on one backend 1982 | curses.KEY_F11, # drain server on one backend 1983 | ): 1984 | if screen.data.socket.ro: 1985 | continue 1986 | if not screen.cstat: 1987 | continue 1988 | 1989 | if c == curses.KEY_ENTER or c == chr(curses.ascii.CR): 1990 | screen.hotkeys = True 1991 | update_display = True 1992 | continue 1993 | 1994 | iid = screen.cstat['iid'] 1995 | sid = screen.cstat['sid'] 1996 | 1997 | if iid <= 0 or sid <= 0: 1998 | continue 1999 | 2000 | pxname = screen.cstat['pxname'] 2001 | svname = screen.cstat['svname'] 2002 | 2003 | if not pxname or not svname: 2004 | continue 2005 | 2006 | notify = False 2007 | 2008 | if c == ' ': 2009 | if screen.cli.puts('%s/%s' % (pxname, svname)): 2010 | screen.switch_mode(5) 2011 | update_display = True 2012 | continue 2013 | elif c == curses.KEY_F1 or c == curses.KEY_F2: 2014 | cliname = 'enable server' 2015 | if c == curses.KEY_F2: 2016 | cliname = 'disable server' 2017 | 2018 | # loop on all proxies (backends) 2019 | for px in screen.data.stat.values(): 2020 | # in a given proxy, loop on all services id (unique inside a proxy) 2021 | # a service can be a frontend, backend, server or socket object 2022 | for sv in px.values(): 2023 | if sv['type'] == 2: # only the type "server" interests us 2024 | # selects only the service name (hostname) 2025 | # which matches that of the current line 2026 | if sv['svname'] == svname: 2027 | screen.cli.execute_cmdline( 2028 | '%s %s/%s' % (cliname, sv['pxname'], svname)) 2029 | notify = True 2030 | elif c == curses.KEY_F3: 2031 | # loop on all proxies (backends) 2032 | for px in screen.data.stat.values(): 2033 | # in a given proxy, loop on all services id (unique inside a proxy) 2034 | # a service can be a frontend, backend, server or socket object 2035 | for sv in px.values(): 2036 | if sv['type'] == 2: # only the type "server" interests us 2037 | # selects only the service name (hostname) 2038 | # which matches that of the current line 2039 | if sv['svname'] == svname: 2040 | screen.cli.execute_cmdline( 2041 | 'set server %s/%s state drain' % (pxname, svname)) 2042 | notify = True 2043 | elif c == curses.KEY_F4: 2044 | screen.cli.execute_cmdline( 2045 | 'set weight %s/%s 100%%' % (pxname, svname)) 2046 | notify = True 2047 | elif c == curses.KEY_F5: 2048 | curweight = screen.cstat['weight'] 2049 | if curweight <= 0: 2050 | continue 2051 | weight = max(0, curweight - 10) # - 10 2052 | screen.cli.execute_cmdline( 2053 | 'set weight %s/%s %d' % (pxname, svname, weight)) 2054 | notify = True 2055 | elif c == curses.KEY_F6: 2056 | curweight = screen.cstat['weight'] 2057 | if curweight <= 0: 2058 | continue 2059 | weight = max(0, curweight - 1) # - 1 2060 | screen.cli.execute_cmdline( 2061 | 'set weight %s/%s %d' % (pxname, svname, weight)) 2062 | notify = True 2063 | elif c == curses.KEY_F7: 2064 | curweight = screen.cstat['weight'] 2065 | if curweight >= 256: 2066 | continue 2067 | weight = min(256, curweight + 1) # + 1 2068 | screen.cli.execute_cmdline( 2069 | 'set weight %s/%s %d' % (pxname, svname, weight)) 2070 | notify = True 2071 | elif c == curses.KEY_F8: 2072 | curweight = screen.cstat['weight'] 2073 | if curweight >= 256: 2074 | continue 2075 | weight = min(256, curweight + 10) # + 10 2076 | screen.cli.execute_cmdline( 2077 | 'set weight %s/%s %d' % (pxname, svname, weight)) 2078 | notify = True 2079 | elif c == curses.KEY_F9: 2080 | screen.cli.execute_cmdline( 2081 | 'enable server %s/%s' % (pxname, svname)) 2082 | notify = True 2083 | elif c == curses.KEY_F10: 2084 | screen.cli.execute_cmdline( 2085 | 'disable server %s/%s' % (pxname, svname)) 2086 | notify = True 2087 | elif c == curses.KEY_F11: 2088 | screen.cli.execute_cmdline( 2089 | 'set server %s/%s state drain' % (pxname, svname)) 2090 | notify = True 2091 | 2092 | # Refresh the screen indicating pending changes... 2093 | if notify: 2094 | screen.cstat['message'] = 'updating...' 2095 | update_display = True 2096 | continue 2097 | 2098 | # -> CLI 2099 | elif screen.mid == 5: 2100 | 2101 | # enter 2102 | if c == curses.KEY_ENTER or c == curses.ascii.CR: 2103 | screen.cli.execute() 2104 | 2105 | # input movements 2106 | elif c == curses.KEY_LEFT: 2107 | screen.cli.mvc(-1) 2108 | elif c == curses.KEY_RIGHT: 2109 | screen.cli.mvc(1) 2110 | elif c == curses.ascii.SOH or c == curses.KEY_HOME: 2111 | screen.cli.mvhome() 2112 | elif c == curses.ascii.ENQ or c == curses.KEY_END: 2113 | screen.cli.mvend() 2114 | 2115 | # input editing 2116 | elif c == curses.ascii.ETB: 2117 | pass # TODO (CTRL-W) 2118 | elif c == curses.KEY_DC: 2119 | screen.cli.delc(1) 2120 | elif c == curses.KEY_BACKSPACE or c == curses.ascii.DEL: 2121 | screen.cli.delc(-1) 2122 | 2123 | # input history 2124 | elif c == curses.KEY_UP: 2125 | screen.cli.prev() 2126 | elif c == curses.KEY_DOWN: 2127 | screen.cli.post() 2128 | 2129 | # output history 2130 | elif c == curses.KEY_PPAGE: 2131 | screen.cli.mvo(-1) 2132 | elif c == curses.KEY_NPAGE: 2133 | screen.cli.mvo(1) 2134 | 2135 | elif 0 < c < 256: 2136 | screen.cli.putc(chr(c)) 2137 | 2138 | # Force screen update with existing data if key was a movement key 2139 | if c in ( 2140 | curses.KEY_UP, 2141 | curses.KEY_DOWN, 2142 | curses.KEY_PPAGE, 2143 | curses.KEY_NPAGE, 2144 | ) or screen.mid != 5 and c in ( 2145 | curses.ascii.SOH, curses.KEY_HOME, 2146 | curses.ascii.ENQ, curses.KEY_END, 2147 | ): 2148 | update_display = True 2149 | 2150 | time.sleep(scan) 2151 | i += 1 2152 | 2153 | 2154 | if __name__ == '__main__': 2155 | 2156 | from optparse import OptionParser, OptionGroup 2157 | 2158 | version = 'hatop version %s' % __version__ 2159 | usage = 'Usage: hatop (-s SOCKET| -t HOST:PORT) [OPTIONS]...' 2160 | 2161 | parser = OptionParser(usage=usage, version=version) 2162 | 2163 | opts = OptionGroup(parser, 'Mandatory') 2164 | opts.add_option('-s', '--unix-socket', dest='socket', 2165 | help='path to the haproxy unix stats socket') 2166 | opts.add_option('-t', '--tcp-socket', dest='tcp_socket', 2167 | help='address of the haproxy tcp stats socket') 2168 | parser.add_option_group(opts) 2169 | 2170 | opts = OptionGroup(parser, 'Optional') 2171 | opts.add_option('-i', '--update-interval', type='int', dest='interval', 2172 | help='update interval in seconds (1-30, default: 3)', default=3) 2173 | opts.add_option('-m', '--mode', type='int', dest='mode', 2174 | help='start in specific mode (1-5, default: 1)', default=1) 2175 | opts.add_option('-n', '--read-only', action='store_true', dest='ro', 2176 | help='disable the cli and query for stats only') 2177 | parser.add_option_group(opts) 2178 | 2179 | opts = OptionGroup(parser, 'Filters', 2180 | 'Note: All filter options may be given multiple times.') 2181 | opts.add_option('-f', '--filter', action='append', dest='stat_filter', 2182 | default=[], metavar='FILTER', 2183 | help='stat filter in format " "') 2184 | opts.add_option('-p', '--proxy', action='append', dest='proxy_filter', 2185 | default=[], metavar='PROXY', 2186 | help='proxy filter in format ""') 2187 | parser.add_option_group(opts) 2188 | 2189 | opts, args = parser.parse_args() 2190 | 2191 | if not 1 <= opts.interval <= 30: 2192 | log('invalid update interval: %d' % opts.interval) 2193 | sys.exit(1) 2194 | if not 1 <= opts.mode <= 5: 2195 | log('invalid mode: %d' % opts.mode) 2196 | sys.exit(1) 2197 | if len(opts.stat_filter) + len(opts.proxy_filter) > 50: 2198 | log('filter limit exceeded (50)') 2199 | sys.exit(1) 2200 | if opts.ro and opts.mode == 5: 2201 | log('cli not available in read-only mode') 2202 | sys.exit(1) 2203 | if opts.socket and opts.tcp_socket: 2204 | log('Specify either --unix-socket OR --tcp-socket') 2205 | parser.print_help() 2206 | sys.exit(1) 2207 | if not opts.socket and not opts.tcp_socket: 2208 | parser.print_help() 2209 | sys.exit(0) 2210 | if opts.socket and not os.access(opts.socket, os.R_OK | os.W_OK): 2211 | log('insufficient permissions for socket path %s' % opts.socket) 2212 | sys.exit(2) 2213 | 2214 | if opts.socket: 2215 | socket = Socket(opts.socket, opts.ro) 2216 | else: 2217 | socket = Socket(opts.tcp_socket, opts.ro, True) 2218 | 2219 | data = SocketData(socket) 2220 | screen = Screen(data, opts.mode) 2221 | 2222 | signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(0)) 2223 | 2224 | try: 2225 | try: 2226 | socket.connect() 2227 | screen.setup() 2228 | 2229 | # Register filters 2230 | data.register_stat_filter(opts.stat_filter) 2231 | data.register_proxy_filter(opts.proxy_filter) 2232 | 2233 | while True: 2234 | try: 2235 | mainloop(screen, opts.interval) 2236 | except StopIteration: 2237 | break 2238 | except KeyboardInterrupt: 2239 | break 2240 | except CursesError as e: 2241 | screen.reset() 2242 | log('curses error: %s, restarting...' % e) 2243 | time.sleep(1) 2244 | screen.recover() 2245 | 2246 | except ValueError as e: 2247 | screen.reset() 2248 | log('value error: %s' % e) 2249 | sys.exit(1) 2250 | except RuntimeError as e: 2251 | screen.reset() 2252 | log('runtime error: %s' % e) 2253 | sys.exit(1) 2254 | except SocketError as e: 2255 | screen.reset() 2256 | log('socket error: %s' % e) 2257 | sys.exit(2) 2258 | 2259 | finally: 2260 | screen.reset() 2261 | socket.close() 2262 | 2263 | sys.exit(0) 2264 | 2265 | # vim: et sw=4 sts=4 ts=4 tw=78 fdn=1 fdm=indent 2266 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | 15 | .PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest 16 | 17 | help: 18 | @echo "Please use \`make ' where is one of" 19 | @echo " html to make standalone HTML files" 20 | @echo " dirhtml to make HTML files named index.html in directories" 21 | @echo " pickle to make pickle files" 22 | @echo " json to make JSON files" 23 | @echo " htmlhelp to make HTML files and a HTML help project" 24 | @echo " qthelp to make HTML files and a qthelp project" 25 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 26 | @echo " changes to make an overview of all changed/added/deprecated items" 27 | @echo " linkcheck to check all external links for integrity" 28 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 29 | 30 | clean: 31 | -rm -rf $(BUILDDIR)/* 32 | 33 | html: 34 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 35 | @echo 36 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 37 | 38 | dirhtml: 39 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 40 | @echo 41 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 42 | 43 | pickle: 44 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 45 | @echo 46 | @echo "Build finished; now you can process the pickle files." 47 | 48 | json: 49 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 50 | @echo 51 | @echo "Build finished; now you can process the JSON files." 52 | 53 | htmlhelp: 54 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 55 | @echo 56 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 57 | ".hhp project file in $(BUILDDIR)/htmlhelp." 58 | 59 | qthelp: 60 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 61 | @echo 62 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 63 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 64 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/HATop.qhcp" 65 | @echo "To view the help file:" 66 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/HATop.qhc" 67 | 68 | latex: 69 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 70 | @echo 71 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 72 | @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ 73 | "run these through (pdf)latex." 74 | 75 | changes: 76 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 77 | @echo 78 | @echo "The overview file is in $(BUILDDIR)/changes." 79 | 80 | linkcheck: 81 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 82 | @echo 83 | @echo "Link check complete; look for any errors in the above output " \ 84 | "or in $(BUILDDIR)/linkcheck/output.txt." 85 | 86 | doctest: 87 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 88 | @echo "Testing of doctests in the sources finished, look at the " \ 89 | "results in $(BUILDDIR)/doctest/output.txt." 90 | -------------------------------------------------------------------------------- /doc/bugs.rst: -------------------------------------------------------------------------------- 1 | .. _bugs: 2 | 3 | 4 | ******************** 5 | Bugs and suggestions 6 | ******************** 7 | 8 | For now, please contact us directly at bugs@feurix.org. Thanks! :-) 9 | 10 | *Please note your exact HAProxy and Python version in the bug report!* 11 | 12 | -------------------------------------------------------------------------------- /doc/build/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | -------------------------------------------------------------------------------- /doc/changes.rst: -------------------------------------------------------------------------------- 1 | .. _changes: 2 | 3 | .. include:: ../CHANGES.rst 4 | 5 | -------------------------------------------------------------------------------- /doc/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # HATop documentation build configuration file. 4 | 5 | import sys 6 | import time 7 | 8 | project = u'HATop' 9 | copyright = u'2009-%s, John Feuerstein' % time.strftime('%Y') 10 | 11 | # Import hack to get the current script version from the executable 12 | from imp import load_source 13 | sys.dont_write_bytecode = True 14 | load_source('hatop', '../bin/hatop') 15 | 16 | from hatop import __version__ as version, __version__ as release 17 | 18 | # -- General configuration ----------------------------------------------------- 19 | 20 | # Add any Sphinx extension module names here, as strings. They can be extensions 21 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 22 | extensions = [] 23 | 24 | # Add any paths that contain templates here, relative to this directory. 25 | templates_path = ['templates'] 26 | 27 | # The suffix of source filenames. 28 | source_suffix = '.rst' 29 | 30 | # The encoding of source files. 31 | source_encoding = 'utf-8' 32 | 33 | # The master toctree document. 34 | master_doc = 'contents' 35 | 36 | # The language for content autogenerated by Sphinx. Refer to documentation 37 | # for a list of supported languages. 38 | #language = None 39 | 40 | # There are two options for replacing |today|: either, you set today to some 41 | # non-false value, then it is used: 42 | today = '' 43 | # Else, today_fmt is used as the format for a strftime call. 44 | today_fmt = '%B %d, %Y' 45 | 46 | # List of documents that shouldn't be included in the build. 47 | #unused_docs = [] 48 | 49 | # List of directories, relative to source directory, that shouldn't be searched 50 | # for source files. 51 | exclude_trees = ['build'] 52 | 53 | # The reST default role (used for this markup: `text`) to use for all documents. 54 | #default_role = None 55 | 56 | # If true, '()' will be appended to :func: etc. cross-reference text. 57 | #add_function_parentheses = True 58 | 59 | # If true, the current module name will be prepended to all description 60 | # unit titles (such as .. function::). 61 | #add_module_names = True 62 | 63 | # If true, sectionauthor and moduleauthor directives will be shown in the 64 | # output. They are ignored by default. 65 | #show_authors = False 66 | 67 | # The name of the Pygments (syntax highlighting) style to use. 68 | pygments_style = 'sphinx' 69 | 70 | # A list of ignored prefixes for module index sorting. 71 | #modindex_common_prefix = [] 72 | 73 | 74 | # -- Options for HTML output --------------------------------------------------- 75 | 76 | # The theme to use for HTML and HTML Help pages. Major themes that come with 77 | # Sphinx are currently 'default' and 'sphinxdoc'. 78 | html_theme = 'default' 79 | 80 | # Theme options are theme-specific and customize the look and feel of a theme 81 | # further. For a list of options available for each theme, see the 82 | # documentation. 83 | #html_theme_options = {} 84 | 85 | # Add any paths that contain custom themes here, relative to this directory. 86 | #html_theme_path = [] 87 | 88 | # The name for this set of Sphinx documents. If None, it defaults to 89 | # " v documentation". 90 | html_title = 'HATop: Interactive ncurses client for HAProxy' 91 | 92 | # A shorter title for the navigation bar. Default is the same as html_title. 93 | html_short_title = 'HATop' 94 | 95 | # The name of an image file (relative to this directory) to place at the top 96 | # of the sidebar. 97 | #html_logo = None 98 | 99 | # The name of an image file (within the static path) to use as favicon of the 100 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 101 | # pixels large. 102 | #html_favicon = None 103 | 104 | # Add any paths that contain custom static files (such as style sheets) here, 105 | # relative to this directory. They are copied after the builtin static files, 106 | # so a file named "default.css" will overwrite the builtin "default.css". 107 | html_static_path = ['static'] 108 | 109 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 110 | # using the given strftime format. 111 | html_last_updated_fmt = '%b %d, %Y' 112 | 113 | # If true, SmartyPants will be used to convert quotes and dashes to 114 | # typographically correct entities. 115 | html_use_smartypants = True 116 | 117 | # Custom sidebar templates, maps document names to template names. 118 | html_sidebars = { 119 | 'index': 'indexsidebar.html', 120 | } 121 | 122 | # Additional templates that should be rendered to pages, maps page names to 123 | # template names. 124 | html_additional_pages = { 125 | 'index': 'indexcontent.html', 126 | } 127 | 128 | 129 | 130 | # If false, no module index is generated. 131 | html_use_modindex = False 132 | 133 | # If false, no index is generated. 134 | html_use_index = False 135 | 136 | # If true, the index is split into individual pages for each letter. 137 | html_split_index = False 138 | 139 | # If true, links to the reST sources are added to the pages. 140 | html_show_sourcelink = True 141 | 142 | # If true, an OpenSearch description file will be output, and all pages will 143 | # contain a tag referring to it. The value of this option must be the 144 | # base URL from which the finished HTML is served. 145 | #html_use_opensearch = '' 146 | 147 | # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). 148 | #html_file_suffix = '' 149 | 150 | # Output file base name for HTML help builder. 151 | htmlhelp_basename = 'hatopdoc' 152 | 153 | 154 | # -- Options for LaTeX output -------------------------------------------------- 155 | 156 | # The paper size ('letter' or 'a4'). 157 | latex_paper_size = 'a4' 158 | 159 | # The font size ('10pt', '11pt' or '12pt'). 160 | #latex_font_size = '10pt' 161 | 162 | # Grouping the document tree into LaTeX files. List of tuples 163 | # (source start file, target name, title, author, documentclass [howto/manual]). 164 | latex_documents = [ 165 | ('index', 'HATop.tex', u'HATop Documentation', 166 | u'John Feuerstein', 'manual'), 167 | ] 168 | 169 | # The name of an image file (relative to this directory) to place at the top of 170 | # the title page. 171 | #latex_logo = None 172 | 173 | # For "manual" documents, if this is true, then toplevel headings are parts, 174 | # not chapters. 175 | #latex_use_parts = False 176 | 177 | # Additional stuff for the LaTeX preamble. 178 | #latex_preamble = '' 179 | 180 | # Documents to append as an appendix to all manuals. 181 | #latex_appendices = [] 182 | 183 | # If false, no module index is generated. 184 | #latex_use_modindex = True 185 | -------------------------------------------------------------------------------- /doc/contents.rst: -------------------------------------------------------------------------------- 1 | %%%%%%% 2 | HATop 3 | %%%%%%% 4 | 5 | .. toctree:: 6 | 7 | index.rst 8 | changes.rst 9 | readme.rst 10 | install.rst 11 | screenshots.rst 12 | keybinds.rst 13 | license.rst 14 | bugs.rst 15 | 16 | -------------------------------------------------------------------------------- /doc/images/0-help.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jhunt/hatop/0c0a392d319ed495a55f8ad29291c4a7cbd5077a/doc/images/0-help.png -------------------------------------------------------------------------------- /doc/images/1-status.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jhunt/hatop/0c0a392d319ed495a55f8ad29291c4a7cbd5077a/doc/images/1-status.png -------------------------------------------------------------------------------- /doc/images/2-traffic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jhunt/hatop/0c0a392d319ed495a55f8ad29291c4a7cbd5077a/doc/images/2-traffic.png -------------------------------------------------------------------------------- /doc/images/3-http.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jhunt/hatop/0c0a392d319ed495a55f8ad29291c4a7cbd5077a/doc/images/3-http.png -------------------------------------------------------------------------------- /doc/images/4-errors.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jhunt/hatop/0c0a392d319ed495a55f8ad29291c4a7cbd5077a/doc/images/4-errors.png -------------------------------------------------------------------------------- /doc/images/5-cli-help.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jhunt/hatop/0c0a392d319ed495a55f8ad29291c4a7cbd5077a/doc/images/5-cli-help.png -------------------------------------------------------------------------------- /doc/images/5-cli.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jhunt/hatop/0c0a392d319ed495a55f8ad29291c4a7cbd5077a/doc/images/5-cli.png -------------------------------------------------------------------------------- /doc/index.rst: -------------------------------------------------------------------------------- 1 | %%%%%%% 2 | Index 3 | %%%%%%% 4 | -------------------------------------------------------------------------------- /doc/install.rst: -------------------------------------------------------------------------------- 1 | .. _install: 2 | 3 | .. include:: ../INSTALL.rst 4 | 5 | -------------------------------------------------------------------------------- /doc/keybinds.rst: -------------------------------------------------------------------------------- 1 | .. _keybinds: 2 | 3 | .. include:: ../KEYBINDS 4 | 5 | -------------------------------------------------------------------------------- /doc/license.rst: -------------------------------------------------------------------------------- 1 | .. _license: 2 | 3 | 4 | ********************* 5 | License and Copyright 6 | ********************* 7 | 8 | HATop, all of it's modules and this documentation is: 9 | 10 | Copyright © 2009-2011 John Feuerstein. All rights reserved. 11 | 12 | ------- 13 | 14 | .. literalinclude:: ../LICENSE 15 | -------------------------------------------------------------------------------- /doc/readme.rst: -------------------------------------------------------------------------------- 1 | .. _readme: 2 | 3 | .. include:: ../README.rst 4 | 5 | -------------------------------------------------------------------------------- /doc/screenshots.rst: -------------------------------------------------------------------------------- 1 | .. _screenshots: 2 | 3 | 4 | *********** 5 | Screenshots 6 | *********** 7 | 8 | **Short screenshot tour showing all screen modes / viewports in action.** 9 | 10 | Global header reference (visible in all modes):: 11 | 12 | Node configured name of the haproxy node 13 | Uptime runtime since haproxy was initially started 14 | Pipes pipes are currently used for kernel-based tcp slicing 15 | Procs number of haproxy processes 16 | Tasks number of actice process tasks 17 | Queue number of queued process tasks (run queue) 18 | Proxies number of configured proxies 19 | Services number of configured services 20 | 21 | 22 | Online Help 23 | =========== 24 | 25 | Screenshot: 26 | 27 | .. image:: images/0-help.png 28 | 29 | 30 | 1: The default mode with health, session and queue statistics 31 | ============================================================= 32 | 33 | Screenshot: 34 | 35 | .. image:: images/1-status.png 36 | 37 | Header reference:: 38 | 39 | NAME name of the proxy and his services 40 | W configured weight of the service 41 | STATUS service status (UP/DOWN/NOLB/MAINT/MAINT(via)...) 42 | CHECK status of last health check (see status reference below) 43 | 44 | ACT server is active (server), number of active servers (backend) 45 | BCK server is backup (server), number of backup servers (backend) 46 | QCUR current queued requests 47 | QMAX max queued requests 48 | SCUR current sessions 49 | SMAX max sessions 50 | SLIM sessions limit 51 | STOT total sessions 52 | 53 | 54 | 2: Connection and request rates as well as traffic stats 55 | ======================================================== 56 | 57 | Screenshot: 58 | 59 | .. image:: images/2-traffic.png 60 | 61 | Header reference:: 62 | 63 | NAME name of the proxy and his services 64 | W configured weight of the service 65 | STATUS service status (UP/DOWN/NOLB/MAINT/MAINT(via)...) 66 | 67 | LBTOT total number of times a server was selected 68 | RATE number of sessions per second over last elapsed second 69 | RLIM limit on new sessions per second 70 | RMAX max number of new sessions per second 71 | BIN bytes in (IEEE 1541-2002) 72 | BOUT bytes out (IEEE 1541-2002) 73 | 74 | 75 | 3: Various statistical information related to HTTP 76 | ================================================== 77 | 78 | Screenshot: 79 | 80 | .. image:: images/3-http.png 81 | 82 | Header reference:: 83 | 84 | NAME name of the proxy and his services 85 | W configured weight of the service 86 | STATUS service status (UP/DOWN/NOLB/MAINT/MAINT(via)...) 87 | 88 | RATE HTTP requests per second over last elapsed second 89 | RMAX max number of HTTP requests per second observed 90 | RTOT total number of HTTP requests received 91 | 1xx number of HTTP responses with 1xx code 92 | 2xx number of HTTP responses with 2xx code 93 | 3xx number of HTTP responses with 3xx code 94 | 4xx number of HTTP responses with 4xx code 95 | 5xx number of HTTP responses with 5xx code 96 | ?xx number of HTTP responses with other codes (protocol error) 97 | 98 | 99 | 4: Health info, various error counters and downtimes 100 | ==================================================== 101 | 102 | Screenshot: 103 | 104 | .. image:: images/4-errors.png 105 | 106 | Header reference:: 107 | 108 | NAME name of the proxy and his services 109 | W configured weight of the service 110 | STATUS service status (UP/DOWN/NOLB/MAINT/MAINT(via)...) 111 | CHECK status of last health check (see status reference below) 112 | 113 | CF number of failed checks 114 | CD number of UP->DOWN transitions 115 | CL last status change 116 | ECONN connection errors 117 | EREQ request errors 118 | ERSP response errors 119 | DREQ denied requests 120 | DRSP denied responses 121 | DOWN total downtime 122 | 123 | 124 | 5: The embedded command line client 125 | =================================== 126 | 127 | Screenshots: 128 | 129 | .. image:: images/5-cli.png 130 | 131 | .. raw:: html 132 | 133 |
134 |
135 | 136 | .. image:: images/5-cli-help.png 137 | 138 | 139 | -------------------------------------------------------------------------------- /doc/static/default.css: -------------------------------------------------------------------------------- 1 | /** 2 | * Sphinx stylesheet -- default theme 3 | * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 4 | */ 5 | 6 | @import url("basic.css"); 7 | 8 | /* -- page layout ----------------------------------------------------------- */ 9 | 10 | body { 11 | font-family: sans-serif; 12 | font-size: 100%; 13 | background-color: #11303d; 14 | color: #000; 15 | margin: 0; 16 | padding: 0; 17 | } 18 | 19 | div.document { 20 | background-color: #1c4e63; 21 | } 22 | 23 | div.documentwrapper { 24 | float: left; 25 | width: 100%; 26 | } 27 | 28 | div.bodywrapper { 29 | margin: 0 0 0 230px; 30 | } 31 | 32 | div.body { 33 | background-color: #ffffff; 34 | color: #000000; 35 | padding: 0 20px 30px 20px; 36 | } 37 | 38 | div.footer { 39 | color: #ffffff; 40 | width: 100%; 41 | padding: 9px 0 9px 0; 42 | text-align: center; 43 | font-size: 75%; 44 | } 45 | 46 | div.footer a { 47 | color: #ffffff; 48 | text-decoration: underline; 49 | } 50 | 51 | div.related { 52 | background-color: #133f52; 53 | line-height: 30px; 54 | color: #ffffff; 55 | } 56 | 57 | div.related a { 58 | color: #ffffff; 59 | } 60 | 61 | div.sphinxsidebar { 62 | } 63 | 64 | div.sphinxsidebar h3 { 65 | font-family: 'Trebuchet MS', sans-serif; 66 | color: #ffffff; 67 | font-size: 1.4em; 68 | font-weight: normal; 69 | margin: 0; 70 | padding: 0; 71 | } 72 | 73 | div.sphinxsidebar h3 a { 74 | color: #ffffff; 75 | } 76 | 77 | div.sphinxsidebar h4 { 78 | font-family: 'Trebuchet MS', sans-serif; 79 | color: #ffffff; 80 | font-size: 1.3em; 81 | font-weight: normal; 82 | margin: 5px 0 0 0; 83 | padding: 0; 84 | } 85 | 86 | div.sphinxsidebar p { 87 | color: #ffffff; 88 | } 89 | 90 | div.sphinxsidebar p.topless { 91 | margin: 5px 10px 10px 10px; 92 | } 93 | 94 | div.sphinxsidebar ul { 95 | margin: 10px; 96 | padding: 0; 97 | color: #ffffff; 98 | } 99 | 100 | div.sphinxsidebar a { 101 | color: #98dbcc; 102 | } 103 | 104 | div.sphinxsidebar input { 105 | border: 1px solid #11303D; 106 | font-family: sans-serif; 107 | font-size: 1em; 108 | } 109 | 110 | div.sphinxsidebar input.donate { 111 | margin-top: 10px; 112 | margin-bottom: 30px; 113 | margin-left: 30px; 114 | border: 0px; 115 | } 116 | 117 | /* -- body styles ----------------------------------------------------------- */ 118 | 119 | a { 120 | color: #355f7c; 121 | text-decoration: none; 122 | } 123 | 124 | a:hover { 125 | text-decoration: underline; 126 | } 127 | 128 | div.body p, div.body dd, div.body li { 129 | text-align: justify; 130 | line-height: 130%; 131 | } 132 | 133 | div.body h1, 134 | div.body h2, 135 | div.body h3, 136 | div.body h4, 137 | div.body h5, 138 | div.body h6 { 139 | font-family: 'Trebuchet MS', sans-serif; 140 | background-color: #f2f2f2; 141 | font-weight: normal; 142 | color: #20435c; 143 | border-bottom: 1px solid #ccc; 144 | margin: 20px -20px 10px -20px; 145 | padding: 3px 0 3px 10px; 146 | } 147 | 148 | div.body h1 { margin-top: 0; font-size: 200%; } 149 | div.body h2 { font-size: 160%; } 150 | div.body h3 { font-size: 140%; } 151 | div.body h4 { font-size: 120%; } 152 | div.body h5 { font-size: 110%; } 153 | div.body h6 { font-size: 100%; } 154 | 155 | a.headerlink { 156 | color: #c60f0f; 157 | font-size: 0.8em; 158 | padding: 0 4px 0 4px; 159 | text-decoration: none; 160 | } 161 | 162 | a.headerlink:hover { 163 | background-color: #c60f0f; 164 | color: white; 165 | } 166 | 167 | div.body p, div.body dd, div.body li { 168 | text-align: justify; 169 | line-height: 130%; 170 | } 171 | 172 | div.body p.primer { 173 | line-height: 130%; 174 | font-size: 120%; 175 | } 176 | 177 | div.body p.description { 178 | text-align: justify; 179 | line-height: 130%; 180 | max-width: 800px; 181 | } 182 | 183 | div.body hr { 184 | border: 0px; 185 | height: 10px; 186 | } 187 | 188 | div.body li.features { 189 | margin-left: 100px; 190 | text-align: justify; 191 | line-height: 130%; 192 | } 193 | 194 | 195 | div.admonition p.admonition-title + p { 196 | display: inline; 197 | } 198 | 199 | div.note { 200 | background-color: #eee; 201 | border: 1px solid #ccc; 202 | } 203 | 204 | div.seealso { 205 | background-color: #ffc; 206 | border: 1px solid #ff6; 207 | } 208 | 209 | div.topic { 210 | background-color: #eee; 211 | } 212 | 213 | div.warning { 214 | background-color: #ffe4e4; 215 | border: 1px solid #f66; 216 | } 217 | 218 | p.admonition-title { 219 | display: inline; 220 | } 221 | 222 | p.admonition-title:after { 223 | content: ":"; 224 | } 225 | 226 | pre { 227 | padding: 5px; 228 | background-color: #eeffcc; 229 | color: #333333; 230 | line-height: 120%; 231 | border: 1px solid #ac9; 232 | border-left: none; 233 | border-right: none; 234 | } 235 | 236 | tt { 237 | background-color: #ecf0f3; 238 | padding: 0 1px 0 1px; 239 | font-size: 0.95em; 240 | } 241 | 242 | /* -- custom ----------------------------------------------------------- */ 243 | 244 | a.download { 245 | display: table; 246 | background: #F0F0F0; 247 | padding: 5px; 248 | margin-top: 10px; 249 | text-decoration: none; 250 | } 251 | a.download:link { 252 | color: #355f7c; 253 | text-decoration: none; 254 | } 255 | a.download:visited { 256 | color: #355f7c; 257 | text-decoration: none; 258 | } 259 | a.download:hover { 260 | color: #000000; 261 | text-decoration: none; 262 | } 263 | 264 | table.docutils { 265 | border:0 solid #DDCCEE; 266 | border-collapse:collapse; 267 | } 268 | table.docutils td, table.docutils th { 269 | background-color:#EEEEFF; 270 | border-left:0 none; 271 | padding:2px 5px; 272 | } 273 | table.field-list td, table.field-list th { 274 | border:0 none !important; 275 | } 276 | table.footnote td, table.footnote th { 277 | border:0 none !important; 278 | } 279 | table.docutils th { 280 | background-color:#EEDDEE; 281 | border-top:1px solid #CCAACC; 282 | } 283 | 284 | -------------------------------------------------------------------------------- /doc/static/disk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jhunt/hatop/0c0a392d319ed495a55f8ad29291c4a7cbd5077a/doc/static/disk.png -------------------------------------------------------------------------------- /doc/static/glider.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jhunt/hatop/0c0a392d319ed495a55f8ad29291c4a7cbd5077a/doc/static/glider.png -------------------------------------------------------------------------------- /doc/static/gplv3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jhunt/hatop/0c0a392d319ed495a55f8ad29291c4a7cbd5077a/doc/static/gplv3.png -------------------------------------------------------------------------------- /doc/static/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jhunt/hatop/0c0a392d319ed495a55f8ad29291c4a7cbd5077a/doc/static/logo.png -------------------------------------------------------------------------------- /doc/templates/indexcontent.html: -------------------------------------------------------------------------------- 1 | {% extends "defindex.html" %} 2 | {% block body %} 3 |

{{ docstitle|e }}

4 | 5 | GPLv3 License 6 | 7 |

8 | Welcome! This is 9 | {% block description %}the documentation for {{ project|e }} 10 | version {{ release|e }}{% if last_updated %}, last updated {{ last_updated|e }}{% endif %}{% endblock %}. 11 |

12 | 13 |

What is HATop?

14 |

15 | 16 | HATop is an interactive ncurses client and real-time monitoring,
17 | statistics displaying tool for the 18 | HAProxy 19 | TCP/HTTP load balancer. 20 |
21 |

22 | 23 |

24 | HATop's appearance is similar to 25 | top(1). 26 | It supports various modes for detailed statistics of all configured proxies 27 | and services in near realtime. In addition, it features an interactive CLI for 28 | the haproxy unix socket. This allows administrators to control the given 29 | haproxy instance (change server weight, put servers into maintenance mode, ...) 30 | directly out of hatop (using keybinds or the CLI) and monitor the results 31 | immediately. 32 |

33 | 34 |

35 | HATop is written in pure Python 36 | and has no external dependencies.
37 | It requires Python 2.4 or later and HAProxy 1.4 or later. 38 |

39 | 40 |

41 | 42 | 43 | Download 44 | Download HATop v{{ version }} [hatop-{{ version }}.tar.gz] 45 | 46 | 47 |

48 | 49 |
50 | 51 | {% block tables %} 52 |

Documentation:

53 | 54 | 55 | 61 | 67 | 68 |
56 | 58 | 60 | 62 | 64 | 66 |
69 | 70 |

Meta information:

71 | 72 | 73 | 80 | 81 |
74 | 76 | 77 | 79 |
82 | {% endblock %} 83 | 84 |

Quickstart

85 | 86 |

87 | First of all, make sure you have the stats socket enabled in the haproxy config: 88 |

89 |
90 |
global
 91 |   stats socket /var/run/haproxy/haproxy.sock mode 0600 level admin
 92 | 
93 |
94 | 95 |

96 | That's all you need to use HATop: 97 |

98 |
99 |
100 | $ hatop -s /var/run/haproxy/haproxy.sock
101 | 
102 |
103 | 104 |

105 | See also: 106 | HATop Installation 107 |

108 | 109 |

Development

110 | 111 |

112 | Getting the HATop source code using Git: 113 |

114 |
115 |
116 | $ git clone git://labs.feurix.org/feurix/admin/hatop.git
117 | 
118 |
119 | 120 |

121 | See also: 122 | Git Webinterface, 123 | Source Browser 124 |

125 | 126 | {% endblock %} 127 | -------------------------------------------------------------------------------- /doc/templates/indexsidebar.html: -------------------------------------------------------------------------------- 1 |

Documentation

2 | 9 | 10 |

Examples

11 | 14 | 15 |

Resources

16 | 21 | 22 |

Downloads

23 | 28 | 29 |

Contact us

30 | 31 | 32 |

Support us

33 |
34 | 35 | 36 | 38 | 40 |
41 | -------------------------------------------------------------------------------- /doc/templates/layout.html: -------------------------------------------------------------------------------- 1 | {% extends "!layout.html" %} 2 | {% block rootrellink %} 3 |
  • 5 |
  • Feurix Free Open Source Projects{{ reldelim1 }}
  • 6 |
  • {{ shorttitle }}{{ reldelim1 }}
  • 7 | {% endblock %} 8 | {% block extrahead %} 9 | 10 | {{ super() }} 11 | {% endblock %} 12 | {% block sidebarlogo %} 13 | 14 | HATop Project 15 | 16 | {% endblock %} 17 | {% block footer %} 18 | 23 | {% endblock %} 24 | -------------------------------------------------------------------------------- /man/hatop.1: -------------------------------------------------------------------------------- 1 | .TH HATOP 1 "19 August 2010" 2 | .SH NAME 3 | HATop \- interactive ncurses client for haproxy 4 | .SH SYNOPSIS 5 | hatop \-s \fISOCKET\fB [\fIOPTIONS\fB] 6 | .SH DESCRIPTION 7 | HATop is an interactive ncurses client and real\-time monitoring, 8 | statistics displaying tool for the HAProxy TCP/HTTP load balancer. 9 | 10 | HATop's appearance is similar to top(1). It supports various modes for 11 | detailed statistics of all configured proxies and services in near realtime. 12 | In addition, it features an interactive CLI for the haproxy unix socket. 13 | This allows administrators to control the given haproxy instance 14 | (change server weight, put servers into maintenance mode, ...) directly out 15 | of hatop (using keybinds or the CLI) and monitor the results immediately. 16 | 17 | HATop uses a unix domain socket to communicate with HAProxy. This can be 18 | configured in the HAProxy configuration using the "stats socket" option. 19 | To enable all of HATop's features the "level" parameter of this option 20 | should be set to "admin". 21 | .SH OPTIONS 22 | .TP 23 | \fB\-\-version\fP 24 | show version number and exit 25 | .TP 26 | \fB\-h, \-\-help\fP 27 | show help message and exit 28 | .TP 29 | \fB\-s \fISOCKET\fB, \-\-unix\-socket=\fISOCKET\fP 30 | path to the haproxy stats socket 31 | .TP 32 | \fB\-i \fIINTERVAL\fB, \-\-update\-interval=\fIINTERVAL\fP 33 | update interval in seconds (1\-30, default: 3) 34 | .TP 35 | \fB\-m \fIMODE\fB, \-\-mode=\fIMODE\fP 36 | start in specific mode (1\-5, default: 1) 37 | .TP 38 | \fB\-n, \-\-read\-only\fP 39 | disable the cli and query for stats only 40 | 41 | .PP 42 | The following filter options may be given multiple times: 43 | .TP 44 | \fB\-f \fIFILTER\fB, \-\-filter=\fIFILTER\fP 45 | stat filter in format " " 46 | .TP 47 | \fB\-p \fIPROXY\fB, \-\-proxy=\fIPROXY\fP 48 | proxy filter in format "" 49 | .SH KEYBINDS 50 | .TP 51 | \fBHh?\fP 52 | Display help screen 53 | .TP 54 | \fBQq\fP 55 | Quit 56 | .TP 57 | \fBTAB\fP 58 | Cycle mode forwards 59 | .TP 60 | \fBS\-TAB\fP 61 | Cycle mode backwards 62 | .TP 63 | \fBESC\-n\fP 64 | Switch to mode n, where n is the numeric mode id 65 | .TP 66 | \fBESC\fP 67 | Jump to previous mode 68 | .TP 69 | \fBENTER\fP 70 | Display hotkey menu for selected service 71 | .TP 72 | \fBSPACE\fP 73 | Copy and paste selected service identifier to the CLI 74 | .TP 75 | \fBUP\fP / \fBDOWN\fP / \fBPGUP\fP / \fBPGDOWN\fP / \fBHOME\fP / \fBEND\fP 76 | Scroll the stat views to select a given service 77 | .SH HOTKEYS 78 | .TP 79 | \fBF1\fP 80 | Enable server on all backends (return from maintenance mode) 81 | .TP 82 | \fBF2\fP 83 | Disable server on all backends (put into maintenance mode) 84 | .TP 85 | \fBF3\fP 86 | Drain server on all backends (prepare for maintenance mode, don't allow new connections) 87 | .TP 88 | \fBF4\fP 89 | Restore initial server weight 90 | 91 | .TP 92 | \fBF5\fP 93 | Decrease server weight: \- 10 94 | .TP 95 | \fBF6\fP 96 | Decrease server weight: \- 1 97 | .TP 98 | \fBF7\fP 99 | Increase server weight: + 1 100 | .TP 101 | \fBF8\fP 102 | Increase server weight: + 10 103 | 104 | .TP 105 | \fBF9\fP 106 | Enable server on one backend (return from maintenance mode) 107 | .TP 108 | \fBF10\fP 109 | Disable server on one backend (put into maintenance mode) 110 | .TP 111 | \fBF11\fP 112 | Drain server on one backend (prepare for maintenance mode, don't allow new connections) 113 | .SH SEE ALSO 114 | .BR haproxy (1) 115 | 116 | A much better documentation can be found online: 117 | .PP 118 | http://feurix.org/projects/hatop/ 119 | .SH AUTHOR 120 | HATop and this man page was written by John Feuerstein. 121 | -------------------------------------------------------------------------------- /scripts/package.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ############################ 4 | # Exported variables. # 5 | ############################ 6 | 7 | export BASE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" 8 | 9 | if [ $# -lt 1 ]; then 10 | echo "$0 " 11 | exit 1 12 | fi 13 | 14 | PKG_TYPE=$1 15 | 16 | PKG_SCRIPT="${BASE_DIR}/package_${PKG_TYPE}.sh" 17 | 18 | # Check and call script 19 | if [ ! -f $PKG_SCRIPT ]; then 20 | echo "$PKG_SCRIPT not found" 21 | exit 1 22 | fi 23 | 24 | # Info 25 | export PACKAGE_NAME="hatop" 26 | export PACKAGE_DESCRIPTION="An Interactive ncurses Client for HAProxy" 27 | export PACKAGE_VERSION=$(cat ${BASE_DIR}/../bin/hatop | sed -n -E "s/^__version__\s+=\s+'([0-9\.]+)'\$/\1/p") 28 | export PACKAGE_PROGRAM="hatop" 29 | 30 | # Directories. 31 | export PACKAGE_PREFIX=/usr 32 | export PACKAGE_BINDIR=${PACKAGE_PREFIX}/bin 33 | export PACKAGE_SHAREDIR=${PACKAGE_PREFIX}/share/${PACKAGE_NAME} 34 | export PACKAGE_MANDIR=${PACKAGE_PREFIX}/share/man 35 | export PACKAGE_OUTPUTDIR="${BASE_DIR}/tmp" 36 | export PACKAGE_TMPDIR="${PACKAGE_OUTPUTDIR}/pkg_${PKG_TYPE}" 37 | 38 | 39 | . $PKG_SCRIPT 40 | -------------------------------------------------------------------------------- /scripts/package_deb.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo $BASE_DIR 4 | 5 | if [[ -f /etc/upstream-release/lsb-release ]]; then 6 | source /etc/upstream-release/lsb-release 7 | elif [[ -f /etc/lsb-release ]]; then 8 | source /etc/lsb-release 9 | else 10 | echo "ERROR: could not determine debian release." 11 | exit 1 12 | fi 13 | 14 | DISTRIB_ID=$(echo $DISTRIB_ID | tr '[:upper:]' '[:lower:]') 15 | DISTRIB_RELEASE_NUM=$(echo ${DISTRIB_RELEASE} | sed "s/\.//") 16 | 17 | # Default to 1 if no release is set. 18 | if [[ -z $RELEASE ]]; then 19 | RELEASE="1" 20 | fi 21 | 22 | PACKAGE_FULLNAME="${PACKAGE_NAME}_${PACKAGE_VERSION}-${RELEASE}-${DISTRIB_ID}-${DISTRIB_RELEASE}_all" 23 | 24 | rm -fr ${PACKAGE_TMPDIR} 25 | 26 | # >= 20.04 does not have python 2.x, so depend on python3 and the python-is-python3 27 | # package that symlinks /usr/bin/python. 28 | if [ ${DISTRIB_RELEASE_NUM} -ge 2004 ]; then 29 | DEPENDS="python3, python-is-python3" 30 | else : 31 | DEPENDS="python (>= 2.4)" 32 | fi 33 | 34 | # Create debian files. 35 | mkdir -p ${PACKAGE_TMPDIR}/DEBIAN 36 | echo "Package: ${PACKAGE_NAME} 37 | Version: ${PACKAGE_VERSION}-${RELEASE} 38 | Section: admin 39 | Priority: extra 40 | Architecture: all 41 | Depends: $DEPENDS 42 | Homepage: https://github.com/jhunt/hatop 43 | Maintainer: James Hunt 44 | Description: ${PACKAGE_DESCRIPTION}" &> ${PACKAGE_TMPDIR}/DEBIAN/control 45 | 46 | if [ -f "${BASE_DIR}/deb_custom_control" ]; then 47 | cat "${BASE_DIR}/deb_custom_control" >> ${PACKAGE_TMPDIR}/DEBIAN/control 48 | fi 49 | 50 | cat ${PACKAGE_TMPDIR}/DEBIAN/control 51 | 52 | # Copy program 53 | mkdir -p ${PACKAGE_TMPDIR}/${PACKAGE_BINDIR} 54 | cp ${BASE_DIR}/../bin/${PACKAGE_PROGRAM} ${PACKAGE_TMPDIR}/${PACKAGE_BINDIR}/${PACKAGE_NAME} 55 | 56 | # Copy man file 57 | mkdir -p ${PACKAGE_TMPDIR}/${PACKAGE_MANDIR}/man1 58 | cp ${BASE_DIR}/../man/hatop.1 ${PACKAGE_TMPDIR}/${PACKAGE_MANDIR}/man1 59 | gzip ${PACKAGE_TMPDIR}/${PACKAGE_MANDIR}/man1/hatop.1 60 | 61 | # Copy some documentation files 62 | mkdir -p ${PACKAGE_TMPDIR}/${PACKAGE_SHAREDIR} 63 | cp ${BASE_DIR}/../CHANGES.rst \ 64 | ${BASE_DIR}/../KEYBINDS \ 65 | ${BASE_DIR}/../README.rst \ 66 | ${PACKAGE_TMPDIR}/${PACKAGE_SHAREDIR} 67 | 68 | fakeroot dpkg-deb --build ${PACKAGE_TMPDIR} ${PACKAGE_OUTPUTDIR}/${PACKAGE_FULLNAME}.deb 69 | -------------------------------------------------------------------------------- /test/.gitignore: -------------------------------------------------------------------------------- 1 | *.sock 2 | *.txt 3 | -------------------------------------------------------------------------------- /test/hatop/.gitignore: -------------------------------------------------------------------------------- 1 | /docker-compose.yml 2 | /haproxy.cfg 3 | /nginx 4 | -------------------------------------------------------------------------------- /test/hatop/README.md: -------------------------------------------------------------------------------- 1 | HATop Testing Lab 2 | ================= 3 | 4 | This directory provides a small testing lab for playing with 5 | haproxy and nginx configurations, for when you want to see a real 6 | system, but don't have enough unique content / configuration / 7 | application code to pull something together. 8 | 9 | It uses Docker and Docker Compose. To run it: 10 | 11 | ./run 12 | 13 | If you want to background the compose runs, tack on a `-d`: 14 | 15 | ./run -d 16 | 17 | This configuration currently spins up N (default: 3) nginx 18 | "application servers", each of which responds to a GET /index.html 19 | with a numbered, distinguishable response payload. Those are each 20 | proxied, individually, on ports 884X, where X ranges from 1 to N. 21 | 22 | An additional backend, on prot 8840, proxies all of the backends. 23 | 24 | To change the number of instances spun up, set the `INSTANCES` 25 | environment variable: 26 | 27 | INSTANCES=5 ./run -d 28 | 29 | You shouldn't go above N=9, because of the naive port numbering 30 | strategy (N is expected to be a single digit). 31 | -------------------------------------------------------------------------------- /test/hatop/configure: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # vim:et:sts=2:ts=2:sw=2 3 | set -eu 4 | 5 | INSTANCES=${INSTANCES:-3} 6 | 7 | rm -rf nginx/ 8 | mkdir nginx 9 | for n in $(seq 1 $INSTANCES); do 10 | cp -a template nginx/app${n} 11 | sed -e "s/{{N}}/$n/" template/index.html > nginx/app${n}/index.html 12 | done 13 | 14 | ( 15 | cat <haproxy.cfg 63 | 64 | ( 65 | cat <docker-compose.yml 90 | -------------------------------------------------------------------------------- /test/hatop/fetch: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | n=${1:-15} 3 | for x in $(seq 1 $n); do 4 | curl -s http://127.0.0.1:8840 | grep h1 5 | done | sort | uniq -c 6 | -------------------------------------------------------------------------------- /test/hatop/hatop: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | exec sudo ../../bin/hatop -s $PWD/stat/admin.sock "$@" 3 | -------------------------------------------------------------------------------- /test/hatop/run: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -eu 3 | 4 | ./configure 5 | docker-compose up "$@" 6 | -------------------------------------------------------------------------------- /test/hatop/template/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | hatop test app #{{N}} 5 | 6 | 7 |

    hatop test app #{{N}}

    8 | 9 | 10 | -------------------------------------------------------------------------------- /test/sample-socket.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Thu Apr 08 16:51:58 CEST 2010 John Feuerstein 3 | # 4 | # This script emulates the haproxy stats unix socket to help in 5 | # hatop development and to provide some (fake) sample data. 6 | 7 | SOCKET_PATH='sample-socket.sock' 8 | SOCKET_PROMPT='> ' 9 | 10 | import os 11 | import socket 12 | import sys 13 | import time 14 | 15 | if not len(sys.argv) == 3: 16 | sys.stderr.write( 17 | 'usage: %s ' 18 | ' ' 19 | '\n' % sys.argv[0]) 20 | sys.exit(1) 21 | 22 | def read_info(): 23 | with file(sys.argv[1]) as info: 24 | data = info.read() 25 | return data 26 | 27 | def read_stat(): 28 | with file(sys.argv[2]) as stat: 29 | data = stat.read() 30 | return data 31 | 32 | try: 33 | os.unlink(SOCKET_PATH) 34 | except: 35 | pass 36 | 37 | s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 38 | s.bind(SOCKET_PATH) 39 | s.listen(1) 40 | 41 | while 1: 42 | conn, addr = s.accept() 43 | 44 | while 1: 45 | data = conn.recv(1024).strip() 46 | print('--- %s' % time.ctime()) 47 | print('<<< %s' % data) 48 | if not data: 49 | continue 50 | if data == 'quit': 51 | break 52 | elif data.startswith('show info'): 53 | print('>>> info...') 54 | conn.sendall(read_info()) 55 | elif data.startswith('show stat'): 56 | print('>>> stat...') 57 | conn.sendall(read_stat()) 58 | print('>>> empty line (end of response)') 59 | conn.sendall('\n') 60 | print('>>> prompt') 61 | conn.sendall(SOCKET_PROMPT) 62 | print('--- %s\n' % time.ctime()) 63 | 64 | conn.close() 65 | 66 | --------------------------------------------------------------------------------