├── .gitignore ├── CHANGES ├── HACKING ├── INSTALL ├── KEYBINDS ├── LICENSE ├── README ├── 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 └── test ├── .gitignore └── sample-socket.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[co] 2 | *.swp 3 | *.tmp 4 | *.~ 5 | .DS_Store 6 | -------------------------------------------------------------------------------- /CHANGES: -------------------------------------------------------------------------------- 1 | ********* 2 | Changelog 3 | ********* 4 | 5 | This is a brief overview of the changes introduced by each version. 6 | 7 | For the full changelog refer to the 8 | `Git version history `_. 9 | 10 | 11 | HATop 0.7 12 | ========= 13 | 14 | This is the first public series after reaching a feature complete state. 15 | 16 | 17 | HATop 0.7.7 18 | ----------- 19 | 20 | :Date: Oct 05, 2010 21 | 22 | - Feature: Display hotkey footer when pressing ENTER on selected service. 23 | 24 | - Feature: Use string identifier ("pxname/svname") instead of numerical 25 | identifier ("#iid/#sid") for hotkey actions. 26 | 27 | - Bugfix: Display cursor and focus input if started in CLI mode. 28 | 29 | - Bugfix: Reload stat data if number of proxies or services has changed. 30 | 31 | - Bugfix: Prevent infinite size sync if screen size is larger than supported. 32 | (Jérémy Bonnet) 33 | 34 | - Docs: Add notes to INSTALL for the man page. (James Briggs) 35 | 36 | - Docs: Fix hatop(1) man page and document the new hotkey footer. 37 | 38 | 39 | HATop 0.7.6 40 | ----------- 41 | 42 | :Date: Aug 20, 2010 43 | 44 | - Bugfix: Support terminals lacking different cursor visibilities. 45 | (Matt Behrens) 46 | 47 | - Bugfix: Handle empty or incomplete info and stat data. 48 | 49 | - Bugfix: Handle unknown proxy names with the -p / --proxy filter options. 50 | 51 | - Docs: Add initial hatop(1) man page 52 | 53 | 54 | HATop 0.7.5 55 | ----------- 56 | 57 | :Date: Aug 18, 2010 58 | 59 | - Bugfix: Pressing ENTER on the embedded CLI could result in display 60 | corruption. (Cyril Bonté) 61 | 62 | - Docs: Add common packaging files CHANGES and INSTALL 63 | 64 | - Docs: Add keybind reference in KEYBINDS 65 | 66 | 67 | HATop 0.7.4 68 | ----------- 69 | 70 | :Date: Aug 16, 2010 71 | 72 | - Bugfix: Fix the expected stat CSV format. (Jim Riggs) 73 | 74 | 75 | HATop 0.7.3 76 | ----------- 77 | 78 | :Date: Aug 16, 2010 79 | 80 | - Bugfix: Restore compatibility with Python 2.4 and 2.5. 81 | 82 | 83 | HATop 0.7.2 84 | ----------- 85 | 86 | :Date: Aug 16, 2010 87 | 88 | - Bugfix: Handle socket connections to incompatible HAProxy versions. 89 | 90 | 91 | HATop 0.7.1 92 | ----------- 93 | 94 | :Date: Aug 16, 2010 95 | 96 | - Bugfix: Prevent timeout changes to the internal interactive session used to 97 | query for stats. 98 | 99 | 100 | HATop 0.7.0 101 | ----------- 102 | 103 | :Date: Aug 15, 2010 104 | 105 | - The first public and feature complete version. 106 | 107 | .. vim: tw=78 108 | -------------------------------------------------------------------------------- /HACKING: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2010 John Feuerstein 2 | # HATop hacking... 3 | 4 | Development: http://labs.feurix.org/admin/hatop/ 5 | 6 | Git: git clone git://labs.feurix.org/feurix/admin/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: -------------------------------------------------------------------------------- 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 | 31 | F4 Restore initial server weight 32 | 33 | F5 Decrease server weight: - 10 34 | F6 Decrease server weight: - 1 35 | F7 Increase server weight: + 1 36 | F8 Increase server weight: + 10 37 | 38 | F9 Enable server (return from maintenance mode) 39 | F10 Disable server (put into maintenance mode) 40 | 41 | Hotkey actions and server responses are logged on the CLI viewport. 42 | 43 | 44 | Keybinds for the command line interface 45 | ======================================= 46 | :: 47 | 48 | Key Action 49 | 50 | ALT-n / ESC-n escape the shell and display given viewport 51 | 52 | ENTER execute cmdline or display marker if input empty 53 | 54 | UP / DOWN scroll input history up or down 55 | LEFT / RIGHT move input cursor one character to the left or right 56 | HOME / END move input cursor to the beginning or end of line 57 | BACKSPACE / DEL delete one character backwards or forwards 58 | 59 | PGUP / PGDOWN scroll output history up or down 60 | 61 | -------------------------------------------------------------------------------- /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: -------------------------------------------------------------------------------- 1 | ************* 2 | Documentation 3 | ************* 4 | 5 | *Interactive ncurses client for the HAProxy unix socket* 6 | 7 | Author: John Feuerstein 8 | 9 | License: GPLv3 10 | 11 | Project URL: http://feurix.org/projects/hatop/ 12 | 13 | Mirror URL: http://code.google.com/p/hatop/ 14 | 15 | Development URL: http://labs.feurix.org/admin/hatop/ 16 | 17 | 18 | What is HATop? 19 | ============== 20 | 21 | HATop's appearance is similar to top(1). It supports various modes 22 | for detailed statistics of all configured proxies and services in near 23 | realtime. In addition, it features an interactive CLI for the haproxy 24 | unix socket. This allows administrators to control the given haproxy 25 | instance (change server weight, put servers into maintenance mode, ...) 26 | directly out of hatop and monitor the results immediately. 27 | 28 | *It is important to understand that when multiple haproxy processes are started 29 | on the same socket, any process may pick up the request and thus hatop will 30 | output stats owned solely by that process. The current haproxy-internal 31 | process id is displayed top right.* 32 | 33 | 34 | Installation 35 | ============ 36 | 37 | See ``INSTALL`` or refer to :ref:`install` 38 | 39 | 40 | Command line options 41 | ==================== 42 | 43 | Invoking hatop without options or with ``-h / --help`` results in: 44 | 45 | :: 46 | 47 | $ hatop --help 48 | Usage: hatop -s SOCKET [OPTIONS]... OR hatop -H HOST -P PORT [OPTIONS]... 49 | 50 | Options: 51 | --version show program's version number and exit 52 | -h, --help show this help message and exit 53 | 54 | Mandatory if connecting via UNIX domain socket: 55 | -s SOCKET, --unix-socket=SOCKET 56 | path to the haproxy unix socket 57 | 58 | Mandatory if connecting via TCP: 59 | -P TCPPORT, --port=TCPPORT 60 | TCP port on haproxy server 61 | -H TCPHOST, --host=TCPHOST 62 | Remote host to connect to via TCP 63 | 64 | Optional: 65 | -i INTERVAL, --update-interval=INTERVAL 66 | update interval in seconds (1-30, default: 3) 67 | -m MODE, --mode=MODE 68 | start in specific mode (1-5, default: 1) 69 | -n, --read-only disable the cli and query for stats only 70 | 71 | Filters: 72 | Note: All filter options may be given multiple times. 73 | 74 | -f FILTER, --filter=FILTER 75 | stat filter in format " " 76 | -p PROXY, --proxy=PROXY 77 | proxy filter in format "" 78 | 79 | 80 | Display mode reference 81 | ====================== 82 | 83 | See also: :ref:`screenshots` 84 | 85 | :: 86 | 87 | ID Mode Description 88 | 89 | 1 STATUS The default mode with health, session and queue statistics 90 | 2 TRAFFIC Display connection and request rates as well as traffic stats 91 | 3 HTTP Display various statistical information related to HTTP 92 | 4 ERRORS Display health info, various error counters and downtimes 93 | 5 CLI Display embedded command line client for the unix socket 94 | 95 | Keybind reference 96 | ================= 97 | 98 | See also: :ref:`keybinds` 99 | 100 | :: 101 | 102 | Key Action 103 | 104 | Hh? Display this help screen 105 | CTRL-C / Qq Quit 106 | 107 | TAB Cycle mode forwards 108 | SHIFT-TAB Cycle mode backwards 109 | ALT-n / ESC-n Switch to mode n, where n is the numeric mode id 110 | ESC-ESC Jump to previous mode 111 | 112 | ENTER Display hotkey menu for selected service 113 | SPACE Copy and paste selected service identifier to the CLI 114 | 115 | You can scroll the stat views using ``UP / DOWN / PGUP / PGDOWN / HOME / END``. 116 | 117 | The reverse colored cursor line is used to select a given service instance. 118 | 119 | An unique identifier ``[#/<#sid>]`` of the selected 120 | service is displayed bottom right. 121 | 122 | You can hit ``SPACE`` to copy and paste the identifier in string format 123 | ``pxname/svname`` to the CLI for easy re-use with some commands. 124 | 125 | For example: 126 | 127 | 1. Open the CLI 128 | 2. Type "disable server " 129 | 3. Switch back to some stat view using TAB / SHIFT-TAB 130 | 4. Select the server instance using UP / DOWN 131 | 5. Hit SPACE 132 | 133 | The result is this command line:: 134 | 135 | > disable server / 136 | 137 | Hotkeys for common administrative actions 138 | ----------------------------------------- 139 | :: 140 | 141 | Hotkey Action 142 | 143 | F4 Restore initial server weight 144 | 145 | F5 Decrease server weight: - 10 146 | F6 Decrease server weight: - 1 147 | F7 Increase server weight: + 1 148 | F8 Increase server weight: + 10 149 | 150 | F9 Enable server (return from maintenance mode) 151 | F10 Disable server (put into maintenance mode) 152 | 153 | Hotkey actions and server responses are logged on the CLI viewport. 154 | 155 | You can scroll the output on the CLI view using ``PGUP / PGDOWN``. 156 | 157 | A brief keybind reference is logged there directly after startup... 158 | 159 | 160 | Header reference 161 | ================ 162 | 163 | See also: :ref:`screenshots` 164 | 165 | :: 166 | 167 | Node configured name of the haproxy node 168 | Uptime runtime since haproxy was initially started 169 | Pipes pipes are currently used for kernel-based tcp slicing 170 | Procs number of haproxy processes 171 | Tasks number of actice process tasks 172 | Queue number of queued process tasks (run queue) 173 | Proxies number of configured proxies 174 | Services number of configured services 175 | 176 | In multiple modes 177 | ----------------- 178 | :: 179 | 180 | NAME name of the proxy and his services 181 | W configured weight of the service 182 | STATUS service status (UP/DOWN/NOLB/MAINT/MAINT(via)...) 183 | CHECK status of last health check (see status reference below) 184 | 185 | In STATUS mode 186 | -------------- 187 | :: 188 | 189 | ACT server is active (server), number of active servers (backend) 190 | BCK server is backup (server), number of backup servers (backend) 191 | QCUR current queued requests 192 | QMAX max queued requests 193 | SCUR current sessions 194 | SMAX max sessions 195 | SLIM sessions limit 196 | STOT total sessions 197 | 198 | In TRAFFIC mode 199 | --------------- 200 | :: 201 | 202 | LBTOT total number of times a server was selected 203 | RATE number of sessions per second over last elapsed second 204 | RLIM limit on new sessions per second 205 | RMAX max number of new sessions per second 206 | BIN bytes in (IEEE 1541-2002) 207 | BOUT bytes out (IEEE 1541-2002) 208 | 209 | In HTTP mode 210 | ------------ 211 | :: 212 | 213 | RATE HTTP requests per second over last elapsed second 214 | RMAX max number of HTTP requests per second observed 215 | RTOT total number of HTTP requests received 216 | 1xx number of HTTP responses with 1xx code 217 | 2xx number of HTTP responses with 2xx code 218 | 3xx number of HTTP responses with 3xx code 219 | 4xx number of HTTP responses with 4xx code 220 | 5xx number of HTTP responses with 5xx code 221 | ?xx number of HTTP responses with other codes (protocol error) 222 | 223 | In ERRORS mode 224 | -------------- 225 | :: 226 | 227 | CF number of failed checks 228 | CD number of UP->DOWN transitions 229 | CL last status change 230 | ECONN connection errors 231 | EREQ request errors 232 | ERSP response errors 233 | DREQ denied requests 234 | DRSP denied responses 235 | DOWN total downtime 236 | 237 | 238 | Health check status reference 239 | ============================= 240 | :: 241 | 242 | UNK unknown 243 | INI initializing 244 | SOCKERR socket error 245 | L4OK check passed on layer 4, no upper layers testing enabled 246 | L4TMOUT layer 1-4 timeout 247 | L4CON layer 1-4 connection problem, for example 248 | "Connection refused" (tcp rst) or "No route to host" (icmp) 249 | L6OK check passed on layer 6 250 | L6TOUT layer 6 (SSL) timeout 251 | L6RSP layer 6 invalid response - protocol error 252 | L7OK check passed on layer 7 253 | L7OKC check conditionally passed on layer 7, for example 404 with 254 | disable-on-404 255 | L7TOUT layer 7 (HTTP/SMTP) timeout 256 | L7RSP layer 7 invalid response - protocol error 257 | L7STS layer 7 response error, for example HTTP 5xx 258 | 259 | 260 | Connecting using TCP over a network 261 | =================================== 262 | 263 | Although not natively supported in HAProxy it is possible to expose the command 264 | socket to the network for remote administration. HATop now has support for this. 265 | 266 | An example of this using socat to expose the HAProxy socket can be found here: 267 | https://github.com/Wirehive/haproxy-remote 268 | -------------------------------------------------------------------------------- /bin/hatop: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # Copyright (C) 2010 John Feuerstein 4 | # 5 | # Project URL: http://feurix.org/projects/hatop/ 6 | # Mirror URL: http://code.google.com/p/hatop/ 7 | # 8 | # This program is free software; you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation; either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU Library General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program; if not, write to the Free Software 20 | # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 21 | # 22 | '''\ 23 | HATop is an interactive ncurses client for the HAProxy unix socket 24 | ================================================================== 25 | 26 | HATop's appearance is similar to top(1). It supports various modes 27 | for detailed statistics of all configured proxies and services in near 28 | realtime. In addition, it features an interactive CLI for the haproxy 29 | unix socket. This allows administrators to control the given haproxy 30 | instance (change server weight, put servers into maintenance mode, ...) 31 | directly out of hatop and monitor the results immediately. 32 | 33 | Note: It is important to understand that when multiple haproxy processes 34 | are started on the same socket, any process may pick up the request 35 | and thus hatop will output stats owned solely by that process. 36 | The current haproxy-internal process id is displayed top right. 37 | 38 | Display mode reference: 39 | 40 | ID Mode Description 41 | 42 | 1 STATUS The default mode with health, session and queue statistics 43 | 2 TRAFFIC Display connection and request rates as well as traffic stats 44 | 3 HTTP Display various statistical information related to HTTP 45 | 4 ERRORS Display health info, various error counters and downtimes 46 | 5 CLI Display embedded command line client for the unix socket 47 | 48 | Keybind reference: 49 | 50 | Key Action 51 | 52 | Hh? Display this help screen 53 | CTRL-C / Qq Quit 54 | 55 | TAB Cycle mode forwards 56 | SHIFT-TAB Cycle mode backwards 57 | ALT-n / ESC-n Switch to mode n, where n is the numeric mode id 58 | ESC-ESC Jump to previous mode 59 | 60 | ENTER Display hotkey menu for selected service 61 | SPACE Copy and paste selected service identifier to the CLI 62 | 63 | You can scroll the stat views using UP / DOWN / PGUP / PGDOWN / HOME / END. 64 | 65 | The reverse colored cursor line is used to select a given service instance. 66 | 67 | An unique identifier [#/<#sid>] of the selected service is displayed 68 | bottom right. 69 | 70 | You can hit SPACE to copy and paste the identifier in string format 71 | "pxname/svname" to the CLI for easy re-use with some commands. 72 | 73 | For example: 74 | 75 | 1) Open the CLI 76 | 2) Type "disable server " 77 | 3) Switch back to some stat view using TAB / SHIFT-TAB 78 | 4) Select the server instance using UP / DOWN 79 | 5) Hit SPACE 80 | 81 | The result is this command line: 82 | 83 | > disable server / 84 | 85 | Some common administrative actions have hotkeys: 86 | 87 | Hotkey Action 88 | 89 | F4 Restore initial server weight 90 | 91 | F5 Decrease server weight: - 10 92 | F6 Decrease server weight: - 1 93 | F7 Increase server weight: + 1 94 | F8 Increase server weight: + 10 95 | 96 | F9 Enable server (return from maintenance mode) 97 | F10 Disable server (put into maintenance mode) 98 | 99 | Hotkey actions and server responses are logged on the CLI viewport. 100 | You can scroll the output on the CLI view using PGUP / PGDOWN. 101 | A brief keybind reference is logged there directly after startup... 102 | 103 | 104 | Header reference: 105 | 106 | Node configured name of the haproxy node 107 | Uptime runtime since haproxy was initially started 108 | Pipes pipes are currently used for kernel-based tcp slicing 109 | Procs number of haproxy processes 110 | Tasks number of actice process tasks 111 | Queue number of queued process tasks (run queue) 112 | Proxies number of configured proxies 113 | Services number of configured services 114 | 115 | In multiple modes: 116 | 117 | NAME name of the proxy and his services 118 | W configured weight of the service 119 | STATUS service status (UP/DOWN/NOLB/MAINT/MAINT(via)...) 120 | CHECK status of last health check (see status reference below) 121 | 122 | In STATUS mode: 123 | 124 | ACT server is active (server), number of active servers (backend) 125 | BCK server is backup (server), number of backup servers (backend) 126 | QCUR current queued requests 127 | QMAX max queued requests 128 | SCUR current sessions 129 | SMAX max sessions 130 | SLIM sessions limit 131 | STOT total sessions 132 | 133 | In TRAFFIC mode: 134 | 135 | LBTOT total number of times a server was selected 136 | RATE number of sessions per second over last elapsed second 137 | RLIM limit on new sessions per second 138 | RMAX max number of new sessions per second 139 | BIN bytes in (IEEE 1541-2002) 140 | BOUT bytes out (IEEE 1541-2002) 141 | 142 | In HTTP mode: 143 | 144 | RATE HTTP requests per second over last elapsed second 145 | RMAX max number of HTTP requests per second observed 146 | RTOT total number of HTTP requests received 147 | 1xx number of HTTP responses with 1xx code 148 | 2xx number of HTTP responses with 2xx code 149 | 3xx number of HTTP responses with 3xx code 150 | 4xx number of HTTP responses with 4xx code 151 | 5xx number of HTTP responses with 5xx code 152 | ?xx number of HTTP responses with other codes (protocol error) 153 | 154 | In ERRORS mode: 155 | 156 | CF number of failed checks 157 | CD number of UP->DOWN transitions 158 | CL last status change 159 | ECONN connection errors 160 | EREQ request errors 161 | ERSP response errors 162 | DREQ denied requests 163 | DRSP denied responses 164 | DOWN total downtime 165 | 166 | Health check status reference: 167 | 168 | UNK unknown 169 | INI initializing 170 | SOCKERR socket error 171 | L4OK check passed on layer 4, no upper layers testing enabled 172 | L4TMOUT layer 1-4 timeout 173 | L4CON layer 1-4 connection problem, for example 174 | "Connection refused" (tcp rst) or "No route to host" (icmp) 175 | L6OK check passed on layer 6 176 | L6TOUT layer 6 (SSL) timeout 177 | L6RSP layer 6 invalid response - protocol error 178 | L7OK check passed on layer 7 179 | L7OKC check conditionally passed on layer 7, for example 404 with 180 | disable-on-404 181 | L7TOUT layer 7 (HTTP/SMTP) timeout 182 | L7RSP layer 7 invalid response - protocol error 183 | L7STS layer 7 response error, for example HTTP 5xx 184 | ''' 185 | __author__ = 'John Feuerstein ' 186 | __copyright__ = 'Copyright (C) 2010 %s' % __author__ 187 | __license__ = 'GNU GPLv3' 188 | __version__ = '0.8.0' 189 | 190 | import fcntl 191 | import os 192 | import re 193 | import signal 194 | import socket 195 | import struct 196 | import sys 197 | import time 198 | import tty 199 | 200 | import curses 201 | import curses.ascii 202 | 203 | from socket import error as SocketError 204 | from _curses import error as CursesError 205 | 206 | from collections import deque 207 | from textwrap import TextWrapper 208 | 209 | # ------------------------------------------------------------------------- # 210 | # GLOBALS # 211 | # ------------------------------------------------------------------------- # 212 | 213 | # Settings of interactive command session over the unix-socket 214 | HAPROXY_CLI_BUFSIZE = 4096 215 | HAPROXY_CLI_TIMEOUT = 60 216 | HAPROXY_CLI_PROMPT = '> ' 217 | HAPROXY_CLI_CMD_SEP = ';' 218 | HAPROXY_CLI_CMD_TIMEOUT = 1 219 | HAPROXY_CLI_MAXLINES = 1000 220 | 221 | # Settings of the embedded CLI 222 | CLI_MAXLINES = 1000 223 | CLI_MAXHIST = 100 224 | CLI_INPUT_LIMIT = 200 225 | CLI_INPUT_RE = re.compile('[a-zA-Z0-9_:\.\-\+; /#%]') 226 | CLI_INPUT_DENY_CMD = ['prompt', 'set timeout cli', 'quit'] 227 | 228 | # Note: Only the last 3 lines are visible instantly on 80x25 229 | CLI_HELP_TEXT = '''\ 230 | Welcome on the embedded interactive HAProxy shell! 231 | 232 | Type `help' to get a command reference 233 | ''' 234 | 235 | # Screen setup 236 | SCREEN_XMIN = 78 237 | SCREEN_YMIN = 20 238 | SCREEN_XMAX = 200 239 | SCREEN_YMAX = 100 240 | SCREEN_HPOS = 11 241 | 242 | HAPROXY_INFO_RE = { 243 | 'software_name': re.compile('^Name:\s*(?P\S+)'), 244 | 'software_version': re.compile('^Version:\s*(?P\S+)'), 245 | 'software_release': re.compile('^Release_date:\s*(?P\S+)'), 246 | 'nproc': re.compile('^Nbproc:\s*(?P\d+)'), 247 | 'procn': re.compile('^Process_num:\s*(?P\d+)'), 248 | 'pid': re.compile('^Pid:\s*(?P\d+)'), 249 | 'uptime': re.compile('^Uptime:\s*(?P[\S ]+)$'), 250 | 'maxconn': re.compile('^Maxconn:\s*(?P\d+)'), 251 | 'curconn': re.compile('^CurrConns:\s*(?P\d+)'), 252 | 'maxpipes': re.compile('^Maxpipes:\s*(?P\d+)'), 253 | 'curpipes': re.compile('^PipesUsed:\s*(?P\d+)'), 254 | 'tasks': re.compile('^Tasks:\s*(?P\d+)'), 255 | 'runqueue': re.compile('^Run_queue:\s*(?P\d+)'), 256 | 'node': re.compile('^node:\s*(?P\S+)'), 257 | } 258 | 259 | HAPROXY_STAT_MAX_SERVICES = 100 260 | HAPROXY_STAT_LIMIT_WARNING = '''\ 261 | Warning: You have reached the stat parser limit! (%d) 262 | Use --filter to parse specific service stats only. 263 | ''' % HAPROXY_STAT_MAX_SERVICES 264 | HAPROXY_STAT_FILTER_RE = re.compile( 265 | '^(?P-?\d+)\s+(?P-?\d+)\s+(?P-?\d+)$') 266 | HAPROXY_STAT_PROXY_FILTER_RE = re.compile( 267 | '^(?P[a-zA-Z0-9_:\.\-]+)$') 268 | HAPROXY_STAT_COMMENT = '#' 269 | HAPROXY_STAT_SEP = ',' 270 | HAPROXY_STAT_CSV = [ 271 | # Note: Fields must be listed in correct order, as described in: 272 | # http://haproxy.1wt.eu/download/1.4/doc/configuration.txt [9.1] 273 | 274 | # TYPE FIELD 275 | 276 | (str, 'pxname'), # proxy name 277 | (str, 'svname'), # service name (FRONTEND / BACKEND / name) 278 | (int, 'qcur'), # current queued requests 279 | (int, 'qmax'), # max queued requests 280 | (int, 'scur'), # current sessions 281 | (int, 'smax'), # max sessions 282 | (int, 'slim'), # sessions limit 283 | (int, 'stot'), # total sessions 284 | (int, 'bin'), # bytes in 285 | (int, 'bout'), # bytes out 286 | (int, 'dreq'), # denied requests 287 | (int, 'dresp'), # denied responses 288 | (int, 'ereq'), # request errors 289 | (int, 'econ'), # connection errors 290 | (int, 'eresp'), # response errors (among which srv_abrt) 291 | (int, 'wretr'), # retries (warning) 292 | (int, 'wredis'), # redispatches (warning) 293 | (str, 'status'), # status (UP/DOWN/NOLB/MAINT/MAINT(via)...) 294 | (int, 'weight'), # server weight (server), total weight (backend) 295 | (int, 'act'), # server is active (server), 296 | # number of active servers (backend) 297 | (int, 'bck'), # server is backup (server), 298 | # number of backup servers (backend) 299 | (int, 'chkfail'), # number of failed checks 300 | (int, 'chkdown'), # number of UP->DOWN transitions 301 | (int, 'lastchg'), # last status change (in seconds) 302 | (int, 'downtime'), # total downtime (in seconds) 303 | (int, 'qlimit'), # queue limit 304 | (int, 'pid'), # process id 305 | (int, 'iid'), # unique proxy id 306 | (int, 'sid'), # service id (unique inside a proxy) 307 | (int, 'throttle'), # warm up status 308 | (int, 'lbtot'), # total number of times a server was selected 309 | (str, 'tracked'), # id of proxy/server if tracking is enabled 310 | (int, 'type'), # (0=frontend, 1=backend, 2=server, 3=socket) 311 | (int, 'rate'), # number of sessions per second 312 | # over the last elapsed second 313 | (int, 'rate_lim'), # limit on new sessions per second 314 | (int, 'rate_max'), # max number of new sessions per second 315 | (str, 'check_status'), # status of last health check 316 | (int, 'check_code'), # layer5-7 code, if available 317 | (int, 'check_duration'), # time in ms took to finish last health check 318 | (int, 'hrsp_1xx'), # http responses with 1xx code 319 | (int, 'hrsp_2xx'), # http responses with 2xx code 320 | (int, 'hrsp_3xx'), # http responses with 3xx code 321 | (int, 'hrsp_4xx'), # http responses with 4xx code 322 | (int, 'hrsp_5xx'), # http responses with 5xx code 323 | (int, 'hrsp_other'), # http responses with other codes (protocol error) 324 | (str, 'hanafail'), # failed health checks details 325 | (int, 'req_rate'), # HTTP requests per second 326 | (int, 'req_rate_max'), # max number of HTTP requests per second 327 | (int, 'req_tot'), # total number of HTTP requests received 328 | (int, 'cli_abrt'), # number of data transfers aborted by client 329 | (int, 'srv_abrt'), # number of data transfers aborted by server 330 | ] 331 | HAPROXY_STAT_NUMFIELDS = len(HAPROXY_STAT_CSV) 332 | HAPROXY_STAT_CSV = [(k, v) for k, v in enumerate(HAPROXY_STAT_CSV)] 333 | 334 | # All big numeric values on the screen are prefixed using the metric prefix 335 | # set, while everything byte related is prefixed using binary prefixes. 336 | # Note: If a non-byte numeric value fits into the field, we skip prefixing. 337 | PREFIX_BINARY = { 338 | 1024: 'K', 339 | 1024**2: 'M', 340 | } 341 | PREFIX_METRIC = { 342 | 1000: 'k', 343 | 1000**2: 'M', 344 | 1000**3: 'G', 345 | } 346 | PREFIX_TIME = { 347 | 60: 'm', 348 | 60*60: 'h', 349 | 60*60*24:'d', 350 | } 351 | 352 | # ------------------------------------------------------------------------- # 353 | # CLASS DEFINITIONS # 354 | # ------------------------------------------------------------------------- # 355 | 356 | # Use bounded length deque if available (Python 2.6+) 357 | try: 358 | deque(maxlen=0) 359 | 360 | class RingBuffer(deque): 361 | 362 | def __init__(self, maxlen): 363 | assert maxlen > 0 364 | deque.__init__(self, maxlen=maxlen) 365 | 366 | except TypeError: 367 | 368 | class RingBuffer(deque): 369 | 370 | def __init__(self, maxlen): 371 | assert maxlen > 0 372 | deque.__init__(self) 373 | self.maxlen = maxlen 374 | 375 | def append(self, item): 376 | if len(self) == self.maxlen: 377 | self.popleft() 378 | deque.append(self, item) 379 | 380 | def appendleft(self, item): 381 | if len(self) == self.maxlen: 382 | self.popright() 383 | deque.appendleft(self, item) 384 | 385 | def extend(self, iterable): 386 | for item in iterable: 387 | self.append(item) 388 | 389 | def extendleft(self, iterable): 390 | for item in iterable: 391 | self.appendleft(item) 392 | 393 | 394 | class Socket: 395 | 396 | def __init__(self, mode, path="", host="", port=43100, readonly=False): 397 | self.mode = mode 398 | self.ro = readonly 399 | self.path = path 400 | self.host = host 401 | self.port = port 402 | if (self.mode == 'socket'): 403 | self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 404 | if (self.mode == 'tcp'): 405 | self._socket = socket.socket() 406 | 407 | def _recv(self): 408 | # socket.recv() wrapper raising SocketError if we receive 409 | # EOF before seeing the interactive socket prompt. 410 | data = self._socket.recv(HAPROXY_CLI_BUFSIZE) 411 | if not data: 412 | raise SocketError('error while waiting for prompt') 413 | return data 414 | 415 | def connect(self): 416 | # Initialize socket connection 417 | if (self.mode == 'socket'): 418 | self._socket.connect(self.path) 419 | if (self.mode == 'tcp'): 420 | self._socket.connect((self.host, self.port)) 421 | self._socket.settimeout(HAPROXY_CLI_CMD_TIMEOUT) 422 | 423 | # Enter the interactive socket mode. This requires HAProxy 1.4+ and 424 | # allows us to error out early if connected to an older version. 425 | try: 426 | self.send('prompt') 427 | self.wait() 428 | self.send('set timeout cli %d' % HAPROXY_CLI_TIMEOUT) 429 | self.wait() 430 | except SocketError: 431 | raise SocketError('error while initializing interactive mode') 432 | 433 | def close(self): 434 | try: 435 | self.send('quit') 436 | except: 437 | pass 438 | try: 439 | self._socket.close() 440 | except: 441 | pass 442 | 443 | def send(self, cmdline): 444 | self._socket.sendall('%s\n' % cmdline) 445 | 446 | def wait(self): 447 | # Wait for the prompt and discard data. 448 | rbuf = '' 449 | while not rbuf.endswith(HAPROXY_CLI_PROMPT): 450 | data = self._recv() 451 | rbuf = rbuf[-(len(HAPROXY_CLI_PROMPT)-1):] + data 452 | 453 | def recv(self): 454 | # Receive lines until HAPROXY_CLI_MAXLINES or the prompt is reached. 455 | # If the prompt was still not found, discard data and wait for it. 456 | linecount = 0 457 | rbuf = '' 458 | while not rbuf.endswith(HAPROXY_CLI_PROMPT): 459 | 460 | if linecount == HAPROXY_CLI_MAXLINES: 461 | data = self._recv() 462 | rbuf = rbuf[-(len(HAPROXY_CLI_PROMPT)-1):] + data 463 | continue 464 | 465 | data = self._recv() 466 | rbuf += data 467 | 468 | while linecount < HAPROXY_CLI_MAXLINES and '\n' in rbuf: 469 | line, rbuf = rbuf.split('\n', 1) 470 | linecount += 1 471 | yield line 472 | 473 | 474 | class SocketData: 475 | 476 | def __init__(self, socket): 477 | self.socket = socket 478 | self.pxcount = 0 479 | self.svcount = 0 480 | self.info = {} 481 | self.stat = {} 482 | self._filters = set() 483 | 484 | def register_stat_filter(self, stat_filter): 485 | 486 | # Validate and register filters 487 | stat_filter_set = set(stat_filter) 488 | for filter in stat_filter_set: 489 | match = HAPROXY_STAT_FILTER_RE.match(filter) 490 | if not match: 491 | raise ValueError('invalid stat filter: %s' % filter) 492 | self._filters.add(( 493 | int(match.group('iid'), 10), 494 | int(match.group('type'), 10), 495 | int(match.group('sid'), 10), 496 | )) 497 | 498 | def register_proxy_filter(self, proxy_filter): 499 | 500 | # Validate filters 501 | proxy_filter_set = set(proxy_filter) 502 | for filter in proxy_filter_set: 503 | if not HAPROXY_STAT_PROXY_FILTER_RE.match(filter): 504 | raise ValueError('invalid proxy filter: %s' % filter) 505 | 506 | # Convert proxy filters into more efficient stat filters 507 | self.socket.send('show stat') 508 | pxstat, pxcount, svcount = parse_stat(self.socket.recv()) 509 | 510 | proxy_iid_map = {} # {pxname: iid, ...} 511 | 512 | for pxname in proxy_filter_set: 513 | for iid in pxstat: 514 | for sid in pxstat[iid]: 515 | if pxstat[iid][sid]['pxname'] == pxname: 516 | proxy_iid_map[pxname] = iid 517 | break 518 | if pxname in proxy_iid_map: 519 | break 520 | 521 | for pxname in proxy_filter_set: 522 | if not pxname in proxy_iid_map: 523 | raise RuntimeError('proxy not found: %s' % pxname) 524 | 525 | # Register filters 526 | for iid in proxy_iid_map.itervalues(): 527 | self._filters.add((iid, -1, -1)) 528 | 529 | def update_info(self): 530 | self.socket.send('show info') 531 | iterable = self.socket.recv() 532 | self.info = parse_info(iterable) 533 | 534 | def update_stat(self): 535 | # Store current data 536 | pxcount_old = self.pxcount 537 | svcount_old = self.svcount 538 | stat_old = self.stat 539 | 540 | # Reset current data 541 | self.pxcount = 0 542 | self.svcount = 0 543 | self.stat = {} 544 | 545 | if self._filters: 546 | for filter in self._filters: 547 | self.socket.send('show stat %d %d %d' % filter) 548 | filter_stat, filter_pxcount, filter_svcount = \ 549 | parse_stat(self.socket.recv()) 550 | 551 | if filter_pxcount == 0: 552 | raise RuntimeError('stale stat filter: %d %d %d' % filter) 553 | 554 | self.pxcount += filter_pxcount 555 | self.svcount += filter_svcount 556 | self.stat.update(filter_stat) 557 | else: 558 | self.socket.send('show stat') 559 | self.stat, self.pxcount, self.svcount = \ 560 | parse_stat(self.socket.recv()) 561 | 562 | if self.pxcount == 0: 563 | raise RuntimeWarning('no stat data available') 564 | 565 | # Warn if the HAProxy configuration has changed on-the-fly 566 | pxdiff = 0 567 | svdiff = 0 568 | 569 | if self.pxcount < pxcount_old: 570 | pxdiff -= pxcount_old - self.pxcount 571 | if pxcount_old > 0 and self.pxcount > pxcount_old: 572 | pxdiff += self.pxcount - pxcount_old 573 | if self.svcount < svcount_old: 574 | svdiff -= svcount_old - self.svcount 575 | if svcount_old > 0 and self.svcount > svcount_old: 576 | svdiff += self.svcount - svcount_old 577 | 578 | if pxdiff != 0 or svdiff != 0: 579 | raise RuntimeWarning( 580 | 'config changed: proxy %+d, service %+d ' 581 | '(reloading...)' % (pxdiff, svdiff)) 582 | 583 | 584 | class ScreenCLI: 585 | 586 | def __init__(self, screen): 587 | self.screen = screen 588 | 589 | # Output 590 | self.obuf = RingBuffer(CLI_MAXLINES) 591 | self.ypos = 0 592 | self.wrapper = TextWrapper() 593 | self.screenlines = [] 594 | 595 | # Input 596 | self.ihist = RingBuffer(CLI_MAXHIST) 597 | self.ibuf = [] 598 | self.ibpos = 0 599 | self.ibmin = 0 600 | 601 | 602 | # INPUT 603 | @property 604 | def imin(self): 605 | return self.screen.xmin + 2 606 | 607 | @property 608 | def imax(self): 609 | return self.screen.xmax - 4 610 | 611 | @property 612 | def ispan(self): 613 | return self.imax - self.imin 614 | 615 | @property 616 | def ipos(self): 617 | return self.ibpos - self.ibmin 618 | 619 | @property 620 | def ibmax(self): 621 | return self.ibmin + self.ispan 622 | 623 | @property 624 | def iblen(self): 625 | return len(self.ibuf) 626 | 627 | @property 628 | def cmdline(self): 629 | return ''.join(self.ibuf) 630 | 631 | # OUTPUT 632 | @property 633 | def ospan(self): 634 | return self.screen.span - 1 635 | 636 | 637 | def setup(self): 638 | self.ipad = curses.newpad(1, SCREEN_XMAX) # input 639 | self.opad = curses.newpad(SCREEN_YMAX, SCREEN_XMAX) # output 640 | 641 | # Display initial help text... 642 | self.obuf.extend(CLI_HELP_TEXT.split('\n')) 643 | self.update_screenlines() 644 | 645 | def start(self): 646 | try: 647 | curses.curs_set(1) 648 | except CursesError: 649 | pass 650 | self.draw_output() 651 | self.draw_input() 652 | 653 | def stop(self): 654 | try: 655 | curses.curs_set(0) 656 | except CursesError: 657 | pass 658 | 659 | def update_screenlines(self): 660 | self.wrapper.width = self.screen.xmax 661 | self.screenlines = [] 662 | for line in self.obuf: 663 | if len(line) > self.wrapper.width: 664 | self.screenlines.extend(self.wrapper.wrap(line)) 665 | else: 666 | self.screenlines.append(line) 667 | self.ypos = len(self.screenlines) 668 | 669 | def reset_input(self): 670 | self.ibuf = [] 671 | self.ibpos = 0 672 | self.ibmin = 0 673 | 674 | def refresh_input(self, sync=False): 675 | if sync: 676 | refresh = self.ipad.refresh 677 | else: 678 | refresh = self.ipad.noutrefresh 679 | 680 | refresh(0, 0, 681 | self.screen.smax, self.screen.xmin, 682 | self.screen.smax, self.screen.xmax - 1) 683 | 684 | def refresh_output(self, sync=False): 685 | if sync: 686 | refresh = self.opad.refresh 687 | else: 688 | refresh = self.opad.noutrefresh 689 | 690 | refresh(0, 0, 691 | self.screen.smin, self.screen.xmin, 692 | self.screen.smax - 2, self.screen.xmax - 1) 693 | 694 | def draw_input(self): 695 | self.ipad.clear() 696 | self.ipad.addstr(0, 0, '> ', curses.A_BOLD) 697 | self.ipad.addstr(0, 2, ''.join(self.ibuf[self.ibmin:self.ibmax])) 698 | 699 | # Mark input lines longer than the visible input span 700 | if self.ibmin > 0: 701 | self.ipad.addstr(0, self.imin - 1, '<') 702 | if self.iblen > self.ibmax: 703 | self.ipad.addstr(0, self.imax, '>') 704 | 705 | self.ipad.move(0, self.imin + self.ipos) 706 | 707 | def draw_output(self): 708 | self.opad.clear() 709 | vmin = max(0, self.ypos - self.ospan) 710 | vmax = vmin + self.ospan 711 | lines = self.screenlines[vmin:vmax] 712 | self.opad.addstr(0, 0, '\n'.join(lines)) 713 | 714 | # INPUT 715 | def prev(self): 716 | if len(self.ihist) == 0: 717 | return 718 | if len(self.ibuf) == 0: 719 | self.ibuf = list(self.ihist[-1]) 720 | self.mvend() 721 | return 722 | if self.ibuf != self.ihist[-1]: 723 | self.ihist.append(self.ibuf) 724 | self.ihist.rotate(1) 725 | self.ibuf = list(self.ihist[-1]) 726 | self.mvend() 727 | 728 | def next(self): 729 | if len(self.ihist) == 0: 730 | return 731 | self.ihist.rotate(-1) 732 | self.ibuf = list(self.ihist[-1]) 733 | self.mvend() 734 | 735 | def puts(self, s): 736 | s = list(s) 737 | if len(self.ibuf) + len(s) >= CLI_INPUT_LIMIT: 738 | return 739 | for c in s: 740 | if not CLI_INPUT_RE.match(c): 741 | return 742 | 743 | if self.ibpos < self.iblen: 744 | self.ibuf = self.ibuf[:self.ibpos] + s + self.ibuf[self.ibpos:] 745 | else: 746 | self.ibuf.extend(s) 747 | 748 | self.mvc(len(s)) 749 | return True 750 | 751 | def putc(self, c): 752 | if len(self.ibuf) == CLI_INPUT_LIMIT: 753 | return 754 | if not CLI_INPUT_RE.match(c): 755 | return 756 | 757 | if self.ibpos < self.iblen: 758 | self.ibuf.insert(self.ibpos, c) 759 | else: 760 | self.ibuf.append(c) 761 | 762 | self.mvc(1) 763 | 764 | def delc(self, n): 765 | if n == 0 or self.iblen == 0: 766 | return 767 | 768 | # Delete LEFT 769 | elif n < 0 and self.ibpos >= 1: 770 | self.ibuf.pop(self.ibpos - 1) 771 | self.mvc(-1) 772 | 773 | # Delete RIGHT 774 | elif n > 0 and self.ibpos < self.iblen: 775 | self.ibuf.pop(self.ibpos) 776 | self.draw_input() 777 | self.refresh_input(sync=True) 778 | 779 | def mvhome(self): 780 | self.ibmin = 0 781 | self.ibpos = 0 782 | self.draw_input() 783 | self.refresh_input(sync=True) 784 | 785 | def mvend(self): 786 | self.ibmin = max(0, self.iblen - self.ispan) 787 | self.ibpos = self.iblen 788 | self.draw_input() 789 | self.refresh_input(sync=True) 790 | 791 | def mvc(self, n): 792 | if n == 0: 793 | return 794 | 795 | # Move LEFT 796 | if n < 0: 797 | self.ibpos = max(0, self.ibpos + n) 798 | if self.ibpos < self.ibmin: 799 | self.ibmin = self.ibpos 800 | 801 | # Move RIGHT 802 | elif n > 0: 803 | self.ibpos = min(self.iblen, self.ibpos + n) 804 | if self.ibpos > self.ibmax: 805 | self.ibmin += n 806 | 807 | self.draw_input() 808 | self.refresh_input(sync=True) 809 | 810 | # OUTPUT 811 | def mvo(self, n): 812 | if n == 0: 813 | return 814 | 815 | # Move UP 816 | if n < 0 and self.ypos > self.ospan: 817 | self.ypos = max(self.ospan, self.ypos + n) 818 | 819 | # Move DOWN 820 | elif n > 0 and self.ypos < len(self.screenlines): 821 | self.ypos = min(len(self.screenlines), self.ypos + n) 822 | 823 | self.draw_output() 824 | self.refresh_output(sync=True) 825 | 826 | def execute(self): 827 | 828 | # Nothing to do... print marker line instead. 829 | if self.iblen == 0: 830 | self.obuf.append('- %s %s' % (time.ctime(), '-' * 50)) 831 | self.obuf.append('') 832 | self.update_screenlines() 833 | self.draw_output() 834 | self.refresh_output(sync=True) 835 | self.refresh_input(sync=True) 836 | return 837 | 838 | # Validate each command on the command line 839 | cmds = [cmd.strip() for cmd in 840 | self.cmdline.split(HAPROXY_CLI_CMD_SEP)] 841 | 842 | for pattern in CLI_INPUT_DENY_CMD: 843 | for cmd in cmds: 844 | if re.match(r'^\s*%s(?:\s|$)' % pattern, cmd): 845 | self.obuf.append('* command not allowed: %s' % cmd) 846 | self.obuf.append('') 847 | self.update_screenlines() 848 | self.draw_output() 849 | self.refresh_output(sync=True) 850 | self.refresh_input(sync=True) 851 | return 852 | 853 | self.execute_cmdline(self.cmdline) 854 | 855 | self.draw_output() 856 | self.refresh_output(sync=True) 857 | 858 | self.ihist.append(self.ibuf) 859 | self.reset_input() 860 | self.draw_input() 861 | self.refresh_input(sync=True) 862 | 863 | def execute_cmdline(self, cmdline): 864 | self.obuf.append('* %s' % time.ctime()) 865 | self.obuf.append('> %s' % cmdline) 866 | self.screen.data.socket.send(cmdline) 867 | self.obuf.extend(self.screen.data.socket.recv()) 868 | self.update_screenlines() 869 | 870 | 871 | class Screen: 872 | 873 | def __init__(self, data, mid=1): 874 | self.data = data 875 | self.modes = SCREEN_MODES 876 | self.sb_conn = StatusBar() 877 | self.sb_pipe = StatusBar() 878 | self.lines = [] 879 | self.screen = None 880 | self.xmin = 0 881 | self.xmax = SCREEN_XMIN 882 | self.ymin = 0 883 | self.ymax = SCREEN_YMIN 884 | self.vmin = 0 885 | self.cmin = 0 886 | self.cpos = 0 887 | self.hpos = SCREEN_HPOS 888 | self.help = ScreenHelp(self) 889 | self.cli = ScreenCLI(self) 890 | 891 | self._pmid = mid # previous mode id 892 | self._cmid = mid # current mode id 893 | self._mode = self.modes[mid] 894 | 895 | # Display state 896 | self.active = False 897 | 898 | # Assume a dumb TTY, setup() will detect smart features. 899 | self.dumbtty = True 900 | 901 | # Toggled by the SIGWINCH handler... 902 | # Note: Defaults to true to force the initial size sync. 903 | self._resized = True 904 | 905 | # Display given exceptions on screen 906 | self.exceptions = [] 907 | 908 | # Show cursor line? 909 | self.cursor = True 910 | 911 | # Show hotkeys? 912 | self.hotkeys = False 913 | 914 | def _sigwinchhandler(self, signum, frame): 915 | self._resized = True 916 | 917 | @property 918 | def resized(self): 919 | if self.dumbtty: 920 | ymax, xmax = self.getmaxyx() 921 | return ymax != self.ymax or xmax != self.xmax 922 | else: 923 | return self._resized 924 | 925 | @property 926 | def mid(self): 927 | return self._cmid 928 | 929 | @property 930 | def mode(self): 931 | return self._mode 932 | 933 | @property 934 | def ncols(self): 935 | return self.xmax - self.xmin 936 | 937 | @property 938 | def smin(self): 939 | return self.hpos + 2 940 | 941 | @property 942 | def smax(self): 943 | return self.ymax - 3 944 | 945 | @property 946 | def span(self): 947 | return self.smax - self.smin 948 | 949 | @property 950 | def cmax(self): 951 | return min(self.span, len(self.lines) - 1) 952 | 953 | @property 954 | def cstat(self): 955 | return self.lines[self.vpos].stat 956 | 957 | @property 958 | def vpos(self): 959 | return self.vmin + self.cpos 960 | 961 | @property 962 | def vmax(self): 963 | return min(self.vmin + self.span, len(self.lines) - 1) 964 | 965 | @property 966 | def screenlines(self): 967 | return enumerate(self.lines[self.vmin:self.vmax + 1]) 968 | 969 | # Proxies 970 | def getch(self, *args, **kwargs): 971 | return self.screen.getch(*args, **kwargs) 972 | def hline(self, *args, **kwargs): 973 | return self.screen.hline(*args, **kwargs) 974 | def addstr(self, *args, **kwargs): 975 | return self.screen.addstr(*args, **kwargs) 976 | 977 | def setup(self): 978 | self.screen = curses_init() 979 | self.screen.keypad(1) 980 | self.screen.nodelay(1) 981 | self.screen.idlok(1) 982 | self.screen.move(0, 0) 983 | curses.def_prog_mode() 984 | self.help.setup() 985 | self.cli.setup() 986 | 987 | # Register some terminal resizing magic if supported... 988 | if hasattr(curses, 'resize_term') and hasattr(signal, 'SIGWINCH'): 989 | self.dumbtty = False 990 | signal.signal(signal.SIGWINCH, self._sigwinchhandler) 991 | 992 | # If we came this far the display is active 993 | self.active = True 994 | 995 | def getmaxyx(self): 996 | ymax, xmax = self.screen.getmaxyx() 997 | xmax = min(xmax, SCREEN_XMAX) 998 | ymax = min(ymax, SCREEN_YMAX) 999 | return ymax, xmax 1000 | 1001 | def resize(self): 1002 | if not self.dumbtty: 1003 | self.clear() 1004 | size = fcntl.ioctl(0, tty.TIOCGWINSZ, '12345678') 1005 | size = struct.unpack('4H', size) 1006 | curses.resize_term(size[0], size[1]) 1007 | 1008 | ymax, xmax = self.getmaxyx() 1009 | 1010 | if xmax < SCREEN_XMIN or ymax < SCREEN_YMIN: 1011 | raise RuntimeError( 1012 | 'screen too small, need at least %dx%d' 1013 | % (SCREEN_XMIN, SCREEN_YMIN)) 1014 | if ymax == self.ymax and xmax == self.xmax: 1015 | self._resized = False 1016 | return 1017 | if xmax != self.xmax: 1018 | self.xmax = xmax 1019 | if ymax != self.ymax: 1020 | self.ymax = ymax 1021 | 1022 | self.mode.sync(self) 1023 | 1024 | # Force re-wrapping of the screenlines in CLI mode 1025 | if self.mid == 5: 1026 | self.cli.update_screenlines() 1027 | self.cli.draw_output() 1028 | 1029 | self._resized = False 1030 | 1031 | def reset(self): 1032 | if not self.active: 1033 | return 1034 | curses_reset(self.screen) 1035 | 1036 | def recover(self): 1037 | curses.reset_prog_mode() 1038 | 1039 | def refresh(self): 1040 | self.screen.noutrefresh() 1041 | 1042 | if self.mid == 0: 1043 | self.help.refresh() 1044 | elif self.mid == 5: 1045 | self.cli.refresh_output() 1046 | self.cli.refresh_input() 1047 | 1048 | curses.doupdate() 1049 | 1050 | def clear(self): 1051 | # Note: Forces the whole screen to be repainted upon refresh() 1052 | self.screen.clear() 1053 | 1054 | def erase(self): 1055 | self.screen.erase() 1056 | 1057 | def switch_mode(self, mid): 1058 | if mid == 5 and self.data.socket.ro: 1059 | return # noop 1060 | 1061 | mode = self.modes[mid] 1062 | mode.sync(self) 1063 | 1064 | if self.mid != 5 and mid == 5: 1065 | self.cli.start() 1066 | elif self.mid == 5 and mid != 5: 1067 | self.cli.stop() 1068 | 1069 | self._pmid = self._cmid 1070 | self._cmid, self._mode = mid, mode 1071 | 1072 | def toggle_mode(self): 1073 | if self._pmid == self._cmid: 1074 | return 1075 | self.switch_mode(self._pmid) 1076 | 1077 | def cycle_mode(self, n): 1078 | if n == 0: 1079 | return 1080 | 1081 | if self.data.socket.ro: 1082 | border = 4 1083 | else: 1084 | border = 5 1085 | 1086 | if self._cmid == 0: 1087 | self.switch_mode(1) 1088 | elif n < 0 and self._cmid == 1: 1089 | self.switch_mode(border) 1090 | elif n > 0 and self._cmid == border: 1091 | self.switch_mode(1) 1092 | else: 1093 | self.switch_mode(self._cmid + n) 1094 | 1095 | def update_data(self): 1096 | self.data.update_info() 1097 | try: 1098 | self.data.update_stat() 1099 | except RuntimeWarning, x: 1100 | self.exceptions.append(x) 1101 | 1102 | def update_bars(self): 1103 | self.sb_conn.update_max(int(self.data.info['maxconn'], 10)) 1104 | self.sb_conn.update_cur(int(self.data.info['curconn'], 10)) 1105 | self.sb_pipe.update_max(int(self.data.info['maxpipes'], 10)) 1106 | self.sb_pipe.update_cur(int(self.data.info['curpipes'], 10)) 1107 | 1108 | def update_lines(self): 1109 | # Display non-fatal exceptions on screen 1110 | if self.exceptions: 1111 | self.mvhome() 1112 | self.lines = [] 1113 | self.cursor = False 1114 | for x in self.exceptions: 1115 | for line in str(x).splitlines(): 1116 | line = line.center(SCREEN_XMIN) 1117 | self.lines.append(ScreenLine(text=line)) 1118 | self.exceptions = [] 1119 | return 1120 | 1121 | # Reset cursor visibility 1122 | if not self.cursor: 1123 | self.cursor = True 1124 | 1125 | # Update screen lines 1126 | self.lines = get_screenlines(self.data.stat) 1127 | if self.data.svcount >= HAPROXY_STAT_MAX_SERVICES: 1128 | self.lines.append(ScreenLine()) 1129 | for line in HAPROXY_STAT_LIMIT_WARNING.splitlines(): 1130 | self.lines.append(ScreenLine(text=line)) 1131 | 1132 | def draw_line(self, ypos, xpos=0, text=None, 1133 | attr=curses.A_REVERSE): 1134 | self.hline(ypos, self.xmin, ' ', self.xmax, attr) 1135 | if text: 1136 | self.addstr(ypos, self.xmin + xpos, text, attr) 1137 | 1138 | def draw_head(self): 1139 | self.draw_line(self.ymin) 1140 | attr = curses.A_REVERSE | curses.A_BOLD 1141 | self.addstr(self.ymin, self.xmin, 1142 | time.ctime().rjust(self.xmax - 1), attr) 1143 | self.addstr(self.ymin, self.xmin + 1, 1144 | 'HATop version ' + __version__, attr) 1145 | 1146 | def draw_info(self): 1147 | self.addstr(self.ymin + 2, self.xmin + 2, 1148 | '%s Version: %s (released: %s)' % ( 1149 | self.data.info['software_name'], 1150 | self.data.info['software_version'], 1151 | self.data.info['software_release'], 1152 | ), curses.A_BOLD) 1153 | self.addstr(self.ymin + 2, self.xmin + 56, 1154 | 'PID: %d (proc %d)' % ( 1155 | int(self.data.info['pid'], 10), 1156 | int(self.data.info['procn'], 10), 1157 | ), curses.A_BOLD) 1158 | self.addstr(self.ymin + 4, self.xmin + 2, 1159 | ' Node: %s (uptime %s)' % ( 1160 | self.data.info['node'] or 'unknown', 1161 | self.data.info['uptime'], 1162 | )) 1163 | self.addstr(self.ymin + 6, self.xmin + 2, 1164 | ' Pipes: %s' % self.sb_pipe) 1165 | self.addstr(self.ymin + 7, self.xmin + 2, 1166 | 'Connections: %s' % self.sb_conn) 1167 | self.addstr(self.ymin + 9, self.xmin + 2, 1168 | 'Procs: %3d Tasks: %5d Queue: %5d ' 1169 | 'Proxies: %3d Services: %4d' % ( 1170 | int(self.data.info['nproc'], 10), 1171 | int(self.data.info['tasks'], 10), 1172 | int(self.data.info['runqueue'], 10), 1173 | self.data.pxcount, 1174 | self.data.svcount, 1175 | )) 1176 | 1177 | def draw_cols(self): 1178 | self.draw_line(self.hpos, text=self.mode.head, 1179 | attr=curses.A_REVERSE | curses.A_BOLD) 1180 | 1181 | def draw_foot(self): 1182 | xpos = self.xmin 1183 | ypos = self.ymax - 1 1184 | self.draw_line(ypos) 1185 | attr_active = curses.A_BOLD 1186 | attr_inactive = curses.A_BOLD | curses.A_REVERSE 1187 | 1188 | # HOTKEYS 1189 | if (self.hotkeys and 1190 | 0 < self.mid < 5 and 1191 | self.cstat and 1192 | self.cstat['iid'] > 0 and 1193 | self.cstat['sid'] > 0): 1194 | self.draw_line(ypos) 1195 | self.addstr(ypos, 1, 'HOTKEYS:', 1196 | curses.A_BOLD | curses.A_REVERSE) 1197 | self.addstr(ypos, 11, 1198 | 'F4=W-RESET ' 1199 | 'F5=W-10 F6=W-1 F7=W+1 F8=W+10 ' 1200 | 'F9=ENABLE F10=DISABLE', 1201 | curses.A_NORMAL | curses.A_REVERSE) 1202 | return 1203 | 1204 | # VIEWPORTS 1205 | for mid, mode in enumerate(self.modes): 1206 | if mid == 0: 1207 | continue 1208 | if mid == 5 and self.data.socket.ro: 1209 | continue 1210 | if mid == self.mid: 1211 | attr = attr_active 1212 | else: 1213 | attr = attr_inactive 1214 | 1215 | s = ' %d-%s ' % (mid, mode.name) 1216 | self.addstr(ypos, xpos, s, attr) 1217 | xpos += len(s) 1218 | 1219 | if 0 < self.mid < 5 and self.cstat: 1220 | if self.cstat['iid'] > 0 and self.cstat['sid'] > 0: 1221 | if self.data.socket.ro: 1222 | s = 'READ-ONLY [#%d/#%d]' % ( 1223 | self.cstat['iid'], self.cstat['sid']) 1224 | else: 1225 | s = 'ENTER=MENU SPACE=SEL [#%d/#%d]' % ( 1226 | self.cstat['iid'], self.cstat['sid']) 1227 | else: 1228 | if self.data.socket.ro: 1229 | s = 'READ-ONLY [#%d/#%d]' % ( 1230 | self.cstat['iid'], self.cstat['sid']) 1231 | else: 1232 | s = '[#%d/#%d]' % ( 1233 | self.cstat['iid'], self.cstat['sid']) 1234 | elif self.mid == 5: 1235 | s = 'PGUP/PGDOWN=SCROLL' 1236 | else: 1237 | s = 'UP/DOWN=SCROLL H=HELP Q=QUIT' 1238 | self.addstr(ypos, self.xmax - len(s) - 1, s, attr_inactive) 1239 | 1240 | def draw_stat(self): 1241 | for idx, line in self.screenlines: 1242 | if self.cursor and idx == self.cpos: 1243 | attr = line.attr | curses.A_REVERSE 1244 | else: 1245 | attr = line.attr 1246 | if not line.stat: 1247 | screenline = get_cell(self.xmax, 'L', line.text) 1248 | elif 'message' in line.stat: 1249 | screenline = get_cell(self.xmax, 'L', line.stat['message']) 1250 | else: 1251 | screenline = get_screenline(self.mode, line.stat) 1252 | self.addstr(self.smin + idx, self.xmin, screenline, attr) 1253 | 1254 | def draw_mode(self): 1255 | if self.mid == 0: 1256 | self.help.draw() 1257 | elif self.mid == 5 and self._pmid == self._cmid: 1258 | self.cli.start() # initial mid was 5 1259 | elif 0 < self.mid < 5: 1260 | self.draw_stat() 1261 | 1262 | def mvc(self, n): 1263 | if n == 0: 1264 | return 1265 | 1266 | # Move DOWN 1267 | if n > 0: 1268 | # move cursor 1269 | if self.cpos < self.cmax: 1270 | self.cpos = min(self.cmax, self.cpos + n) 1271 | return 1272 | # move screenlines 1273 | maxvmin = max(0, len(self.lines) - self.span - 1) 1274 | if self.cpos == self.cmax and self.vmin < maxvmin: 1275 | self.vmin = min(maxvmin, self.vmin + n) 1276 | 1277 | # Move UP 1278 | elif n < 0: # UP 1279 | # move cursor 1280 | if self.cpos > self.cmin: 1281 | self.cpos = max(self.cmin, self.cpos + n) 1282 | return 1283 | # move screenlines 1284 | if self.cpos == self.cmin and self.vmin > 0: 1285 | self.vmin = max(0, self.vmin + n) 1286 | 1287 | def mvhome(self): 1288 | # move cursor 1289 | if self.cpos != self.cmin: 1290 | self.cpos = self.cmin 1291 | # move screenlines 1292 | if self.vmin != 0: 1293 | self.vmin = 0 1294 | 1295 | def mvend(self): 1296 | # move cursor 1297 | if self.cpos != self.cmax: 1298 | self.cpos = self.cmax 1299 | # move screenlines 1300 | maxvmin = max(0, len(self.lines) - self.span - 1) 1301 | if self.vmin != maxvmin: 1302 | self.vmin = maxvmin 1303 | 1304 | 1305 | class ScreenHelp: 1306 | 1307 | def __init__(self, screen): 1308 | self.screen = screen 1309 | self.xmin = screen.xmin + 1 1310 | self.xmax = screen.xmax 1311 | self.ymin = 0 1312 | self.ymax = __doc__.count('\n') 1313 | self.xpos = 0 1314 | self.ypos = 0 1315 | 1316 | def setup(self): 1317 | self.pad = curses.newpad(self.ymax + 1, self.xmax + 1) 1318 | 1319 | def addstr(self, *args, **kwargs): 1320 | return self.pad.addstr(*args, **kwargs) 1321 | 1322 | def refresh(self): 1323 | self.pad.noutrefresh( 1324 | self.ypos, self.xpos, 1325 | self.screen.smin, self.xmin, 1326 | self.screen.smax, self.xmax - 2) 1327 | 1328 | def draw(self): 1329 | self.addstr(0, 0, __doc__) 1330 | 1331 | def mvc(self, n): 1332 | if n == 0: 1333 | return 1334 | 1335 | # Move DOWN 1336 | if n > 0: 1337 | self.ypos = min(self.ymax - self.screen.span, self.ypos + n) 1338 | 1339 | # Move UP 1340 | elif n < 0: 1341 | self.ypos = max(self.ymin, self.ypos + n) 1342 | 1343 | def mvhome(self): 1344 | self.ypos = self.ymin 1345 | 1346 | def mvend(self): 1347 | self.ypos = self.ymax - self.screen.span 1348 | 1349 | 1350 | class ScreenMode: 1351 | 1352 | def __init__(self, name): 1353 | self.name = name 1354 | self.columns = [] 1355 | 1356 | @property 1357 | def head(self): 1358 | return get_head(self) 1359 | 1360 | def sync(self, screen): 1361 | for idx, column in enumerate(self.columns): 1362 | column.width = get_width(column.minwidth, screen.xmax, 1363 | len(self.columns), idx) 1364 | 1365 | 1366 | class ScreenColumn: 1367 | 1368 | def __init__(self, name, header, minwidth, maxwidth, align, filters={}): 1369 | self.name = name 1370 | self.header = header 1371 | self.align = align 1372 | self.minwidth = minwidth 1373 | self.maxwidth = maxwidth 1374 | self.width = minwidth 1375 | self.filters = {'always': [], 'ondemand': []} 1376 | self.filters.update(filters) 1377 | 1378 | def get_width(self): 1379 | return self._width 1380 | 1381 | def set_width(self, n): 1382 | if self.maxwidth: 1383 | self._width = min(self.maxwidth, n) 1384 | self._width = max(self.minwidth, n) 1385 | 1386 | width = property(get_width, set_width) 1387 | 1388 | 1389 | class ScreenLine: 1390 | 1391 | def __init__(self, stat=None, text='', attr=0): 1392 | self.stat = stat 1393 | self.text = text 1394 | self.attr = attr 1395 | 1396 | 1397 | class StatusBar: 1398 | 1399 | def __init__(self, width=60, min=0, max=100, status=True): 1400 | self.width = width 1401 | self.curval = min 1402 | self.minval = min 1403 | self.maxval = max 1404 | self.status = status 1405 | self.prepend = '[' 1406 | self.append = ']' 1407 | self.usedchar = '|' 1408 | self.freechar = ' ' 1409 | 1410 | def __str__(self): 1411 | if self.status: 1412 | status = '%d/%d' % (self.curval, self.maxval) 1413 | 1414 | space = self.width - len(self.prepend) - len(self.append) 1415 | span = self.maxval - self.minval 1416 | 1417 | if span: 1418 | used = min(float(self.curval) / float(span), 1.0) 1419 | else: 1420 | used = 0.0 1421 | free = 1.0 - used 1422 | 1423 | # 100% equals full bar width, ignoring status text within the bar 1424 | bar = self.prepend 1425 | bar += self.usedchar * int(space * used) 1426 | bar += self.freechar * int(space * free) 1427 | if self.status: 1428 | bar = bar[:(self.width - len(status) - len(self.append))] 1429 | bar += status 1430 | bar += self.append 1431 | 1432 | return bar 1433 | 1434 | def update_cur(self, value): 1435 | value = min(self.maxval, value) 1436 | value = max(self.minval, value) 1437 | self.curval = value 1438 | 1439 | def update_max(self, value): 1440 | if value >= self.minval: 1441 | self.maxval = value 1442 | else: 1443 | self.maxval = self.minval 1444 | 1445 | # ------------------------------------------------------------------------- # 1446 | # DISPLAY FILTERS # 1447 | # ------------------------------------------------------------------------- # 1448 | 1449 | def human_seconds(numeric): 1450 | for minval, prefix in sorted(PREFIX_TIME.items(), reverse=True): 1451 | if (numeric/minval): 1452 | return '%d%s' % (numeric/minval, prefix) 1453 | return '%ds' % numeric 1454 | 1455 | def human_metric(numeric): 1456 | for minval, prefix in sorted(PREFIX_METRIC.items(), reverse=True): 1457 | if (numeric/minval): 1458 | return '%d%s' % (numeric/minval, prefix) 1459 | return str(numeric) 1460 | 1461 | def human_binary(numeric): 1462 | for minval, prefix in sorted(PREFIX_BINARY.items(), reverse=True): 1463 | if (numeric/minval): 1464 | return '%.2f%s' % (float(numeric)/float(minval), prefix) 1465 | return '%dB' % numeric 1466 | 1467 | def trim(string, length): 1468 | if len(string) <= length: 1469 | return string 1470 | if length == 1: 1471 | return string[0] 1472 | if length > 5: 1473 | return '..%s' % string[-(length-2):] 1474 | return '...' 1475 | 1476 | # ------------------------------------------------------------------------- # 1477 | # SCREEN LAYOUT # 1478 | # ------------------------------------------------------------------------- # 1479 | 1480 | SCREEN_MODES = [ 1481 | ScreenMode('HELP'), 1482 | ScreenMode('STATUS'), 1483 | ScreenMode('TRAFFIC'), 1484 | ScreenMode('HTTP'), 1485 | ScreenMode('ERRORS'), 1486 | ScreenMode('CLI'), 1487 | ] 1488 | 1489 | # Mode: HELP name header xmin xmax align 1490 | SCREEN_MODES[0].columns = [ 1491 | ScreenColumn('help', ' HATop Online Help ', 1492 | SCREEN_XMIN, 0, 'L'), 1493 | ] 1494 | 1495 | # Mode: STATUS name header xmin xmax align 1496 | SCREEN_MODES[1].columns = [ 1497 | ScreenColumn('svname', 'NAME', 10, 50, 'L'), 1498 | ScreenColumn('weight', 'W', 4, 6, 'R'), 1499 | ScreenColumn('status', 'STATUS', 6, 10, 'L'), 1500 | ScreenColumn('check_status', 'CHECK', 7, 20, 'L'), 1501 | ScreenColumn('act', 'ACT', 3, 0, 'R', 1502 | filters={'ondemand': [human_metric]}), 1503 | ScreenColumn('bck', 'BCK', 3, 0, 'R', 1504 | filters={'ondemand': [human_metric]}), 1505 | ScreenColumn('qcur', 'QCUR', 5, 0, 'R', 1506 | filters={'ondemand': [human_metric]}), 1507 | ScreenColumn('qmax', 'QMAX', 5, 0, 'R', 1508 | filters={'ondemand': [human_metric]}), 1509 | ScreenColumn('scur', 'SCUR', 6, 0, 'R', 1510 | filters={'ondemand': [human_metric]}), 1511 | ScreenColumn('smax', 'SMAX', 6, 0, 'R', 1512 | filters={'ondemand': [human_metric]}), 1513 | ScreenColumn('slim', 'SLIM', 6, 0, 'R', 1514 | filters={'ondemand': [human_metric]}), 1515 | ScreenColumn('stot', 'STOT', 6, 0, 'R', 1516 | filters={'ondemand': [human_metric]}), 1517 | ] 1518 | 1519 | # Mode: TRAFFIC name header xmin xmax align 1520 | SCREEN_MODES[2].columns = [ 1521 | ScreenColumn('svname', 'NAME', 10, 50, 'L'), 1522 | ScreenColumn('weight', 'W', 4, 6, 'R'), 1523 | ScreenColumn('status', 'STATUS', 6, 10, 'L'), 1524 | ScreenColumn('lbtot', 'LBTOT', 8, 0, 'R', 1525 | filters={'ondemand': [human_metric]}), 1526 | ScreenColumn('rate', 'RATE', 6, 0, 'R', 1527 | filters={'ondemand': [human_metric]}), 1528 | ScreenColumn('rate_lim', 'RLIM', 6, 0, 'R', 1529 | filters={'ondemand': [human_metric]}), 1530 | ScreenColumn('rate_max', 'RMAX', 6, 0, 'R', 1531 | filters={'ondemand': [human_metric]}), 1532 | ScreenColumn('bin', 'BIN', 12, 0, 'R', 1533 | filters={'always': [human_binary]}), 1534 | ScreenColumn('bout', 'BOUT', 12, 0, 'R', 1535 | filters={'always': [human_binary]}), 1536 | ] 1537 | 1538 | # Mode: HTTP name header xmin xmax align 1539 | SCREEN_MODES[3].columns = [ 1540 | ScreenColumn('svname', 'NAME', 10, 50, 'L'), 1541 | ScreenColumn('weight', 'W', 4, 6, 'R'), 1542 | ScreenColumn('status', 'STATUS', 6, 10, 'L'), 1543 | ScreenColumn('req_rate', 'RATE', 5, 0, 'R', 1544 | filters={'ondemand': [human_metric]}), 1545 | ScreenColumn('req_rate_max', 'RMAX', 5, 0, 'R', 1546 | filters={'ondemand': [human_metric]}), 1547 | ScreenColumn('req_tot', 'RTOT', 7, 0, 'R', 1548 | filters={'ondemand': [human_metric]}), 1549 | ScreenColumn('hrsp_1xx', '1xx', 5, 0, 'R', 1550 | filters={'ondemand': [human_metric]}), 1551 | ScreenColumn('hrsp_2xx', '2xx', 5, 0, 'R', 1552 | filters={'ondemand': [human_metric]}), 1553 | ScreenColumn('hrsp_3xx', '3xx', 5, 0, 'R', 1554 | filters={'ondemand': [human_metric]}), 1555 | ScreenColumn('hrsp_4xx', '4xx', 5, 0, 'R', 1556 | filters={'ondemand': [human_metric]}), 1557 | ScreenColumn('hrsp_5xx', '5xx', 5, 0, 'R', 1558 | filters={'ondemand': [human_metric]}), 1559 | ScreenColumn('hrsp_other', '?xx', 5, 0, 'R', 1560 | filters={'ondemand': [human_metric]}), 1561 | ] 1562 | 1563 | # Mode: ERRORS name header xmin xmax align 1564 | SCREEN_MODES[4].columns = [ 1565 | ScreenColumn('svname', 'NAME', 10, 50, 'L'), 1566 | ScreenColumn('weight', 'W', 4, 6, 'R'), 1567 | ScreenColumn('status', 'STATUS', 6, 10, 'L'), 1568 | ScreenColumn('check_status', 'CHECK', 7, 20, 'L'), 1569 | ScreenColumn('chkfail', 'CF', 3, 0, 'R', 1570 | filters={'ondemand': [human_metric]}), 1571 | ScreenColumn('chkdown', 'CD', 3, 0, 'R', 1572 | filters={'ondemand': [human_metric]}), 1573 | ScreenColumn('lastchg', 'CL', 3, 0, 'R', 1574 | filters={'always': [human_seconds]}), 1575 | ScreenColumn('econ', 'ECONN', 5, 0, 'R', 1576 | filters={'ondemand': [human_metric]}), 1577 | ScreenColumn('ereq', 'EREQ', 5, 0, 'R', 1578 | filters={'ondemand': [human_metric]}), 1579 | ScreenColumn('eresp', 'ERSP', 5, 0, 'R', 1580 | filters={'ondemand': [human_metric]}), 1581 | ScreenColumn('dreq', 'DREQ', 5, 0, 'R', 1582 | filters={'ondemand': [human_metric]}), 1583 | ScreenColumn('dresp', 'DRSP', 5, 0, 'R', 1584 | filters={'ondemand': [human_metric]}), 1585 | ScreenColumn('downtime', 'DOWN', 5, 0, 'R', 1586 | filters={'always': [human_seconds]}), 1587 | ] 1588 | 1589 | # Mode: CLI name header xmin xmax align 1590 | SCREEN_MODES[5].columns = [ 1591 | ScreenColumn('cli', 1592 | ' haproxy command line ' 1593 | ' use ALT-n / ESC-n to escape', 1594 | SCREEN_XMIN, 0, 'L'), 1595 | ] 1596 | 1597 | # ------------------------------------------------------------------------- # 1598 | # HELPERS # 1599 | # ------------------------------------------------------------------------- # 1600 | 1601 | def log(msg): 1602 | sys.stderr.write('%s\n' % msg) 1603 | 1604 | def parse_stat(iterable): 1605 | pxcount = svcount = 0 1606 | pxstat = {} # {iid: {sid: svstat, ...}, ...} 1607 | 1608 | idx_iid = get_idx('iid') 1609 | idx_sid = get_idx('sid') 1610 | 1611 | for line in iterable: 1612 | if not line: 1613 | continue 1614 | if line.startswith(HAPROXY_STAT_COMMENT): 1615 | continue # comment 1616 | if line.count(HAPROXY_STAT_SEP) < HAPROXY_STAT_NUMFIELDS: 1617 | continue # unknown format 1618 | 1619 | csv = line.split(HAPROXY_STAT_SEP, HAPROXY_STAT_NUMFIELDS) 1620 | 1621 | # Skip further parsing? 1622 | if svcount > HAPROXY_STAT_MAX_SERVICES: 1623 | try: 1624 | iid = csv[idx_iid] 1625 | iid = int(iid, 10) 1626 | except ValueError: 1627 | raise RuntimeError( 1628 | 'garbage proxy identifier: iid="%s" (need %s)' % 1629 | (iid, int)) 1630 | try: 1631 | sid = csv[idx_sid] 1632 | sid = int(sid, 10) 1633 | except ValueError: 1634 | raise RuntimeError( 1635 | 'garbage service identifier: sid="%s" (need %s)' % 1636 | (sid, int)) 1637 | if iid not in pxstat: 1638 | pxcount += 1 1639 | svcount += 1 1640 | elif sid not in pxstat[iid]: 1641 | svcount += 1 1642 | continue 1643 | 1644 | # Parse stat... 1645 | svstat = {} # {field: value, ...} 1646 | 1647 | for idx, field in HAPROXY_STAT_CSV: 1648 | field_type, field_name = field 1649 | value = csv[idx] 1650 | 1651 | try: 1652 | if field_type is int: 1653 | if len(value): 1654 | value = int(value, 10) 1655 | else: 1656 | value = 0 1657 | elif field_type is not type(value): 1658 | value = field_type(value) 1659 | except ValueError: 1660 | raise RuntimeError('garbage field: %s="%s" (need %s)' % ( 1661 | field_name, value, field_type)) 1662 | 1663 | # Special case 1664 | if field_name == 'status' and value == 'no check': 1665 | value = '-' 1666 | elif field_name == 'check_status' and svstat['status'] == '-': 1667 | value = 'none' 1668 | 1669 | svstat[field_name] = value 1670 | 1671 | # Record result... 1672 | iid = svstat['iid'] 1673 | stype = svstat['type'] 1674 | 1675 | if stype == 0 or stype == 1: # FRONTEND / BACKEND 1676 | id = svstat['svname'] 1677 | else: 1678 | id = svstat['sid'] 1679 | 1680 | try: 1681 | pxstat[iid][id] = svstat 1682 | except KeyError: 1683 | pxstat[iid] = { id: svstat } 1684 | pxcount += 1 1685 | svcount += 1 1686 | 1687 | return pxstat, pxcount, svcount 1688 | 1689 | def parse_info(iterable): 1690 | info = {} 1691 | for line in iterable: 1692 | line = line.strip() 1693 | if not line: 1694 | continue 1695 | for key, regexp in HAPROXY_INFO_RE.iteritems(): 1696 | match = regexp.match(line) 1697 | if match: 1698 | info[key] = match.group('value') 1699 | break 1700 | 1701 | for key in HAPROXY_INFO_RE.iterkeys(): 1702 | if not key in info: 1703 | raise RuntimeError('missing "%s" in info data' % key) 1704 | 1705 | return info 1706 | 1707 | def get_idx(field): 1708 | return filter(lambda x: x[1][1] == field, HAPROXY_STAT_CSV)[0][0] 1709 | 1710 | def get_width(width, xmax, ncols, idx): 1711 | # distribute excess space evenly from left to right 1712 | if xmax > SCREEN_XMIN: 1713 | xdiff = xmax - SCREEN_XMIN 1714 | if xdiff <= ncols: 1715 | if idx < xdiff: 1716 | width += 1 1717 | else: 1718 | if idx < (xdiff - (xdiff / ncols) * ncols): 1719 | width += 1 # compensate rounding 1720 | width = width + xdiff / ncols 1721 | return width 1722 | 1723 | def get_cell(width, align, value): 1724 | s = str(value) 1725 | if align == 'L': 1726 | s = s.ljust(width) 1727 | elif align == 'C': 1728 | s = s.center(width) 1729 | elif align == 'R': 1730 | s = s.rjust(width) 1731 | return s 1732 | 1733 | def get_head(mode): 1734 | columns = [] 1735 | for column in mode.columns: 1736 | s = column.header 1737 | s = get_cell(column.width, column.align, s) 1738 | columns.append(s) 1739 | return ' '.join(columns) 1740 | 1741 | def get_screenlines(stat): 1742 | screenlines = [] 1743 | 1744 | for iid, svstats in stat.iteritems(): 1745 | lines = [] 1746 | 1747 | try: 1748 | frontend = svstats.pop('FRONTEND') 1749 | except KeyError: 1750 | frontend = None 1751 | try: 1752 | backend = svstats.pop('BACKEND') 1753 | except KeyError: 1754 | backend = None 1755 | 1756 | if frontend: 1757 | lines.append(ScreenLine(stat=frontend)) 1758 | 1759 | for sid, svstat in sorted(svstats.items()): 1760 | lines.append(ScreenLine(stat=svstat)) 1761 | 1762 | if backend: 1763 | lines.append(ScreenLine(stat=backend)) 1764 | 1765 | if not len(lines): 1766 | continue 1767 | 1768 | pxname = lines[0].stat['pxname'] 1769 | screenlines.append(ScreenLine(attr=curses.A_BOLD, 1770 | text='>>> %s' % pxname)) 1771 | screenlines += lines 1772 | screenlines.append(ScreenLine()) 1773 | 1774 | # remove trailing empty line 1775 | if len(screenlines) > 1: 1776 | screenlines.pop() 1777 | 1778 | return screenlines 1779 | 1780 | def get_screenline(mode, stat): 1781 | cells = [] 1782 | for column in mode.columns: 1783 | value = stat[column.name] 1784 | 1785 | for filter in column.filters['always']: 1786 | value = filter(value) 1787 | 1788 | if len(str(value)) > column.width: 1789 | for filter in column.filters['ondemand']: 1790 | value = filter(value) 1791 | 1792 | value = str(value) 1793 | value = trim(value, column.width) 1794 | cells.append(get_cell(column.width, column.align, value)) 1795 | 1796 | return ' '.join(cells) 1797 | 1798 | # ------------------------------------------------------------------------- # 1799 | # CURSES HELPERS # 1800 | # ------------------------------------------------------------------------- # 1801 | 1802 | def curses_init(): 1803 | screen = curses.initscr() 1804 | curses.noecho() 1805 | curses.nonl() 1806 | curses.raw() 1807 | 1808 | # Some terminals don't support different cursor visibilities 1809 | try: 1810 | curses.curs_set(0) 1811 | except CursesError: 1812 | pass 1813 | 1814 | # Some terminals don't support the default color palette 1815 | try: 1816 | curses.start_color() 1817 | curses.use_default_colors() 1818 | except CursesError: 1819 | pass 1820 | 1821 | return screen 1822 | 1823 | def curses_reset(screen): 1824 | if not screen: 1825 | return 1826 | screen.keypad(0) 1827 | curses.noraw() 1828 | curses.echo() 1829 | curses.endwin() 1830 | 1831 | # ------------------------------------------------------------------------- # 1832 | # MAIN LOOP # 1833 | # ------------------------------------------------------------------------- # 1834 | 1835 | def mainloop(screen, interval): 1836 | # Sleep time of each iteration in seconds 1837 | scan = 1.0 / 100.0 1838 | # Query socket and redraw the screen in the given interval 1839 | iterations = interval / scan 1840 | 1841 | i = 0 1842 | update_stat = True # Toggle stat update (query socket, parse csv) 1843 | update_lines = True # Toggle screen line update (sync with stat data) 1844 | update_display = True # Toggle screen update (resize, repaint, refresh) 1845 | switch_mode = False # Toggle mode / viewport switch 1846 | 1847 | while True: 1848 | 1849 | # Resize toggled by SIGWINCH? 1850 | if screen.resized: 1851 | screen.resize() 1852 | update_display = True 1853 | 1854 | # Update interval reached... 1855 | if i == iterations: 1856 | update_stat = True 1857 | if 0 < screen.mid < 5: 1858 | update_lines = True 1859 | update_display = True 1860 | i = 0 1861 | 1862 | # Refresh screen? 1863 | if update_display: 1864 | 1865 | if update_stat: 1866 | screen.update_data() 1867 | screen.update_bars() 1868 | update_stat = False 1869 | 1870 | if update_lines: 1871 | screen.update_lines() 1872 | update_lines = False 1873 | 1874 | screen.erase() 1875 | screen.draw_head() 1876 | screen.draw_info() 1877 | screen.draw_cols() 1878 | screen.draw_mode() 1879 | screen.draw_foot() 1880 | screen.refresh() 1881 | 1882 | update_display = False 1883 | 1884 | c = screen.getch() 1885 | 1886 | if c < 0: 1887 | time.sleep(scan) 1888 | i += 1 1889 | continue 1890 | 1891 | # Toggle hotkey footer 1892 | if screen.hotkeys: 1893 | if c not in ( 1894 | curses.KEY_F4, # reset weight 1895 | curses.KEY_F5, # weight -10 1896 | curses.KEY_F6, # weight -1 1897 | curses.KEY_F7, # weight +1 1898 | curses.KEY_F8, # weight +10 1899 | curses.KEY_F9, # enable server 1900 | curses.KEY_F10, # disable server 1901 | ): 1902 | screen.hotkeys = False 1903 | update_display = True 1904 | if c in ( 1905 | curses.KEY_ENTER, 1906 | curses.ascii.CR 1907 | ): 1908 | continue 1909 | 1910 | if c == curses.ascii.ETX: 1911 | raise KeyboardInterrupt() 1912 | 1913 | # Mode switch (ALT-n / ESC-n) or toggle (ESC / ESC-ESC) 1914 | if c == curses.ascii.ESC: 1915 | c = screen.getch() 1916 | if c < 0 or c == curses.ascii.ESC: 1917 | screen.toggle_mode() 1918 | update_display = True 1919 | continue 1920 | if 0 < c < 256: 1921 | c = chr(c) 1922 | if c in 'qQHh?12345': 1923 | switch_mode = True 1924 | 1925 | # Mode cycle (TAB / BTAB) 1926 | elif c == ord('\t'): 1927 | screen.cycle_mode(1) 1928 | update_display = True 1929 | continue 1930 | elif c == curses.KEY_BTAB: 1931 | screen.cycle_mode(-1) 1932 | update_display = True 1933 | continue 1934 | 1935 | # Mode switch in non-CLI modes using the number only 1936 | elif 0 <= screen.mid < 5 and 0 < c < 256: 1937 | c = chr(c) 1938 | if c in 'qQHh?12345': 1939 | switch_mode = True 1940 | 1941 | if switch_mode: 1942 | switch_mode = False 1943 | if c in 'qQ': 1944 | raise StopIteration() 1945 | if c != str(screen.mid) or (c in 'Hh?' and screen.mid != 0): 1946 | if c in 'Hh?': 1947 | screen.switch_mode(0) 1948 | elif c in '12345': 1949 | screen.switch_mode(int(c)) 1950 | 1951 | # Force screen update with existing data 1952 | update_display = True 1953 | continue 1954 | 1955 | # -> HELP 1956 | if screen.mid == 0: 1957 | if c == curses.KEY_UP and screen.help.ypos > 0: 1958 | screen.help.mvc(-1) 1959 | elif c == curses.KEY_DOWN and \ 1960 | screen.help.ypos < screen.help.ymax - screen.span: 1961 | screen.help.mvc(1) 1962 | elif c == curses.KEY_PPAGE and screen.help.ypos > 0: 1963 | screen.help.mvc(-10) 1964 | elif c == curses.KEY_NPAGE and \ 1965 | screen.help.ypos < screen.help.ymax - screen.span: 1966 | screen.help.mvc(10) 1967 | elif c == curses.ascii.SOH or c == curses.KEY_HOME: 1968 | screen.help.mvhome() 1969 | elif c == curses.ascii.ENQ or c == curses.KEY_END: 1970 | screen.help.mvend() 1971 | 1972 | # -> STATUS / TRAFFIC / HTTP / ERRORS 1973 | elif 1 <= screen.mid <= 4: 1974 | 1975 | # movements 1976 | if c == curses.KEY_UP: 1977 | screen.mvc(-1) 1978 | elif c == curses.KEY_DOWN: 1979 | screen.mvc(1) 1980 | elif c == curses.KEY_PPAGE: 1981 | screen.mvc(-10) 1982 | elif c == curses.KEY_NPAGE: 1983 | screen.mvc(10) 1984 | elif c == curses.ascii.SOH or c == curses.KEY_HOME: 1985 | screen.mvhome() 1986 | elif c == curses.ascii.ENQ or c == curses.KEY_END: 1987 | screen.mvend() 1988 | 1989 | # actions 1990 | elif c in ( 1991 | curses.KEY_ENTER, # show hotkeys 1992 | chr(curses.ascii.CR), # show hotkeys 1993 | chr(curses.ascii.SP), # copy & paste identifier 1994 | curses.KEY_F4, # reset weight 1995 | curses.KEY_F5, # weight -10 1996 | curses.KEY_F6, # weight -1 1997 | curses.KEY_F7, # weight +1 1998 | curses.KEY_F8, # weight +10 1999 | curses.KEY_F9, # enable server 2000 | curses.KEY_F10, # disable server 2001 | ): 2002 | if screen.data.socket.ro: 2003 | continue 2004 | if not screen.cstat: 2005 | continue 2006 | 2007 | if c == curses.KEY_ENTER or c == chr(curses.ascii.CR): 2008 | screen.hotkeys = True 2009 | update_display = True 2010 | continue 2011 | 2012 | iid = screen.cstat['iid'] 2013 | sid = screen.cstat['sid'] 2014 | 2015 | if iid <= 0 or sid <= 0: 2016 | continue 2017 | 2018 | pxname = screen.cstat['pxname'] 2019 | svname = screen.cstat['svname'] 2020 | 2021 | if not pxname or not svname: 2022 | continue 2023 | 2024 | notify = False 2025 | 2026 | if c == ' ': 2027 | if screen.cli.puts('%s/%s' % (pxname, svname)): 2028 | screen.switch_mode(5) 2029 | update_display = True 2030 | continue 2031 | elif c == curses.KEY_F4: 2032 | screen.cli.execute_cmdline( 2033 | 'set weight %s/%s 100%%' % (pxname, svname)) 2034 | notify = True 2035 | elif c == curses.KEY_F5: 2036 | curweight = screen.cstat['weight'] 2037 | if curweight <= 0: 2038 | continue 2039 | weight = max(0, curweight - 10) # - 10 2040 | screen.cli.execute_cmdline( 2041 | 'set weight %s/%s %d' % (pxname, svname, weight)) 2042 | notify = True 2043 | elif c == curses.KEY_F6: 2044 | curweight = screen.cstat['weight'] 2045 | if curweight <= 0: 2046 | continue 2047 | weight = max(0, curweight - 1) # - 1 2048 | screen.cli.execute_cmdline( 2049 | 'set weight %s/%s %d' % (pxname, svname, weight)) 2050 | notify = True 2051 | elif c == curses.KEY_F7: 2052 | curweight = screen.cstat['weight'] 2053 | if curweight >= 256: 2054 | continue 2055 | weight = min(256, curweight + 1) # + 1 2056 | screen.cli.execute_cmdline( 2057 | 'set weight %s/%s %d' % (pxname, svname, weight)) 2058 | notify = True 2059 | elif c == curses.KEY_F8: 2060 | curweight = screen.cstat['weight'] 2061 | if curweight >= 256: 2062 | continue 2063 | weight = min(256, curweight + 10) # + 10 2064 | screen.cli.execute_cmdline( 2065 | 'set weight %s/%s %d' % (pxname, svname, weight)) 2066 | notify = True 2067 | elif c == curses.KEY_F9: 2068 | screen.cli.execute_cmdline( 2069 | 'enable server %s/%s' % (pxname, svname)) 2070 | notify = True 2071 | elif c == curses.KEY_F10: 2072 | screen.cli.execute_cmdline( 2073 | 'disable server %s/%s' % (pxname, svname)) 2074 | notify = True 2075 | 2076 | # Refresh the screen indicating pending changes... 2077 | if notify: 2078 | screen.cstat['message'] = 'updating...' 2079 | update_display = True 2080 | continue 2081 | 2082 | # -> CLI 2083 | elif screen.mid == 5: 2084 | 2085 | # enter 2086 | if c == curses.KEY_ENTER or c == curses.ascii.CR: 2087 | screen.cli.execute() 2088 | 2089 | # input movements 2090 | elif c == curses.KEY_LEFT: 2091 | screen.cli.mvc(-1) 2092 | elif c == curses.KEY_RIGHT: 2093 | screen.cli.mvc(1) 2094 | elif c == curses.ascii.SOH or c == curses.KEY_HOME: 2095 | screen.cli.mvhome() 2096 | elif c == curses.ascii.ENQ or c == curses.KEY_END: 2097 | screen.cli.mvend() 2098 | 2099 | # input editing 2100 | elif c == curses.ascii.ETB: 2101 | pass # TODO (CTRL-W) 2102 | elif c == curses.KEY_DC: 2103 | screen.cli.delc(1) 2104 | elif c == curses.KEY_BACKSPACE or c == curses.ascii.DEL: 2105 | screen.cli.delc(-1) 2106 | 2107 | # input history 2108 | elif c == curses.KEY_UP: 2109 | screen.cli.prev() 2110 | elif c == curses.KEY_DOWN: 2111 | screen.cli.next() 2112 | 2113 | # output history 2114 | elif c == curses.KEY_PPAGE: 2115 | screen.cli.mvo(-1) 2116 | elif c == curses.KEY_NPAGE: 2117 | screen.cli.mvo(1) 2118 | 2119 | elif 0 < c < 256: 2120 | screen.cli.putc(chr(c)) 2121 | 2122 | # Force screen update with existing data if key was a movement key 2123 | if c in ( 2124 | curses.KEY_UP, 2125 | curses.KEY_DOWN, 2126 | curses.KEY_PPAGE, 2127 | curses.KEY_NPAGE, 2128 | ) or screen.mid != 5 and c in ( 2129 | curses.ascii.SOH, curses.KEY_HOME, 2130 | curses.ascii.ENQ, curses.KEY_END, 2131 | ): 2132 | update_display = True 2133 | 2134 | time.sleep(scan) 2135 | i += 1 2136 | 2137 | 2138 | if __name__ == '__main__': 2139 | 2140 | from optparse import OptionParser, OptionGroup 2141 | 2142 | version = 'hatop version %s' % __version__ 2143 | usage = 'Usage: hatop -s SOCKET [OPTIONS]... OR hatop -H HOST -P PORT [OPTIONS]...' 2144 | 2145 | parser = OptionParser(usage=usage, version=version) 2146 | 2147 | opts = OptionGroup(parser, 'Mandatory if connecting via UNIX domain socket') 2148 | opts.add_option('-s', '--unix-socket', dest='socket', 2149 | help='path to the haproxy unix socket') 2150 | parser.add_option_group(opts) 2151 | 2152 | opts = OptionGroup(parser, 'Mandatory if connecting via TCP') 2153 | opts.add_option('-P', '--port', type='int', dest='tcpport', 2154 | help='TCP port on haproxy server') 2155 | opts.add_option('-H', '--host', dest='tcphost', 2156 | help='Remote host to connect to via TCP') 2157 | 2158 | parser.add_option_group(opts) 2159 | 2160 | opts = OptionGroup(parser, 'Optional') 2161 | opts.add_option('-i', '--update-interval', type='int', dest='interval', 2162 | help='update interval in seconds (1-30, default: 3)', default=3) 2163 | opts.add_option('-m', '--mode', type='int', dest='mode', 2164 | help='start in specific mode (1-5, default: 1)', default=1) 2165 | opts.add_option('-n', '--read-only', action='store_true', dest='ro', 2166 | help='disable the cli and query for stats only') 2167 | parser.add_option_group(opts) 2168 | 2169 | opts = OptionGroup(parser, 'Filters', 2170 | 'Note: All filter options may be given multiple times.') 2171 | opts.add_option('-f', '--filter', action='append', dest='stat_filter', 2172 | default=[], metavar='FILTER', 2173 | help='stat filter in format " "') 2174 | opts.add_option('-p', '--proxy', action='append', dest='proxy_filter', 2175 | default=[], metavar='PROXY', 2176 | help='proxy filter in format ""') 2177 | parser.add_option_group(opts) 2178 | 2179 | opts, args = parser.parse_args() 2180 | 2181 | if not 1 <= opts.interval <= 30: 2182 | log('invalid update interval: %d' % opts.interval) 2183 | sys.exit(1) 2184 | if not 1 <= opts.mode <= 5: 2185 | log('invalid mode: %d' % opts.mode) 2186 | sys.exit(1) 2187 | if len(opts.stat_filter) + len(opts.proxy_filter) > 50: 2188 | log('filter limit exceeded (50)') 2189 | sys.exit(1) 2190 | if opts.ro and opts.mode == 5: 2191 | log('cli not available in read-only mode') 2192 | sys.exit(1) 2193 | if not opts.socket: 2194 | if not opts.tcphost or not opts.tcpport: 2195 | parser.print_help() 2196 | sys.exit(0) 2197 | if opts.socket and (opts.tcphost or opts.tcpport): 2198 | log('you can not use domain socket and TCP at the same time') 2199 | sys.exit(2) 2200 | if opts.socket: 2201 | connectionmode="socket" 2202 | if not os.access(opts.socket, os.R_OK | os.W_OK): 2203 | log('insufficient permissions for socket path %s' % opts.socket) 2204 | sys.exit(2) 2205 | if opts.tcphost and opts.tcpport: 2206 | connectionmode="tcp" 2207 | 2208 | socket = Socket(connectionmode, opts.socket, opts.tcphost, opts.tcpport, opts.ro) 2209 | data = SocketData(socket) 2210 | screen = Screen(data, opts.mode) 2211 | 2212 | signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(0)) 2213 | 2214 | try: 2215 | try: 2216 | socket.connect() 2217 | screen.setup() 2218 | 2219 | # Register filters 2220 | data.register_stat_filter(opts.stat_filter) 2221 | data.register_proxy_filter(opts.proxy_filter) 2222 | 2223 | while True: 2224 | try: 2225 | mainloop(screen, opts.interval) 2226 | except StopIteration: 2227 | break 2228 | except KeyboardInterrupt: 2229 | break 2230 | except CursesError, e: 2231 | screen.reset() 2232 | log('curses error: %s, restarting...' % e) 2233 | time.sleep(1) 2234 | screen.recover() 2235 | 2236 | except ValueError, e: 2237 | screen.reset() 2238 | log('value error: %s' % e) 2239 | sys.exit(1) 2240 | except RuntimeError, e: 2241 | screen.reset() 2242 | log('runtime error: %s' % e) 2243 | sys.exit(1) 2244 | except SocketError, e: 2245 | screen.reset() 2246 | log('socket error: %s' % e) 2247 | sys.exit(2) 2248 | 2249 | finally: 2250 | screen.reset() 2251 | socket.close() 2252 | 2253 | sys.exit(0) 2254 | 2255 | # vim: et sw=4 sts=4 ts=4 tw=78 fdn=1 fdm=indent 2256 | -------------------------------------------------------------------------------- /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 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/Wirehive/hatop/557ba48f3a743f23a20cf379c8cb773148fcb0d3/doc/images/0-help.png -------------------------------------------------------------------------------- /doc/images/1-status.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wirehive/hatop/557ba48f3a743f23a20cf379c8cb773148fcb0d3/doc/images/1-status.png -------------------------------------------------------------------------------- /doc/images/2-traffic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wirehive/hatop/557ba48f3a743f23a20cf379c8cb773148fcb0d3/doc/images/2-traffic.png -------------------------------------------------------------------------------- /doc/images/3-http.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wirehive/hatop/557ba48f3a743f23a20cf379c8cb773148fcb0d3/doc/images/3-http.png -------------------------------------------------------------------------------- /doc/images/4-errors.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wirehive/hatop/557ba48f3a743f23a20cf379c8cb773148fcb0d3/doc/images/4-errors.png -------------------------------------------------------------------------------- /doc/images/5-cli-help.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wirehive/hatop/557ba48f3a743f23a20cf379c8cb773148fcb0d3/doc/images/5-cli-help.png -------------------------------------------------------------------------------- /doc/images/5-cli.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wirehive/hatop/557ba48f3a743f23a20cf379c8cb773148fcb0d3/doc/images/5-cli.png -------------------------------------------------------------------------------- /doc/index.rst: -------------------------------------------------------------------------------- 1 | %%%%%%% 2 | Index 3 | %%%%%%% 4 | -------------------------------------------------------------------------------- /doc/install.rst: -------------------------------------------------------------------------------- 1 | .. _install: 2 | 3 | .. include:: ../INSTALL 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-2010 John Feuerstein. All rights reserved. 11 | 12 | ------- 13 | 14 | .. literalinclude:: ../LICENSE 15 | -------------------------------------------------------------------------------- /doc/readme.rst: -------------------------------------------------------------------------------- 1 | .. _readme: 2 | 3 | .. include:: ../README 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/Wirehive/hatop/557ba48f3a743f23a20cf379c8cb773148fcb0d3/doc/static/disk.png -------------------------------------------------------------------------------- /doc/static/glider.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wirehive/hatop/557ba48f3a743f23a20cf379c8cb773148fcb0d3/doc/static/glider.png -------------------------------------------------------------------------------- /doc/static/gplv3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wirehive/hatop/557ba48f3a743f23a20cf379c8cb773148fcb0d3/doc/static/gplv3.png -------------------------------------------------------------------------------- /doc/static/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wirehive/hatop/557ba48f3a743f23a20cf379c8cb773148fcb0d3/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 | \fBF4\fP 80 | Restore initial server weight 81 | 82 | .TP 83 | \fBF5\fP 84 | Decrease server weight: \- 10 85 | .TP 86 | \fBF6\fP 87 | Decrease server weight: \- 1 88 | .TP 89 | \fBF7\fP 90 | Increase server weight: + 1 91 | .TP 92 | \fBF8\fP 93 | Increase server weight: + 10 94 | 95 | .TP 96 | \fBF9\fP 97 | Enable server (return from maintenance mode) 98 | .TP 99 | \fBF10\fP 100 | Disable server (put into maintenance mode) 101 | .SH SEE ALSO 102 | .BR haproxy (1) 103 | 104 | A much better documentation can be found online: 105 | .PP 106 | http://feurix.org/projects/hatop/ 107 | .SH AUTHOR 108 | HATop and this man page was written by John Feuerstein. 109 | -------------------------------------------------------------------------------- /test/.gitignore: -------------------------------------------------------------------------------- 1 | *.sock 2 | *.txt 3 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------