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