├── gcam ├── src ├── common.py ├── errors.py ├── packager.py ├── params.py ├── numsort.py ├── prettytable.py └── __main__.py ├── README.md └── LICENSE /gcam: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | path=$(readlink "$0" || echo "$0") 4 | path=$(dirname "$path") 5 | 6 | python3 "$path/src/__main__.py" "$@" 7 | -------------------------------------------------------------------------------- /src/common.py: -------------------------------------------------------------------------------- 1 | """Provide functions that could potentially have shared use.""" 2 | 3 | import itertools 4 | 5 | def grouper(n, iterable): 6 | """Return an iterable with items grouped into tuples of length n.""" 7 | # grouper(3, 'ABCDEF') --> ABC DEF 8 | # Derived from http://docs.python.org/dev/py3k/library/itertools.html#itertools-recipes 9 | args = [iter(iterable)] * n 10 | return zip(*args) 11 | 12 | def pairwise(iterable): 13 | """Return an iterable with items grouped pairwise.""" 14 | # pairwise(s) --> (s0,s1), (s1,s2), (s2, s3), ... 15 | # From http://docs.python.org/dev/py3k/library/itertools.html#itertools-recipes 16 | a, b = itertools.tee(iterable) 17 | next(b, None) 18 | return zip(a, b) 19 | -------------------------------------------------------------------------------- /src/errors.py: -------------------------------------------------------------------------------- 1 | # Reference: 2 | # http://docs.python.org/dev/py3k/library/exceptions.html 3 | # http://docs.python.org/dev/py3k/tutorial/errors.html 4 | 5 | class Error(Exception): 6 | """Base class for exceptions in this module. 7 | 8 | Exceptions are expected to be raised with a descriptive str message 9 | argument.""" 10 | 11 | class ArgumentError(Error): 12 | """Exception raised for an invalid argument value provided by the user 13 | either on the command line or in the parameters file. 14 | """ 15 | 16 | class SubprocessError(Error): 17 | """Exception raised for an error while attempting to run a subprocess.""" 18 | 19 | class TTYError(Error): 20 | """Exception raised if stdout is not connected to a tty-like device.""" -------------------------------------------------------------------------------- /src/packager.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os, sys, zipfile 4 | 5 | ## Usage: run from directory containing file. 6 | 7 | # Determine required parameter values 8 | app_path = os.getcwd() 9 | app_name = os.path.basename(app_path) # or params._PROGRAM_NAME_SHORT 10 | python_exec_name = os.path.basename(sys.executable) 11 | 12 | # Create zipfile (for provisioning source code) 13 | 14 | zipfile_ = '{}.{}.zip'.format(app_name, python_exec_name) 15 | filenames = [f for f in os.listdir(app_path) if 16 | ((os.path.splitext(f)[1] in ('.py',)) and ('backup' not in f))] 17 | filenames.append(app_name) 18 | filenames.sort() 19 | 20 | zipfile_ = zipfile.ZipFile(zipfile_, mode='w') 21 | for f in filenames: zipfile_.write(f) 22 | zipfile_.close() 23 | 24 | # Create pyzipfile (for provisioning application) 25 | 26 | zipfile_ = '{}.compiled.{}.zip'.format(app_name, python_exec_name) 27 | 28 | zipfile_ = zipfile.PyZipFile(zipfile_, mode='w') 29 | zipfile_.writepy(app_path) 30 | zipfile_.close() 31 | -------------------------------------------------------------------------------- /src/params.py: -------------------------------------------------------------------------------- 1 | import os, tempfile 2 | 3 | # All parameters defined in this module should be named in full uppercase. This 4 | # hack allows the logging module to identify them. 5 | 6 | # Values of the parameters defined here may be updated based on command line 7 | # arguments to the program. 8 | 9 | _PROGRAM_NAME = 'GPFS Current Activity Monitor' 10 | 11 | _PROGRAM_NAME_SHORT = 'gcam' 12 | # = (''.join([c[0] for c in _PROGRAM_NAME.split()])).lower() 13 | 14 | DEBUG_MMPMON_RUNS = 3 15 | # Min should be 2 because calculated deltas are 1 less. To run continuously, 16 | # use 0. 17 | 18 | DEBUG_MODE = False 19 | 20 | DEBUG_NODES = ['penguin1', 'gadolinium'] 21 | 22 | DISPLAY_PAUSE_KEY = ' ' 23 | # Can be any single key. The same key is also used to resume the display. 24 | 25 | GPFS_NODESET = None 26 | # Can be a str. If None, first nodeset listed by mmlsnode is used. 27 | 28 | LOG_FILE_PATH = os.path.join(tempfile.gettempdir(), 29 | '{}{}{}'.format(_PROGRAM_NAME_SHORT, os.extsep, 30 | 'log')) 31 | 32 | LOG_FILE_WRITE = False 33 | # If True, log is written to file. 34 | 35 | LOG_LEVEL = 'info' 36 | # Can be 'info' or 'debug' 37 | 38 | LOG_NUM_MMPMON_LINES = 1000 39 | # Number of initial mmpmon output lines to log, contingent upon other logging 40 | # parameters. 41 | 42 | MMPMON_HOST = 'localhost' 43 | # Hostname of host on which to run mmpmon. Can also be localhost. 44 | 45 | MONITORING_INTERVAL_SECS = 3 46 | # Can't be less than 1. Can be an int or a float. 47 | 48 | PRINT_LAST_RECORD = True 49 | # If True, the last displayed record is printed to stdout. 50 | 51 | SSH_ARGS = ['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=4'] 52 | 53 | TABLE_TYPE = 'separated' 54 | # Can be 'separated' or 'interlaced' -------------------------------------------------------------------------------- /src/numsort.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python3 2 | 3 | ## {{{ http://code.activestate.com/recipes/135435/ (r1) 4 | # numsort.py 5 | # sorting in numeric order 6 | # for example: 7 | # ['aaa35', 'aaa6', 'aaa261'] 8 | # is sorted into: 9 | # ['aaa6', 'aaa35', 'aaa261'] 10 | 11 | import functools 12 | 13 | @functools.lru_cache(maxsize=None) 14 | def numsorted(alist): 15 | # inspired by Alex Martelli 16 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234 17 | indices = map(_generate_index, alist) 18 | decorated = list(zip(indices, alist)) 19 | decorated.sort() 20 | return [item for index, item in decorated] #@UnusedVariable 21 | 22 | def _generate_index(astr): 23 | """ 24 | Splits a string into alpha and numeric elements, which 25 | is used as an index for sorting" 26 | """ 27 | # 28 | # the index is built progressively 29 | # using the _append function 30 | # 31 | index = [] 32 | def _append(fragment, alist=index): 33 | if fragment.isdigit(): fragment = int(fragment) 34 | alist.append(fragment) 35 | 36 | # initialize loop 37 | prev_isdigit = astr[0].isdigit() 38 | current_fragment = '' 39 | # group a string into digit and non-digit parts 40 | for char in astr: 41 | curr_isdigit = char.isdigit() 42 | if curr_isdigit == prev_isdigit: 43 | current_fragment += char 44 | else: 45 | _append(current_fragment) 46 | current_fragment = char 47 | prev_isdigit = curr_isdigit 48 | _append(current_fragment) 49 | return tuple(index) 50 | 51 | 52 | def _test(): 53 | initial_list = [ 'gad', 'gad-10', 'zeus', 'gad-5', 'gad-0', 'gad-12' ] 54 | sorted_list = numsorted(initial_list) 55 | import pprint 56 | print("Before sorting...") 57 | pprint.pprint (initial_list) 58 | print("After sorting...") 59 | pprint.pprint (sorted_list) 60 | print("Normal python sorting produces...") 61 | initial_list.sort() 62 | pprint.pprint (initial_list) 63 | 64 | if __name__ == '__main__': 65 | _test() 66 | ## end of http://code.activestate.com/recipes/135435/ }}} 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gcam 2 | 3 | **gcam** ([GPFS](http://www-03.ibm.com/systems/software/gpfs/) Current Activity Monitor) uses [`mmpmon`](http://publib.boulder.ibm.com/infocenter/clresctr/vxrx/topic/com.ibm.cluster.gpfs321.advanceadm.doc/bl1adv_mmpmonch.html), Python 3, and [`ncurses`](http://www.gnu.org/software/ncurses/) on Linux to display in a console the current GPFS read and write bytes across all currently active GPFS nodes and all GPFS file systems in a given GPFS cluster. 4 | 5 | https://github.com/impredicative/gcam/ 6 | 7 | ## Contents 8 | - [Screenshot](#screenshot) 9 | - [Requirements](#requirements) 10 | - [Usage](#usage) 11 | - [Implementation](#implementation) 12 | - [License](#license) 13 | 14 | ## Screenshot 15 | 16 | 17 | ## Requirements 18 | * Linux or similar OS. The code is tested with [CentOS](http://centos.org/) 5.7. It has also been tested by users with CentOS 7. 19 | * GPFS. The code was developed with GPFS version 3.2.1-4. It has also been tested by users with GPFS versions 3.2.1-25, 3.3.0, and 4.2. It is not know whether other versions of GPFS provide compatible mmpmon output. It is possible for the host providing mmpmon output to be different from the host running `gcam`. 20 | * Python 3 with `curses` support. The code was developed with Python 3.2. It has also been tested by users with Python 3.4, 3.5, and 3.6. On CentOS, ensure that `ncurses`, `ncurses-devel`, and all other relevant `ncurses` packages are installed before installing Python. 21 | 22 | ## Usage 23 | The program can be run as `gcam` without any arguments. Run with the `-h` argument to display help and available command-line options. If the program fails to start, edit the `gcam` file. The `params.py` file in the source zip archive can be edited to change the default values of some options, although this should typically not be necessary. 24 | 25 | ### sudo 26 | If the program needs to be run by a non-root user `foousr`, use `visudo` to consider add a line such as: 27 | ``` 28 | foousr ALL=NOPASSWD: ~/gcam/gcam 29 | ``` 30 | This should allow the user to use `sudo` to run the program. For further ease of use, an alias `gcam` pointing to `sudo gcam` can be added for this user to prevent from having to explicitly use `sudo`. 31 | 32 | ## Implementation 33 | The program uses the `fs_io_s` command sent to the `mmpmon` program to obtain read and write bytes counters. It then calculates deltas over successive counters—these deltas are formatted and displayed on the screen. 34 | 35 | The code is not nearly as efficient as it can be. Additionally, it has some quadratic operations which may make it scale poorly. A significant rewrite, potentially leveraging [Pandas](https://github.com/pydata/pandas), is warranted to address these and other issues. 36 | 37 | `mmpmon` does not indicate when the current batch of counters has ended. The program currently learns of this by waiting until the next batch has begun. This delays the display by up to one iteration. The program can possibly be updated to use a more sophisticated approach to predict when the current batch has ended—this would reduce the display delay. 38 | 39 | If necessary, the _refresh interval_ parameter value can be increased by the user to proportionately spread out the program's CPU usage over time. For large installations, this can ensure that the program's CPU usage does not persistently approach 100% for the specific CPU core that is in use. 40 | 41 | At the current time, the program does not allow logging data for archival or analytic purposes, although it does allow diagnostic logging for debugging purposes. 42 | 43 | ## License 44 | See [license](LICENSE). For the `prettytable` module, see [src/prettytable.py](src/prettytable.py). 45 | -------------------------------------------------------------------------------- /src/prettytable.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # PrettyTable 0.5 4 | # Copyright (c) 2009, Luke Maurits 5 | # All rights reserved. 6 | # With contributions from: 7 | # * Chris Clark 8 | # 9 | # Redistribution and use in source and binary forms, with or without 10 | # modification, are permitted provided that the following conditions are met: 11 | # 12 | # * Redistributions of source code must retain the above copyright notice, 13 | # this list of conditions and the following disclaimer. 14 | # * Redistributions in binary form must reproduce the above copyright notice, 15 | # this list of conditions and the following disclaimer in the documentation 16 | # and/or other materials provided with the distribution. 17 | # * The name of the author may not be used to endorse or promote products 18 | # derived from this software without specific prior written permission. 19 | # 20 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 24 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 26 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 27 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 28 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 29 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 | # POSSIBILITY OF SUCH DAMAGE. 31 | 32 | import cgi 33 | import copy 34 | import pickle 35 | import sys 36 | 37 | FRAME = 0 38 | ALL = 1 39 | NONE = 2 40 | 41 | class PrettyTable: 42 | 43 | def __init__(self, fields=None, caching=True, padding_width=1, left_padding=None, right_padding=None): 44 | 45 | """Return a new PrettyTable instance 46 | 47 | Arguments: 48 | 49 | fields - list or tuple of field names 50 | caching - boolean value to turn string caching on/off 51 | padding width - number of spaces between column lines and content""" 52 | 53 | # Data 54 | self.fields = [] 55 | if fields: 56 | self.set_field_names(fields) 57 | else: 58 | self.widths = [] 59 | self.aligns = [] 60 | self.set_padding_width(padding_width) 61 | self.rows = [] 62 | self.cache = {} 63 | self.html_cache = {} 64 | 65 | # Options 66 | self.hrules = FRAME 67 | self.caching = caching 68 | self.padding_width = padding_width 69 | self.left_padding = left_padding 70 | self.right_padding = right_padding 71 | self.vertical_char = "|" 72 | self.horizontal_char = "-" 73 | self.junction_char = "+" 74 | 75 | def __getslice__(self, i, j): 76 | 77 | """Return a new PrettyTable whose data rows are a slice of this one's 78 | 79 | Arguments: 80 | 81 | i - beginning slice index 82 | j - ending slice index""" 83 | 84 | newtable = copy.deepcopy(self) 85 | newtable.rows = self.rows[i:j] 86 | return newtable 87 | 88 | def __str__(self): 89 | 90 | return self.get_string() 91 | 92 | ############################## 93 | # ATTRIBUTE SETTERS # 94 | ############################## 95 | 96 | def set_field_names(self, fields): 97 | 98 | """Set the names of the fields 99 | 100 | Arguments: 101 | 102 | fields - list or tuple of field names""" 103 | 104 | # We *may* need to change the widths if this isn't the first time 105 | # setting the field names. This could certainly be done more 106 | # efficiently. 107 | if self.fields: 108 | self.widths = [len(field) for field in fields] 109 | for row in self.rows: 110 | for i in range(0,len(row)): 111 | if len(str(row[i])) > self.widths[i]: 112 | self.widths[i] = len(str(row[i])) 113 | else: 114 | self.widths = [len(field) for field in fields] 115 | self.fields = fields 116 | self.aligns = len(fields)*["c"] 117 | self.cache = {} 118 | self.html_cache = {} 119 | 120 | def set_field_align(self, fieldname, align): 121 | 122 | """Set the alignment of a field by its fieldname 123 | 124 | Arguments: 125 | 126 | fieldname - name of the field whose alignment is to be changed 127 | align - desired alignment - "l" for left, "c" for centre and "r" for right""" 128 | 129 | if fieldname not in self.fields: 130 | raise Exception("No field %s exists!" % fieldname) 131 | if align not in ["l","c","r"]: 132 | raise Exception("Alignment %s is invalid, use l, c or r!" % align) 133 | self.aligns[self.fields.index(fieldname)] = align 134 | self.cache = {} 135 | self.html_cache = {} 136 | 137 | def set_padding_width(self, padding_width): 138 | 139 | """Set the number of empty spaces between a column's edge and its content 140 | 141 | Arguments: 142 | 143 | padding_width - number of spaces, must be a positive integer""" 144 | 145 | try: 146 | assert int(padding_width) >= 0 147 | except AssertionError: 148 | raise Exception("Invalid value for padding_width: %s!" % str(padding_width)) 149 | 150 | self.padding_width = padding_width 151 | self.cache = {} 152 | self.html_cache = {} 153 | 154 | def set_left_padding(self, left_padding): 155 | 156 | """Set the number of empty spaces between a column's left edge and its content 157 | 158 | Arguments: 159 | 160 | left_padding - number of spaces, must be a positive integer""" 161 | 162 | try: 163 | assert left_padding == None or int(left_padding) >= 0 164 | except AssertionError: 165 | raise Exception("Invalid value for left_padding: %s!" % str(left_padding)) 166 | 167 | self.left_padding = left_padding 168 | self.cache = {} 169 | self.html_cache = {} 170 | 171 | def set_right_padding(self, right_padding): 172 | 173 | """Set the number of empty spaces between a column's right edge and its content 174 | 175 | Arguments: 176 | 177 | right_padding - number of spaces, must be a positive integer""" 178 | 179 | try: 180 | assert right_padding == None or int(right_padding) >= 0 181 | except AssertionError: 182 | raise Exception("Invalid value for right_padding: %s!" % str(right_padding)) 183 | 184 | self.right_padding = right_padding 185 | self.cache = {} 186 | self.html_cache = {} 187 | 188 | def set_border_chars(self, vertical="|", horizontal="-", junction="+"): 189 | 190 | """Set the characters to use when drawing the table border 191 | 192 | Arguments: 193 | 194 | vertical - character used to draw a vertical line segment. Default is | 195 | horizontal - character used to draw a horizontal line segment. Default is - 196 | junction - character used to draw a line junction. Default is +""" 197 | 198 | if len(vertical) > 1 or len(horizontal) > 1 or len(junction) > 1: 199 | raise Exception("All border characters must be strings of length ONE!") 200 | self.vertical_char = vertical 201 | self.horizontal_char = horizontal 202 | self.junction_char = junction 203 | self.cache = {} 204 | 205 | ############################## 206 | # DATA INPUT METHODS # 207 | ############################## 208 | 209 | def add_row(self, row): 210 | 211 | """Add a row to the table 212 | 213 | Arguments: 214 | 215 | row - row of data, should be a list with as many elements as the table 216 | has fields""" 217 | 218 | if len(row) != len(self.fields): 219 | raise Exception("Row has incorrect number of values, (actual) %d!=%d (expected)" %(len(row),len(self.fields))) 220 | self.rows.append(row) 221 | for i in range(0,len(row)): 222 | if len(str(row[i])) > self.widths[i]: 223 | self.widths[i] = len(str(row[i])) 224 | self.html_cache = {} 225 | 226 | def add_column(self, fieldname, column, align="c"): 227 | 228 | """Add a column to the table. 229 | 230 | Arguments: 231 | 232 | fieldname - name of the field to contain the new column of data 233 | column - column of data, should be a list with as many elements as the 234 | table has rows 235 | align - desired alignment for this column - "l" for left, "c" for centre and "r" for right""" 236 | 237 | if len(self.rows) in (0, len(column)): 238 | if align not in ["l","c","r"]: 239 | raise Exception("Alignment %s is invalid, use l, c or r!" % align) 240 | self.fields.append(fieldname) 241 | self.widths.append(len(fieldname)) 242 | self.aligns.append(align) 243 | for i in range(0, len(column)): 244 | if len(self.rows) < i+1: 245 | self.rows.append([]) 246 | self.rows[i].append(column[i]) 247 | if len(str(column[i])) > self.widths[-1]: 248 | self.widths[-1] = len(str(column[i])) 249 | else: 250 | raise Exception("Column length %d does not match number of rows %d!" % (len(column), len(self.rows))) 251 | 252 | ############################## 253 | # MISC PRIVATE METHODS # 254 | ############################## 255 | 256 | def _get_sorted_rows(self, start, end, sortby, reversesort): 257 | # Sort rows using the "Decorate, Sort, Undecorate" (DSU) paradigm 258 | rows = copy.deepcopy(self.rows[start:end]) 259 | sortindex = self.fields.index(sortby) 260 | # Decorate 261 | rows = [[row[sortindex]]+row for row in rows] 262 | # Sort 263 | rows.sort(reverse=reversesort) 264 | # Undecorate 265 | rows = [row[1:] for row in rows] 266 | return rows 267 | 268 | def _get_paddings(self): 269 | 270 | if self.left_padding is not None: 271 | lpad = self.left_padding 272 | else: 273 | lpad = self.padding_width 274 | if self.right_padding is not None: 275 | rpad = self.right_padding 276 | else: 277 | rpad = self.padding_width 278 | return lpad, rpad 279 | 280 | ############################## 281 | # ASCII PRINT/STRING METHODS # 282 | ############################## 283 | 284 | def printt(self, start=0, end=None, fields=None, header=True, border=True, hrules=FRAME, sortby=None, reversesort=False): 285 | 286 | """Print table in current state to stdout. 287 | 288 | Arguments: 289 | 290 | start - index of first data row to include in output 291 | end - index of last data row to include in output PLUS ONE (list slice style) 292 | fields - names of fields (columns) to include 293 | sortby - name of field to sort rows by 294 | reversesort - True or False to sort in descending or ascending order 295 | border - should be True or False to print or not print borders 296 | hrules - controls printing of horizontal rules after each row. Allowed values: FRAME, ALL, NONE""" 297 | 298 | print(self.get_string(start, end, fields, header, border, hrules, sortby, reversesort)) 299 | 300 | def get_string(self, start=0, end=None, fields=None, header=True, border=True, hrules=FRAME, sortby=None, reversesort=False): 301 | 302 | """Return string representation of table in current state. 303 | 304 | Arguments: 305 | 306 | start - index of first data row to include in output 307 | end - index of last data row to include in output PLUS ONE (list slice style) 308 | fields - names of fields (columns) to include 309 | sortby - name of field to sort rows by 310 | reversesort - True or False to sort in descending or ascending order 311 | border - should be True or False to print or not print borders 312 | hrules - controls printing of horizontal rules after each row. Allowed values: FRAME, ALL, NONE""" 313 | 314 | if self.caching: 315 | key = pickle.dumps((start, end, fields, header, border, hrules, sortby, reversesort)) 316 | if key in self.cache: 317 | return self.cache[key] 318 | 319 | hrule = hrules or self.hrules 320 | bits = [] 321 | if not self.fields: 322 | return "" 323 | if not header: 324 | # Recalculate widths - avoids tables with long field names but narrow data looking odd 325 | old_widths = self.widths[:] 326 | self.widths = [0]*len(self.fields) 327 | for row in self.rows: 328 | for i in range(0,len(row)): 329 | if len(str(row[i])) > self.widths[i]: 330 | self.widths[i] = len(str(row[i])) 331 | if header: 332 | bits.append(self._stringify_header(fields, border, hrules)) 333 | elif border and hrules != NONE: 334 | bits.append(self._stringify_hrule(fields, border)) 335 | if sortby: 336 | rows = self._get_sorted_rows(start, end, sortby, reversesort) 337 | else: 338 | rows = self.rows[start:end] 339 | for row in rows: 340 | bits.append(self._stringify_row(row, fields, border, hrule)) 341 | if border and not hrule: 342 | bits.append(self._stringify_hrule(fields, border)) 343 | string = "\n".join(bits) 344 | 345 | if self.caching: 346 | self.cache[key] = string 347 | 348 | if not header: 349 | # Restore previous widths 350 | self.widths = old_widths 351 | for row in self.rows: 352 | for i in range(0,len(row)): 353 | if len(str(row[i])) > self.widths[i]: 354 | self.widths[i] = len(str(row[i])) 355 | 356 | return string 357 | 358 | def _stringify_hrule(self, fields=None, border=True): 359 | 360 | if not border: 361 | return "" 362 | lpad, rpad = self._get_paddings() 363 | padding_width = lpad+rpad 364 | bits = [self.junction_char] 365 | for field, width in zip(self.fields, self.widths): 366 | if fields and field not in fields: 367 | continue 368 | bits.append((width+padding_width)*self.horizontal_char) 369 | bits.append(self.junction_char) 370 | return "".join(bits) 371 | 372 | def _stringify_header(self, fields=None, border=True, hrules=FRAME): 373 | 374 | lpad, rpad = self._get_paddings() 375 | bits = [] 376 | if border: 377 | if hrules != NONE: 378 | bits.append(self._stringify_hrule(fields, border)) 379 | bits.append("\n") 380 | bits.append(self.vertical_char) 381 | for field, width in zip(self.fields, self.widths): 382 | if fields and field not in fields: 383 | continue 384 | bits.append(" " * lpad + field.center(width) + " " * rpad) 385 | if border: 386 | bits.append(self.vertical_char) 387 | if border and hrules != NONE: 388 | bits.append("\n") 389 | bits.append(self._stringify_hrule(fields, border)) 390 | return "".join(bits) 391 | 392 | def _stringify_row(self, row, fields=None, border=True, hrule=False): 393 | 394 | lpad, rpad = self._get_paddings() 395 | bits = [] 396 | if border: 397 | bits.append(self.vertical_char) 398 | for field, value, width, align in zip(self.fields, row, self.widths, self.aligns): 399 | if fields and field not in fields: 400 | continue 401 | if align == "l": 402 | bits.append(" " * lpad + str(value).ljust(width) + " " * rpad) 403 | elif align == "r": 404 | bits.append(" " * lpad + str(value).rjust(width) + " " * rpad) 405 | else: 406 | bits.append(" " * lpad + str(value).center(width) + " " * rpad) 407 | if border: 408 | bits.append(self.vertical_char) 409 | if border and hrule == ALL: 410 | bits.append("\n") 411 | bits.append(self._stringify_hrule(fields, border)) 412 | return "".join(bits) 413 | 414 | ############################## 415 | # HTML PRINT/STRING METHODS # 416 | ############################## 417 | 418 | def print_html(self, start=0, end=None, fields=None, sortby=None, reversesort=False, format=True, header=True, border=True, hrules=FRAME, attributes=None): 419 | 420 | """Print HTML formatted version of table in current state to stdout. 421 | 422 | Arguments: 423 | 424 | start - index of first data row to include in output 425 | end - index of last data row to include in output PLUS ONE (list slice style) 426 | fields - names of fields (columns) to include 427 | sortby - name of field to sort rows by 428 | format - should be True or False to attempt to format alignmet, padding, etc. or not 429 | header - should be True or False to print a header showing field names or not 430 | border - should be True or False to print or not print borders 431 | hrules - include horizontal rule after each row 432 | attributes - dictionary of name/value pairs to include as HTML attributes in the tag""" 433 | 434 | print(self.get_html_string(start, end, fields, sortby, reversesort, format, header, border, hrules, attributes)) 435 | 436 | def get_html_string(self, start=0, end=None, fields=None, sortby=None, reversesort=False, format=True, header=True, border=True, hrules=FRAME, attributes=None): 437 | 438 | """Return string representation of HTML formatted version of table in current state. 439 | 440 | Arguments: 441 | 442 | start - index of first data row to include in output 443 | end - index of last data row to include in output PLUS ONE (list slice style) 444 | fields - names of fields (columns) to include 445 | sortby - name of 446 | border - should be True or False to print or not print borders 447 | format - should be True or False to attempt to format alignmet, padding, etc. or not 448 | header - should be True or False to print a header showing field names or not 449 | border - should be True or False to print or not print borders 450 | hrules - include horizontal rule after each row 451 | attributes - dictionary of name/value pairs to include as HTML attributes in the
tag""" 452 | 453 | if self.caching: 454 | key = pickle.dumps((start, end, fields, format, header, border, hrules, sortby, reversesort, attributes)) 455 | if key in self.html_cache: 456 | return self.html_cache[key] 457 | 458 | if format: 459 | tmp_html_func=self._get_formatted_html_string 460 | else: 461 | tmp_html_func=self._get_simple_html_string 462 | string = tmp_html_func(start, end, fields, sortby, reversesort, header, border, hrules, attributes) 463 | 464 | if self.caching: 465 | self.html_cache[key] = string 466 | 467 | return string 468 | 469 | def _get_simple_html_string(self, start, end, fields, sortby, reversesort, header, border, hrules, attributes): 470 | 471 | bits = [] 472 | # Slow but works 473 | table_tag = '") 483 | for field in self.fields: 484 | if fields and field not in fields: 485 | continue 486 | bits.append(" " % cgi.escape(str(field))) 487 | bits.append(" ") 488 | # Data 489 | if sortby: 490 | rows = self._get_sorted_rows(stard, end, sortby, reversesort) # @UndefinedVariable 491 | else: 492 | rows = self.rows 493 | for row in self.rows: 494 | bits.append(" ") 495 | for field, datum in zip(self.fields, row): 496 | if fields and field not in fields: 497 | continue 498 | bits.append(" " % cgi.escape(str(datum))) 499 | bits.append(" ") 500 | bits.append("
%s
%s
") 501 | string = "\n".join(bits) 502 | 503 | return string 504 | 505 | def _get_formatted_html_string(self, start, end, fields, sortby, reversesort, header, border, hrules, attributes): 506 | 507 | bits = [] 508 | # Slow but works 509 | table_tag = '") 523 | for field in self.fields: 524 | if fields and field not in fields: 525 | continue 526 | bits.append(" %s" % (lpad, rpad, cgi.escape(str(field)))) 527 | bits.append(" ") 528 | # Data 529 | if sortby: 530 | rows = self._get_sorted_rows(start, end, sortby, reversesort) 531 | else: 532 | rows = self.rows 533 | for row in self.rows: 534 | bits.append(" ") 535 | for field, align, datum in zip(self.fields, self.aligns, row): 536 | if fields and field not in fields: 537 | continue 538 | if align == "l": 539 | bits.append(" %s" % (lpad, rpad, cgi.escape(str(datum)))) 540 | elif align == "r": 541 | bits.append(" %s" % (lpad, rpad, cgi.escape(str(datum)))) 542 | else: 543 | bits.append(" %s" % (lpad, rpad, cgi.escape(str(datum)))) 544 | bits.append(" ") 545 | bits.append("") 546 | string = "\n".join(bits) 547 | 548 | return string 549 | 550 | def main(): 551 | 552 | x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) 553 | x.set_field_align("City name", "l") # Left align city names 554 | x.add_row(["Adelaide",1295, 1158259, 600.5]) 555 | x.add_row(["Brisbane",5905, 1857594, 1146.4]) 556 | x.add_row(["Darwin", 112, 120900, 1714.7]) 557 | x.add_row(["Hobart", 1357, 205556, 619.5]) 558 | x.add_row(["Sydney", 2058, 4336374, 1214.8]) 559 | x.add_row(["Melbourne", 1566, 3806092, 646.9]) 560 | x.add_row(["Perth", 5386, 1554769, 869.4]) 561 | print(x) 562 | 563 | if len(sys.argv) > 1 and sys.argv[1] == "test": 564 | 565 | # This "test suite" is hideous and provides poor, arbitrary coverage. 566 | # I'll replace it with some proper unit tests Sometime Soon (TM). 567 | # Promise. 568 | print("Testing field subset selection:") 569 | x.printt(fields=["City name","Population"]) 570 | print("Testing row subset selection:") 571 | x.printt(start=2, end=5) 572 | print("Testing hrules settings:") 573 | print("FRAME:") 574 | x.printt(hrules=FRAME) 575 | print("ALL:") 576 | x.printt(hrules=ALL) 577 | print("NONE:") 578 | x.printt(hrules=NONE) 579 | print("Testing lack of headers:") 580 | x.printt(header=False) 581 | x.printt(header=False, border=False) 582 | print("Testing lack of borders:") 583 | x.printt(border=False) 584 | print("Testing sorting:") 585 | x.printt(sortby="City name") 586 | x.printt(sortby="Annual Rainfall") 587 | x.printt(sortby="Annual Rainfall", reversesort=True) 588 | print("Testing padding parameter:") 589 | x.set_padding_width(0) 590 | x.printt() 591 | x.set_padding_width(5) 592 | x.printt() 593 | x.set_left_padding(5) 594 | x.set_right_padding(0) 595 | x.printt() 596 | x.set_right_padding(20) 597 | x.printt() 598 | x.set_left_padding(None) 599 | x.set_right_padding(None) 600 | x.set_padding_width(2) 601 | print("Testing changing characters") 602 | x.set_border_chars("*","*","*") 603 | x.printt() 604 | x.set_border_chars("!","~","o") 605 | x.printt() 606 | x.set_border_chars("|","-","+") 607 | print("Testing everything at once:") 608 | x.printt(start=2, end=5, fields=["City name","Population"], border=False, hrules=True) 609 | print("Rebuilding by columns:") 610 | x = PrettyTable() 611 | x.add_column("City name", ["Adelaide", "Brisbane", "Darwin", "Hobart", "Sydney", "Melbourne", "Perth"]) 612 | x.add_column("Area", [1295, 5905, 112, 1357, 2058, 1566, 5385]) 613 | x.add_column("Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092, 1554769]) 614 | x.add_column("Annual Rainfall", [600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 869.4]) 615 | x.printt() 616 | print("Testing HTML:") 617 | x.print_html() 618 | x.print_html(border=False) 619 | x.print_html(border=True) 620 | x.print_html(format=False) 621 | x.print_html(attributes={"name": "table", "id": "table"}) 622 | 623 | if __name__ == "__main__": 624 | main() 625 | 626 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | 663 | -------------------------------------------------------------------------------- /src/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # GPFS Current Activity Monitor 4 | # Run with -h to print help and allowable arguments. 5 | # See params.py for more customizations. 6 | 7 | import argparse, collections, curses, datetime, functools, inspect 8 | import itertools, locale, logging, signal, subprocess, sys, threading, time 9 | 10 | # Local imports 11 | import common, errors, params 12 | from prettytable import PrettyTable 13 | from numsort import numsorted # Uses "@functools.lru_cache(maxsize=None)" 14 | 15 | class ArgParser(argparse.ArgumentParser): 16 | """Parse and store input arguments. Arguments on the command line override 17 | those in the parameters file.""" 18 | 19 | def __init__(self): 20 | 21 | epilog = "Pressing the '{}' key pauses or resumes the display.".format( 22 | params.DISPLAY_PAUSE_KEY) 23 | 24 | super().__init__(description=params._PROGRAM_NAME, epilog=epilog, 25 | prog=params._PROGRAM_NAME_SHORT) 26 | 27 | self._add_misc_args() 28 | self._add_logging_args() 29 | 30 | self._args = self.parse_args() 31 | 32 | self._store_misc_args() 33 | self._store_logging_args() 34 | 35 | def _add_misc_args(self): 36 | """Add miscellaneous arguments to parser.""" 37 | 38 | self.add_argument('-hn', default=params.MMPMON_HOST, 39 | help='GPFS node name on which to run mmpmon ' 40 | '(requires automated SSH login if not ' 41 | 'localhost) (currently: %(default)s)') 42 | 43 | self.add_argument('-n', type=float, 44 | default=params.MONITORING_INTERVAL_SECS, 45 | help='Refresh interval in seconds (%(type)s >=1) ' 46 | '(currently: %(default)s)') 47 | 48 | nodeset = params.GPFS_NODESET or '(first available)' 49 | self.add_argument('-ns', default=params.GPFS_NODESET, 50 | help='GPFS nodeset (currently: {})'.format(nodeset)) 51 | 52 | self.add_argument('-t', default=params.TABLE_TYPE, choices=('s', 'i'), 53 | help="Table type ('s'eparated or 'i'nterlaced) " 54 | '(currently: %(default)s)') 55 | 56 | def _add_logging_args(self): 57 | """Add logging arguments to parser.""" 58 | 59 | arg_group = self.add_argument_group(title='Diagnostic logging arguments') 60 | 61 | logging_status = 'enabled' if params.LOG_FILE_WRITE else 'disabled' 62 | arg_group.add_argument('-l', action='store_true', 63 | default=params.LOG_FILE_WRITE, 64 | help='Enable logging to file ' 65 | '(currently: {})'.format(logging_status)) 66 | 67 | arg_group.add_argument('-lf', default=params.LOG_FILE_PATH, 68 | help='Log file path (if logging is enabled) ' 69 | "(currently: '%(default)s')") 70 | # type=argparse.FileType('w') is not specified because its value is 71 | # automatically touched as a file. This is undesirable if -l is not 72 | # specified, etc. 73 | 74 | arg_group.add_argument('-ll', default=params.LOG_LEVEL, 75 | choices=('i', 'd'), 76 | help='Log level (if logging is enabled) ' 77 | "('i'nfo or 'd'ebug) " 78 | '(currently: %(default)s)') 79 | 80 | def _store_misc_args(self): 81 | """Store parsed miscellaneous arguments.""" 82 | 83 | params.MMPMON_HOST = self._args.hn 84 | params.MONITORING_INTERVAL_SECS = max(self._args.n, 1) 85 | params.GPFS_NODESET = self._args.ns 86 | 87 | if self._args.t == 's': params.TABLE_TYPE = 'separated' 88 | elif self._args.t == 'i': params.TABLE_TYPE = 'interlaced' 89 | 90 | def _store_logging_args(self): 91 | """Store parsed logging arguments.""" 92 | 93 | params.LOG_FILE_WRITE = self._args.l 94 | params.LOG_FILE_PATH = self._args.lf 95 | 96 | if self._args.ll == 'i': params.LOG_LEVEL = 'info' 97 | elif self._args.ll == 'd': params.LOG_LEVEL = 'debug' 98 | 99 | 100 | class DiagnosticLoggerSetup: 101 | """Set up a logger to which diagnostic messages can be logged.""" 102 | 103 | def __init__(self): 104 | 105 | self.logger = logging.getLogger(params._PROGRAM_NAME_SHORT) 106 | self._configure() 107 | 108 | if params.LOG_FILE_WRITE: 109 | self._log_basics() 110 | self._log_params() 111 | 112 | def _configure(self): 113 | """Configure the logger with a level and a formatted handler.""" 114 | 115 | if params.LOG_FILE_WRITE: 116 | 117 | # Set level 118 | level = getattr(logging, params.LOG_LEVEL.upper()) 119 | self.logger.setLevel(level) 120 | 121 | # Create formatter 122 | attributes = ('asctime', 'levelname', 'module', 'lineno', 123 | 'threadName', 'message') 124 | attributes = ['%({})s'.format(a) for a in attributes] 125 | attributes.insert(0, '') 126 | format_ = '::'.join(attributes) 127 | formatter = logging.Formatter(format_) 128 | 129 | # Add handler 130 | handler = logging.FileHandler(params.LOG_FILE_PATH, mode='w') 131 | handler.setFormatter(formatter) 132 | 133 | else: 134 | handler = logging.NullHandler 135 | 136 | self.logger.addHandler(handler) 137 | 138 | def _log_basics(self): 139 | """Retrieve and log basics about the operating system, environment, 140 | platform, program input arguments, and the Python installation in 141 | use.""" 142 | 143 | import os, platform, sys #@UnusedImport @Reimport 144 | 145 | items = ('os.name', 146 | 'os.getcwd()', 147 | 'os.ctermid()', 148 | 'os.getlogin()', 149 | "os.getenv('USER')", 150 | "os.getenv('DISPLAY')", 151 | "os.getenv('LANG')", 152 | "os.getenv('TERM')", 153 | "os.getenv('SHELL')", 154 | "os.getenv('HOSTNAME')", 155 | "os.getenv('PWD')", 156 | 'os.uname()', 157 | 158 | 'platform.architecture()', 159 | 'platform.machine()', 160 | 'platform.node()', 161 | 'platform.platform()', 162 | 'platform.processor()', 163 | 'platform.python_build()', 164 | 'platform.python_compiler()', 165 | 'platform.python_implementation()', 166 | 'platform.python_revision()', 167 | 'platform.python_version_tuple()', 168 | 'platform.release()', 169 | 'platform.system()', 170 | 'platform.version()', 171 | 'platform.uname()', 172 | 'platform.dist()', 173 | 174 | 'sys.argv', 175 | 'sys.executable', 176 | 'sys.flags', 177 | 'sys.path', 178 | 'sys.platform', 179 | 'sys.version', 180 | 'sys.version_info', 181 | ) 182 | 183 | # Run above-mentioned code and log the respective outputs 184 | for source in items: 185 | value = str(eval(source)).replace('\n', ' ') 186 | message = '{}::{}'.format(source, value) 187 | self.logger.info(message) 188 | 189 | def _log_params(self): 190 | """Log the names and values of all parameters.""" 191 | 192 | for item in dir(params): 193 | if (not item.startswith('__')) and (item == item.upper()): 194 | value = str(getattr(params, item)).replace('\n', ' ') 195 | message = 'params.{}::{}'.format(item, value) 196 | self.logger.info(message) 197 | 198 | 199 | class Logger: 200 | """ 201 | Provide a base class to provision logging functionality. 202 | 203 | Instances of derived classes can log messages using methods self.logger and 204 | self.logvar. 205 | """ 206 | 207 | logger = logging.getLogger(params._PROGRAM_NAME_SHORT) 208 | 209 | def logvar(self, var_str, level='info'): 210 | """Log the provided variable's access string and value, and also its 211 | class and method names at the optionally indicated log level. 212 | 213 | The variable can be a local variable. Alternatively, if accessed using 214 | the 'self.' prefix, it can be a class instance variable or otherwise a 215 | class variable. 216 | """ 217 | 218 | # Inspect the stack 219 | stack = inspect.stack() 220 | try: 221 | 222 | # Obtain class and method names 223 | class_name = stack[1][0].f_locals['self'].__class__.__name__ 224 | method_name = stack[1][3] 225 | 226 | # Obtain variable value 227 | if not var_str.startswith('self.'): 228 | # Assuming local variable 229 | var_val = stack[1][0].f_locals[var_str] 230 | else: 231 | var_name = var_str[5:] # len('self.') = 5 232 | try: 233 | # Assuming class instance variable 234 | var_val = stack[1][0].f_locals['self'].__dict__[var_name] 235 | except KeyError: 236 | # Assuming class variable 237 | var_val = (stack[1][0].f_locals['self'].__class__.__dict__ 238 | [var_name]) 239 | 240 | finally: 241 | del stack # Recommended. 242 | # See http://docs.python.org/py3k/library/inspect.html#the-interpreter-stack 243 | 244 | # Format and log the message 245 | message = '{}.{}::{}::{}'.format(class_name, method_name, var_str, 246 | var_val) 247 | level = getattr(logging, level.upper()) 248 | self.logger.log(level, message) 249 | 250 | 251 | class Receiver(Logger): 252 | """Return an iterable containing mmpmon fs_io_s recordset containing 253 | records for all responding nodes and file systems.""" 254 | 255 | def __iter__(self): 256 | return self._fsios_record_group_objectifier() 257 | 258 | def close(self): 259 | """ 260 | Close the subprocess providing data to the iterator. 261 | 262 | This must be used if an unhandled exception occurs. 263 | """ 264 | try: self._mmpmon_subprocess.terminate() 265 | except AttributeError: pass 266 | 267 | @staticmethod 268 | def _process_cmd_args(cmd_args): 269 | """Return command line arguments conditionally modified to run on 270 | remote host.""" 271 | 272 | if params.MMPMON_HOST not in ('localhost', 'localhost.localdomain', 273 | '127.0.0.1'): 274 | cmd_args = params.SSH_ARGS + [params.MMPMON_HOST] + cmd_args 275 | return cmd_args 276 | 277 | @property 278 | def node_seq(self): 279 | """Return a sequence of strings with names of all GPFS nodes in the 280 | specified nodeset.""" 281 | 282 | try: 283 | return self._node_seq 284 | except AttributeError: 285 | 286 | cmd_args = [r'/usr/lpp/mmfs/bin/mmlsnode'] 287 | cmd_args = self._process_cmd_args(cmd_args) 288 | self.logvar('cmd_args') 289 | 290 | try: 291 | output = subprocess.check_output(cmd_args) 292 | except (OSError, subprocess.CalledProcessError) as exception: 293 | # OSError example: 294 | # [Errno 2] No such file or directory: 295 | # '/usr/lpp/mmfs/bin/mmlsnode' 296 | # subprocess.CalledProcessError example: 297 | # Command '['ssh', '-o', 'BatchMode=yes', '-o', 298 | # 'ConnectTimeout=4', 'invalidhost', 299 | # '/usr/lpp/mmfs/bin/mmlsnode']' returned non-zero exit 300 | # status 255 301 | raise errors.SubprocessError(str(exception)) 302 | output = output.split(b'\n')[2:-1] 303 | 304 | # Extract node names for relevant nodeset only 305 | for line in output: 306 | line = line.decode() 307 | node_set, node_seq = line.split(None, 1) 308 | 309 | if ((not params.GPFS_NODESET) or 310 | (node_set == params.GPFS_NODESET)): 311 | 312 | node_seq = node_seq.split() 313 | node_seq.sort() # possibly useful if viewing logs 314 | 315 | self._node_seq = node_seq 316 | return self._node_seq 317 | else: 318 | if params.GPFS_NODESET: 319 | err = '{} is not a valid nodeset per mmlsnode'.format( 320 | params.GPFS_NODESET) 321 | else: 322 | err = 'no nodeset could be found using mmlsnode' 323 | raise errors.ArgumentError(err) 324 | 325 | @property 326 | def num_node(self): 327 | """Return the number of GPFS nodes in the specified nodeset.""" 328 | 329 | try: 330 | return self._num_node 331 | except AttributeError: 332 | if not params.DEBUG_MODE: 333 | self._num_node = len(self.node_seq) 334 | else: 335 | self._num_node = len(params.DEBUG_NODES) 336 | return self._num_node 337 | 338 | def _mmpmon_caller(self): 339 | """Run and prepare the mmpmon subprocess to output data.""" 340 | 341 | # Determine input arguments 342 | delay = str(int(params.MONITORING_INTERVAL_SECS * 1000)) 343 | # int above removes decimals 344 | runs = '0' if not params.DEBUG_MODE else str(params.DEBUG_MMPMON_RUNS) 345 | 346 | # Determine mmpmon command 347 | cmd_args = [r'/usr/lpp/mmfs/bin/mmpmon', '-p', '-s', '-r', runs, 348 | '-d', delay] 349 | cmd_args = self._process_cmd_args(cmd_args) 350 | self.logvar('cmd_args') 351 | 352 | # Determine input commands to mmpmon process 353 | 354 | node_seq = params.DEBUG_NODES if params.DEBUG_MODE else self.node_seq 355 | for node in node_seq: self.logvar('node') #@UnusedVariable 356 | 357 | mmpmon_inputs = ('nlist add {}'.format(node) for node in node_seq) 358 | # While multiple nodes can be added using the same nlist command, 359 | # this apparently restricts the number of nodes added to 98 per 360 | # nlist command. Due to this restriction, only one node is added 361 | # per command instead. 362 | mmpmon_inputs = itertools.chain(mmpmon_inputs, ('fs_io_s',)) 363 | 364 | # Call subprocess, and provide it with relevant commands 365 | self._mmpmon_subprocess = subprocess.Popen(cmd_args, 366 | bufsize=-1, 367 | stdin=subprocess.PIPE, 368 | stdout=subprocess.PIPE, 369 | stderr=subprocess.STDOUT) 370 | for mmpmon_input in mmpmon_inputs: 371 | mmpmon_input = mmpmon_input.encode() + b'\n' 372 | self.logvar('mmpmon_input', 'debug') 373 | self._mmpmon_subprocess.stdin.write(mmpmon_input) 374 | self._mmpmon_subprocess.stdin.close() # this also does flush() 375 | 376 | def _mmpmon_stdout_processor(self): 377 | """Yield lines of text returned by mmpmon.""" 378 | 379 | self._mmpmon_caller() 380 | 381 | # Handle possible known error message 382 | line = next(self._mmpmon_subprocess.stdout); 383 | line = self._mmpmon_line_processor(line) 384 | if line == 'Could not establish connection to file system daemon.': 385 | err_msg = ('Only a limited number of mmpmon processes can be run ' 386 | 'simultaneously on a host. Kill running instances of ' 387 | 'this application that are no longer needed. Also kill ' 388 | 'unnecessary existing mmpmon processes on MMPMON_HOST, ' 389 | 'i.e. {}.').format(params.MMPMON_HOST) 390 | # A max of 5 mmpmon processes were observed to run simultaneously 391 | # on a host. 392 | raise errors.SubprocessError(err_msg) 393 | 394 | # Yield mmpmon output 395 | yield line # (obtained earlier) 396 | for line in self._mmpmon_subprocess.stdout: 397 | yield self._mmpmon_line_processor(line) 398 | 399 | def _mmpmon_line_processor(self, line): 400 | """Return a formatted version of a line returned by mmpmon, so it can 401 | be used for further processing.""" 402 | 403 | line = line.decode().rstrip() 404 | 405 | if params.LOG_FILE_WRITE and \ 406 | (self.logger.getEffectiveLevel() <= logging.DEBUG) and \ 407 | params.LOG_NUM_MMPMON_LINES: 408 | # Note: It is uncertain whether grouping the above conditions into 409 | # a single tuple will result in short-circuit evaluation. 410 | 411 | params.LOG_NUM_MMPMON_LINES -= 1 412 | self.logvar('line', 'debug') # CPU and disk intensive 413 | 414 | # else: 415 | # # Simplify method definition to avoid the now unnecessary check 416 | # self._mmpmon_line_processor = lambda line: line.decode().rstrip() 417 | 418 | return line 419 | 420 | def _record_processor(self): 421 | """Yield dicts corresponding to lines returned by mmpmon.""" 422 | 423 | for record in self._mmpmon_stdout_processor(): 424 | record = record.split() 425 | 426 | type_ = record[0][1:-1] 427 | properties = {k[1:-1]: v for k, v in common.grouper(2, record[1:])} 428 | 429 | record = {'type':type_, 'properties':properties} 430 | yield record 431 | 432 | def _fsios_record_filter(self): 433 | """Yield only fs_io_s records along with their group number.""" 434 | 435 | # Yield records with their group number 436 | counter = itertools.count(start=1) 437 | for r in self._record_processor(): 438 | if (r['type'] == 'fs_io_s' and r['properties']['rc'] == '0'): 439 | r['properties']['gn'] = count #@UndefinedVariable 440 | yield r['properties'] 441 | elif (r['type'] == 'nlist' and 'c' in r['properties']): 442 | count = next(counter) #@UnusedVariable 443 | 444 | def _fsios_record_objectifier(self): 445 | """Yield fs_io_s record dicts as Record objects.""" 446 | 447 | return (Record(record) for record in self._fsios_record_filter()) 448 | 449 | def _fsios_record_grouper(self): 450 | """Yield fs_io_s records grouped into a sequence based on their 451 | creation time. 452 | """ 453 | 454 | # Group records that were created approximately simultaneously, i.e. 455 | # with the same group number 456 | record_group_iterator = itertools.groupby( 457 | self._fsios_record_objectifier(), 458 | lambda r: r.gn) 459 | 460 | # Sort records in each group, and yield groups 461 | for _, record_group in record_group_iterator: # _ = record_group_num 462 | 463 | record_group = list(record_group) 464 | # converting from iterator to list, to allow list to be sorted 465 | # later. 466 | for i in range(len(record_group)): del record_group[i].gn 467 | record_group.sort(key = lambda r: (r.nn, r.fs)) 468 | # sorting to allow further grouping by nn 469 | # "lambda r: operator.itemgetter('nn', 'fs')(r)" 470 | # may work alternatively 471 | 472 | yield record_group 473 | 474 | def _fsios_record_group_objectifier(self): 475 | """Yield fs_io_s record group sequences as RecordGroup objects.""" 476 | 477 | return (RecordGroup(record_group) for record_group in 478 | self._fsios_record_grouper()) 479 | 480 | class Record: 481 | """Return a record object with attributes 482 | fs, gn, nn, ts, fs, br, bw, brw. 483 | """ 484 | 485 | _filter_in_keys = {'gn', 'nn', 't', 'tu', 'fs', 'br', 'bw'} 486 | _non_int_keys = {'gn', 'nn', 'fs'} 487 | 488 | def __getitem__(self, key): 489 | return getattr(self, key) 490 | 491 | def __setitem__(self, key, value): 492 | setattr(self, key, value) 493 | 494 | def __str__(self): 495 | return str(self.__dict__) 496 | 497 | def __init__(self, fsios_dict): 498 | 499 | fsios_dict = self._process(fsios_dict) 500 | self.__dict__.update(fsios_dict) 501 | 502 | def _process(self, dict_): 503 | """Return the processed record dict.""" 504 | 505 | # Filter out keys that are not needed 506 | dict_ = {key : dict_[key] for key in self._filter_in_keys} 507 | 508 | # Convert integer values from str to int 509 | for key in dict_: 510 | if key not in self._non_int_keys: 511 | dict_[key] = int(dict_[key]) 512 | 513 | # Combine seconds and microseconds 514 | dict_['ts'] = dict_['t'] + dict_['tu']/1000000 # ts = timestamp 515 | for key in ['t', 'tu']: del dict_[key] 516 | 517 | # Calculate sum of bytes read and bytes written 518 | dict_['brw'] = dict_['br'] + dict_['bw'] 519 | 520 | return dict_ 521 | 522 | def __sub__(self, older): # self is newer 523 | return RecordDelta(self, older) 524 | 525 | 526 | class RecordDelta(Record): 527 | """Return a record delta object computed from two successive records. 528 | Included attributes are fs, nn, ts, td, br, bw, brw, brps, bwps, brwps. 529 | """ 530 | 531 | # Inheriting from Record allows its functions __getitem__, __setitem__ and 532 | # __str__ to be used. 533 | 534 | def __init__(self, new, old): 535 | 536 | assert new.fs == old.fs and new.nn == old.nn 537 | 538 | # Set identifying attribute values 539 | for attr in ('fs', 'nn', 'ts'): 540 | self[attr] = new[attr] 541 | 542 | self._compute_deltas_and_speeds(new, old) 543 | 544 | def _compute_deltas_and_speeds(self, new, old): 545 | """Compute transfer deltas and speeds.""" 546 | 547 | self.td = new.ts - old.ts # td = time delta 548 | 549 | for attr in ('br', 'bw', 'brw'): 550 | 551 | self[attr] = (new[attr] - old[attr]) % 18446744073709551615 552 | # 18446744073709551615 == (2**64 - 1) 553 | self[attr + 'ps'] = self[attr] / self.td 554 | # (speed is in bytes per second) 555 | 556 | #delattr(self, attr) 557 | # If the above delattr line is uncommented, then 558 | # RecordGroupDelta._lev2_summary_stat_types should not contain 559 | # br, bw, brw. 560 | 561 | 562 | class RecordGroup: 563 | """Return a record group object from a sequence of Record objects. Stats 564 | are available as attributes recs, lev1_summary_stats, and 565 | lev2_summary_stats. Timestamp is available as attribute timestamp. 566 | """ 567 | 568 | _count = 0 569 | _lev1_summary_stat_types = ('nn', 'fs') # (totals) 570 | _lev2_summary_stat_types = ('br', 'bw', 'brw') # (grand totals) 571 | 572 | def count(self): 573 | """Increment class instance count.""" 574 | 575 | self.__class__._count += 1 576 | self._count = self.__class__._count # (makes copy as is desired) 577 | 578 | def __init__(self, recs): 579 | 580 | self.count() 581 | 582 | self.recs = recs 583 | self.timestamp = max((datetime.datetime.fromtimestamp(rec.ts) for 584 | rec in self.recs)) 585 | #self.compute_summary_stats() 586 | # not necessary, except for debugging these values 587 | 588 | def rec_select(self, nn, fs): 589 | """Return the record for the given node name and file system. None is 590 | returned if the record is not found. Note that iterating over records 591 | using this approach approximately has a complexity of O(n**2). 592 | """ 593 | 594 | for rec in self.recs: 595 | if nn == rec.nn and fs == rec.fs: 596 | return rec 597 | 598 | def compute_summary_stats(self): 599 | """Compute summary stats for records, and store them in 600 | self.lev1_summary_stats and self.lev2_summary_stats.""" 601 | 602 | self.lev1_summary_stats = {} 603 | self.lev2_summary_stats = {} 604 | 605 | # Compute level 1 summary stats 606 | for lev1_stattype in self._lev1_summary_stat_types: 607 | seq = [rec[lev1_stattype] for rec in self.recs] 608 | self._compute_lev1_summary_stats(lev1_stattype, seq) 609 | 610 | # Compute level 2 summary stats 611 | for lev2_stattype in self._lev2_summary_stat_types: 612 | self.lev2_summary_stats[lev2_stattype] = sum(rec[lev2_stattype] for 613 | rec in self.recs) 614 | 615 | def _compute_lev1_summary_stats(self, lev1_stattype, seq): 616 | """Compute level 1 summary stats, grouped by items in 617 | self._lev1_summary_stat_types. 618 | """ 619 | 620 | self.lev1_summary_stats[lev1_stattype] = {} 621 | for i in seq: 622 | 623 | curr_summary_stats = {j:0 for j in self._lev2_summary_stat_types} 624 | 625 | for rec in self.recs: # can possibly use itertools for efficiency 626 | 627 | if i == rec[lev1_stattype]: 628 | for stat in curr_summary_stats.keys(): 629 | curr_summary_stats[stat] += rec[stat] 630 | 631 | self.lev1_summary_stats[lev1_stattype][i] = curr_summary_stats 632 | 633 | @staticmethod 634 | def _sso(seq, tabs=0): 635 | """Return an informal String representation for the given Sequence of 636 | Objects. 637 | """ 638 | 639 | tabs = '\t' * tabs 640 | if isinstance(seq, dict): seq = sorted(seq.items()) 641 | strs = ('\n{}{}'.format(tabs, obj) for obj in seq) 642 | str_ = ''.join(strs) 643 | return str_ 644 | 645 | def __str__(self): 646 | 647 | str_ = '{} (#{}) (as of {}):\n'.format(self.__class__.__name__, 648 | self._count, self.timestamp) 649 | 650 | # Try storing string for summary stats 651 | sss = lambda k: '\t\tSummarized by {}:{}'.format(k, 652 | self._sso(self.lev1_summary_stats[k], 3)) 653 | try: 654 | lev1_summary_stats = (sss(k) for k in self.lev1_summary_stats) 655 | lev1_summary_stats_str = '\n'.join(lev1_summary_stats) 656 | str_ += '\tSummarized record stats:\n{}{}\n'.format( 657 | lev1_summary_stats_str, 658 | self._sso((self.lev2_summary_stats,), 2)) 659 | except AttributeError: 660 | pass 661 | 662 | # Store string for individual stats 663 | str_ += '\tIndividual record stats:{}'.format(self._sso(self.recs, 2)) 664 | 665 | return str_ 666 | 667 | def __sub__(self, older): # self is newer 668 | return RecordGroupDelta(self, older) 669 | 670 | 671 | class RecordGroupDelta(RecordGroup): 672 | """Return a record delta object computed from two successive record groups. 673 | Stats are available as attributes recs, lev1_summary_stats, and 674 | lev2_summary_stats. Timestamp is available as attribute timestamp. Time 675 | duration in seconds of the delta is available as attribute 676 | time_duration_secs. 677 | """ 678 | 679 | _count = 0 680 | _lev2_summary_stat_types = ('br', 'bw', 'brw', 'brps', 'bwps', 'brwps') 681 | # (grand totals) 682 | _table_types = collections.OrderedDict(( 683 | #('brwps', {'label': 'Read+Write', 'label_short': 'R+W'}), 684 | # brwps is disabled as it takes up valuable screen space 685 | ('brps', {'label': 'Read', 'label_short': 'R'}), 686 | ('bwps', {'label': 'Write', 'label_short': 'W'}), 687 | )) 688 | 689 | # Inheriting from RecordGroup allows its functions compute_summary_stats 690 | # __str__, etc. to be used. 691 | 692 | def __init__(self, new, old): 693 | 694 | self.count() 695 | 696 | self.timestamp = new.timestamp 697 | 698 | self.time_duration_secs = new.timestamp - old.timestamp 699 | self.time_duration_secs = self.time_duration_secs.total_seconds() 700 | 701 | self._compute_recs_deltas(new, old) 702 | self.compute_summary_stats() 703 | 704 | def _compute_recs_deltas(self, new, old): 705 | """Compute deltas (differences) of new and old records, and store them 706 | in self.recs. 707 | """ 708 | 709 | self.recs = [] # seq of RecordDelta objects, once populated 710 | 711 | # Compute deltas 712 | # (very inefficient, but unoptimizable as long as recs is a seq, and 713 | # not say an efficiently accessible multi-level dict instead) 714 | for rec_new in new.recs: 715 | for rec_old in old.recs: 716 | if rec_new.fs == rec_old.fs and rec_new.nn == rec_old.nn: 717 | rec = rec_new - rec_old 718 | self.recs.append(rec) 719 | break 720 | 721 | @staticmethod 722 | def _bytes_str(num_bytes): 723 | """Return a human readable string representation of the provided number 724 | of bytes. Bytes can be an int or a float or None. Powers of 2 are used. 725 | As such, the units used are binary, and not SI. To save a character, 726 | numbers from 1000 to 1023 are transformed to the next largest unit. 727 | 728 | Examples: 256 --> ' 256.0 ', 1012 --> '1.0K ', 1450 --> ' 1.4K', 729 | 99**99 --> '3.7e+197', None --> ' N/A ' 730 | """ 731 | 732 | # To disable thousands-character-saving, increase width by 1, and 733 | # comment out str len test section. 734 | 735 | # Note that table field headers are hard-coded to have at least the 736 | # same output length as the general output of this function. 737 | 738 | width = 5 # output length is this + 1 for unit 739 | 740 | if num_bytes != None: 741 | 742 | units = (' ', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') 743 | num_bytes_original = num_bytes 744 | 745 | for unit_index, unit in enumerate(units): 746 | if num_bytes < 1024: 747 | if len('{:.1f}'.format(num_bytes)) > width: 748 | # The above condition holds True when num_bytes is 749 | # approximately > 999.94. If num_bytes is always an int, it 750 | # could more simply be ">= 1000". 751 | try: 752 | num_bytes /= 1024 753 | # is always actually less than 1.0, but 754 | # formats as 1.0 with {:.1f} 755 | except OverflowError: 756 | break # num_bytes must be too large 757 | try: unit = units[unit_index + 1] 758 | except IndexError: # units are exhausted 759 | break 760 | str_ = '{:{}.1f}{}'.format(num_bytes, width, unit) 761 | # this is always 6 characters 762 | return str_ 763 | try: num_bytes /= 1024 764 | except OverflowError: break 765 | 766 | try: 767 | # Fall back to scientific notation. 768 | str_ = '{:{}.1e}'.format(num_bytes_original, width) 769 | return str_ 770 | except OverflowError: 771 | # Fall back to basic string representation. 772 | str_ = str(num_bytes_original) 773 | return str_ 774 | # String length can be greater than normal for very large numbers. 775 | 776 | else: 777 | # num_bytes == None 778 | return '{:^{}}'.format('N/A', width + 1) 779 | 780 | @staticmethod 781 | @functools.lru_cache(maxsize=None) 782 | def _mmfa_ipf(num_avail_shares, demands): 783 | """Return the sequence of shares corresponding to the provided number 784 | of available shares and the sequence of demands. Max-min fair 785 | allocation, implemented by an incremental progressive filling algorithm 786 | is used. Note that the implemented algorithm is not entirely efficient 787 | due to its incremental filling nature. 788 | 789 | num_avail_shares should be a non-negative int. 790 | 791 | demands should be a hashable sequence (such as a tuple, and not a list) 792 | of non-negative ints. 793 | 794 | Results are cached in memory. 795 | """ 796 | 797 | demands, indexes = list(zip(*sorted(zip(demands, range(len(demands))), 798 | reverse=True))) 799 | # This sorts 'demands' and get indexes. 800 | # indexes, demands = list(zip(*sorted(enumerate(demands), 801 | # key=operator.itemgetter(1), 802 | # reverse=True))) 803 | # # alternative technique for above 804 | # Note that 'reverse' above can be set equal to False for any specific 805 | # applications that require it. 806 | demands = list(demands) 807 | indexes = sorted(range(len(indexes)), key=lambda k: indexes[k]) 808 | # This transform indexes to make them useful later for restoring 809 | # the original order. 810 | 811 | len_ = len(demands) 812 | shares = [0] * len_ 813 | 814 | i = 0 815 | while num_avail_shares and any(demands): 816 | if demands[i]: 817 | num_avail_shares -= 1 818 | demands[i] -= 1 819 | shares[i] += 1 820 | i = (i + 1) % len_ 821 | 822 | shares = tuple(shares[k] for k in indexes) 823 | return shares 824 | 825 | def tables_str(self, format_, num_avail_lines=80): 826 | """Return a string representation of the table types previously 827 | specified in self.__class__._table_types. The representation is of the 828 | specified format, which can be either separated or interlaced. Inactive 829 | nodes are not included. 830 | """ 831 | 832 | method_name = '_tables_{}_str'.format(format_) 833 | return getattr(self, method_name)(num_avail_lines) 834 | 835 | def _tables_separated_str(self, num_avail_lines): 836 | """Return a separated string representation of the table types 837 | previously specified in self.__class__._table_types. Inactive nodes are 838 | not included. 839 | """ 840 | 841 | # Determine file systems used 842 | fs_seq = numsorted(tuple(self.lev1_summary_stats['fs'])) 843 | # tuple results in a hashable object which is required 844 | table_fields = (['Node', 'Total'] + 845 | ['{:>6}'.format(fs) for fs in fs_seq]) 846 | # 6 is the general len of a str returned by 847 | # self._bytes_str 848 | 849 | def nn_active_names_and_lens(): 850 | """Return active node name sequences and their lengths for all 851 | table types. The returned items are dicts. 852 | """ 853 | 854 | nn_seq = {} 855 | # Keys and values will be table types and respective node 856 | # names. 857 | nn_seq_len = {} 858 | # A key is a tuple containing 859 | # (table_type, 'displayed' or 'active'). The value is the 860 | # respective nn_seq len. 861 | 862 | for table_type in self._table_types: 863 | nn_seq_cur = [nn for nn, nn_summary_stats in 864 | self.lev1_summary_stats['nn'].items() if 865 | nn_summary_stats[table_type] > 0] 866 | #nn_seq_cur.sort() 867 | sort_key = (lambda nn: 868 | self.lev1_summary_stats['nn'][nn][table_type]) 869 | nn_seq_cur.sort(key = sort_key, reverse = True) 870 | nn_seq_len[table_type, 'active'] = len(nn_seq_cur) 871 | nn_seq[table_type] = nn_seq_cur 872 | 873 | return nn_seq, nn_seq_len 874 | 875 | nn_seq, nn_seq_len = nn_active_names_and_lens() 876 | 877 | def num_avail_lines_per_table(num_avail_lines, nn_seq): 878 | """Return a sequence containing the number of available lines for 879 | node name sequences of tables. 880 | """ 881 | num_avail_lines -= (len(self._table_types) * 7) 882 | # 7 is the num of lines cumulatively used by headers, totals 883 | # row, and footers of each table 884 | num_avail_lines = max(num_avail_lines, 0) 885 | lines_reqd_seq = (len(nn_seq[table_type]) for table_type in 886 | self._table_types) 887 | lines_reqd_seq = tuple(lines_reqd_seq) 888 | lines_avail_seq = self._mmfa_ipf(num_avail_lines, lines_reqd_seq) 889 | return lines_avail_seq 890 | 891 | lines_avail_seq = num_avail_lines_per_table(num_avail_lines, nn_seq) 892 | 893 | def nn_displayed_names_and_lens(nn_seq, nn_seq_len, lines_avail_seq): 894 | """Return displayed node name sequences and their lengths for all 895 | table types. The returned items are updated dicts. 896 | """ 897 | 898 | for table_type, lines_avail in zip(self._table_types, 899 | lines_avail_seq): 900 | nn_seq[table_type] = nn_seq[table_type][:lines_avail] 901 | nn_seq_len[table_type, 'displayed'] = len(nn_seq[table_type]) 902 | 903 | return nn_seq, nn_seq_len 904 | 905 | nn_seq, nn_seq_len = nn_displayed_names_and_lens(nn_seq, nn_seq_len, 906 | lines_avail_seq) 907 | 908 | def nn_max_len(): 909 | """Return the max length of a node name across all tables.""" 910 | 911 | try: 912 | # nn_max_len = max(len(nn_cur) for nn_seq_cur in nn_seq.values() 913 | # for nn_cur in nn_seq_cur) 914 | # # only for active nodes, but varies 915 | nn_max_len = max(len(nn) for nn in 916 | self.lev1_summary_stats['nn']) 917 | # for all responding nodes, and less varying 918 | except ValueError: # max() arg is an empty sequence 919 | nn_max_len = 1 920 | # not set to 0 because str.format causes "ValueError: '=' 921 | # alignment not allowed in string format specifier" 922 | # otherwise 923 | 924 | return nn_max_len 925 | 926 | nn_max_len = nn_max_len() 927 | 928 | def tables_str_local(table_fields, fs_seq, nn_max_len, nn_seq, 929 | nn_seq_len): 930 | """Return a string representations for the specified table 931 | types. 932 | """ 933 | 934 | tables = [] 935 | for table_type in self._table_types: 936 | 937 | # Initialize table 938 | table = PrettyTable(table_fields, padding_width=0) 939 | table.vertical_char = ' ' 940 | table.junction_char = '-' 941 | table.set_field_align('Node', 'l') 942 | for field in table_fields[1:]: 943 | table.set_field_align(field, 'r') 944 | 945 | # Add totals row 946 | total_speeds = [self.lev1_summary_stats['fs'][fs][table_type] 947 | for fs in fs_seq] 948 | total_speeds = [self._bytes_str(i) for i in total_speeds] 949 | total_speeds_total = self.lev2_summary_stats[table_type] 950 | total_speeds_total = self._bytes_str(total_speeds_total) 951 | nn = '{:*^{}}'.format('Total', nn_max_len) 952 | row = [nn, total_speeds_total] + total_speeds 953 | table.add_row(row) 954 | 955 | # Add rows for previously determined file systems and node 956 | # names 957 | for nn in nn_seq[table_type]: 958 | nn_recs = [self.rec_select(nn, fs) for fs in fs_seq] 959 | # self.rec_select(nn, fs) can potentially be == None 960 | nn_speeds = [(nn_rec[table_type] if nn_rec else None) for 961 | nn_rec in nn_recs] 962 | nn_speeds = [self._bytes_str(i) for i in nn_speeds] 963 | nn_speeds_total = ( 964 | self.lev1_summary_stats['nn'][nn][table_type]) 965 | nn_speeds_total = self._bytes_str(nn_speeds_total) 966 | nn = '{:.<{}}'.format(nn, nn_max_len) 967 | # e.g. '{:.<{}}'.format('xy',4) = 'xy..' 968 | row = [nn, nn_speeds_total] + nn_speeds 969 | table.add_row(row) 970 | 971 | # Construct printable tables string 972 | label_template = ('{} bytes/s for top {} of {} active nodes ' 973 | 'out of {} responding') 974 | label = label_template.format( 975 | self._table_types[table_type]['label'], 976 | nn_seq_len[table_type, 'displayed'], 977 | nn_seq_len[table_type, 'active'], 978 | len(self.lev1_summary_stats['nn'])) 979 | table = '\n{}:\n{}'.format(label, table) 980 | tables.append(table) 981 | 982 | tables_str = '\n'.join(tables) 983 | return tables_str 984 | 985 | tables_str = tables_str_local(table_fields, fs_seq, nn_max_len, nn_seq, 986 | nn_seq_len) 987 | return tables_str 988 | 989 | def _tables_interlaced_str(self, num_avail_lines): 990 | """Return an interlaced string representation of the table types 991 | previously specified in self.__class__._table_types. Inactive nodes are 992 | not included. 993 | """ 994 | 995 | # Determine file systems used 996 | fs_seq = numsorted(tuple(self.lev1_summary_stats['fs'])) 997 | # tuple results in a hashable object which is required 998 | table_fields = (['Node', 'Type', 'Total'] + 999 | ['{:>6}'.format(fs) for fs in fs_seq]) 1000 | # 6 is the general len of a str returned by 1001 | # self._bytes_str 1002 | 1003 | def nn_max(num_avail_lines): 1004 | """Return the maximum number of nodes for which data can be 1005 | displayed.""" 1006 | 1007 | num_tables = len(self._table_types) 1008 | nn_max = num_avail_lines - 6 - num_tables 1009 | # 6 is the number of lines used by header and footer rows 1010 | # num_tables is the number of lines used by totals rows 1011 | nn_max = int(nn_max/num_tables) 1012 | num_avail_lines = max(num_avail_lines, 0) 1013 | return nn_max 1014 | 1015 | nn_max = nn_max(num_avail_lines) 1016 | 1017 | def nn_names_and_lens(nn_max): 1018 | """Return a sequence of the displayed node names, and a dict of the 1019 | node name sequence lengths. 1020 | """ 1021 | 1022 | nn_seq_len = {} 1023 | 1024 | nn_seq = [nn for nn, nn_summary_stats in 1025 | self.lev1_summary_stats['nn'].items() if 1026 | nn_summary_stats['brw'] > 0] 1027 | #nn_seq.sort() 1028 | sort_key = lambda nn: self.lev1_summary_stats['nn'][nn]['brw'] 1029 | nn_seq.sort(key = sort_key, reverse=True) 1030 | nn_seq_len['active'] = len(nn_seq) 1031 | 1032 | nn_seq = nn_seq[:nn_max] 1033 | nn_seq_len['displayed'] = len(nn_seq) 1034 | 1035 | return nn_seq, nn_seq_len 1036 | 1037 | nn_seq, nn_seq_len = nn_names_and_lens(nn_max) 1038 | 1039 | def nn_max_len(): 1040 | """Return the max length of a node name.""" 1041 | 1042 | try: 1043 | # nn_max_len = max(len(nn_cur) for nn_seq_cur in nn_seq.values() 1044 | # for nn_cur in nn_seq_cur) 1045 | # # this is only for active nodes, but varies 1046 | nn_max_len = max(len(nn) for nn in 1047 | self.lev1_summary_stats['nn']) 1048 | # this is for all responding nodes, and less varying 1049 | except ValueError: # max() arg is an empty sequence 1050 | nn_max_len = 1 1051 | # not set to 0 because str.format causes "ValueError: '=' 1052 | # alignment not allowed in string format specifier" 1053 | # otherwise 1054 | 1055 | return nn_max_len 1056 | 1057 | nn_max_len = nn_max_len() 1058 | 1059 | def tables_str_local(table_fields, fs_seq, nn_max_len, nn_seq): 1060 | """Return a string representation for the specified table types.""" 1061 | 1062 | # Initialize table 1063 | table = PrettyTable(table_fields, padding_width=0) 1064 | table.vertical_char = ' ' 1065 | table.junction_char = '-' 1066 | table.set_field_align('Node', 'l') 1067 | for field in table_fields[2:]: table.set_field_align(field, 'r') 1068 | 1069 | # Add totals row 1070 | nn = '{:*^{}}'.format('Total', nn_max_len) 1071 | for table_type in self._table_types: 1072 | total_speeds = [self.lev1_summary_stats['fs'][fs][table_type] 1073 | for fs in fs_seq] 1074 | total_speeds = [self._bytes_str(i) for i in total_speeds] 1075 | total_speeds_total = self.lev2_summary_stats[table_type] 1076 | total_speeds_total = self._bytes_str(total_speeds_total) 1077 | table_type = self._table_types[table_type]['label_short'] 1078 | row = [nn, table_type, total_speeds_total] + total_speeds 1079 | table.add_row(row) 1080 | nn = '' 1081 | 1082 | # Add rows for previously determined file systems and node names 1083 | for nn in nn_seq: 1084 | nn_recs = [self.rec_select(nn, fs) for fs in fs_seq] 1085 | # self.rec_select(nn, fs) can potentially be == None 1086 | nn_formatted = '{:.<{}}'.format(nn, nn_max_len) 1087 | # e.g. '{:.<{}}'.format('xy',4) = 'xy..' 1088 | for table_type in self._table_types: 1089 | nn_speeds = [(nn_rec[table_type] if nn_rec else None) for 1090 | nn_rec in nn_recs] 1091 | nn_speeds = [self._bytes_str(i) for i in nn_speeds] 1092 | nn_speeds_total = ( 1093 | self.lev1_summary_stats['nn'][nn][table_type]) 1094 | nn_speeds_total = self._bytes_str(nn_speeds_total) 1095 | table_type = self._table_types[table_type]['label_short'] 1096 | row = ([nn_formatted, table_type, nn_speeds_total] + 1097 | nn_speeds) 1098 | table.add_row(row) 1099 | nn_formatted = '' 1100 | 1101 | # Construct printable tables string 1102 | label_template = ('Bytes/s for top {} of {} active nodes out of ' 1103 | '{} responding') 1104 | label = label_template.format(nn_seq_len['displayed'], 1105 | nn_seq_len['active'], 1106 | len(self.lev1_summary_stats['nn'])) 1107 | tables_str = '\n{}:\n{}'.format(label, table) 1108 | 1109 | return tables_str 1110 | 1111 | tables_str = tables_str_local(table_fields, fs_seq, nn_max_len, nn_seq) 1112 | return tables_str 1113 | 1114 | class RecordGroupDeltaIterator: 1115 | """Yield RecordGroupDelta objects.""" 1116 | 1117 | def __iter__(self): 1118 | 1119 | self._receiver = Receiver() 1120 | 1121 | for rec_grp_prev, rec_grp_curr in common.pairwise(self._receiver): 1122 | rec_grp_delta = rec_grp_curr - rec_grp_prev 1123 | # for obj in (rec_grp_prev, rec_grp_curr, rec_grp_delta, ''): 1124 | # print(obj) 1125 | yield rec_grp_delta 1126 | 1127 | def close(self): 1128 | """Close the subprocess providing data to the iterator. 1129 | This must be used if an unhandled exception occurs. 1130 | """ 1131 | self._receiver.close() 1132 | 1133 | 1134 | class Display(Logger): 1135 | """Write RecordGroupDelta objects to the console in a user friendly 1136 | format. 1137 | """ 1138 | 1139 | # # Establish encoding for curses 1140 | # locale.setlocale(locale.LC_ALL, '') 1141 | # _encoding = locale.getpreferredencoding() # typically 'UTF-8' 1142 | 1143 | # Set format string for datetime 1144 | try: 1145 | _d_t_fmt = locale.nl_langinfo(locale.D_T_FMT) 1146 | except AttributeError: 1147 | _d_t_fmt = '%a %b %e %H:%M:%S %Y' 1148 | # obtained with locale.getlocale() == ('en_US', 'UTF8') 1149 | 1150 | def __init__(self): 1151 | 1152 | if not sys.stdout.isatty(): 1153 | err_msg = ('stdout is not open and connected to a tty-like device.' 1154 | ' If running the application on a host using ssh, use ' 1155 | 'the -t ssh option.') 1156 | raise errors.TTYError(err_msg) 1157 | 1158 | try: 1159 | self._init_curses() 1160 | self._write_initial_status() 1161 | self._write_recs() 1162 | finally: 1163 | 1164 | try: curses.endwin() #@UndefinedVariable 1165 | except curses.error: pass #@UndefinedVariable 1166 | 1167 | try: self._recgrps.close() 1168 | except AttributeError: # Attribute in question is self._recgrps 1169 | pass 1170 | 1171 | # Any unhandled exception that may have happened earlier is now 1172 | # raised automatically. 1173 | 1174 | if params.PRINT_LAST_RECORD: 1175 | try: print(self._recgrp_output_str) 1176 | except AttributeError: pass 1177 | 1178 | def _init_curses(self): 1179 | """Set up the curses display.""" 1180 | 1181 | self.logger.info('Initializing curses...') 1182 | 1183 | self._alert_msg = '' 1184 | 1185 | self._win = curses.initscr() 1186 | signal.siginterrupt(signal.SIGWINCH, False) 1187 | # siginterrupt above prevents the SIGWINCH signal handler of curses 1188 | # from raising IOError in Popen. Whether the signal is nevertheless 1189 | # raised or not is unconfirmed, although getmaxyx results are still 1190 | # updated. 1191 | 1192 | # Make cursor invisible 1193 | try: curses.curs_set(0) #@UndefinedVariable 1194 | except curses.error: pass #@UndefinedVariable 1195 | # The error message "_curses.error: curs_set() returned ERR" can 1196 | # possibly be returned when curses.curs_set is called. This can happen 1197 | # if TERM does not support curs_set. 1198 | # 1199 | # Alternative way: 1200 | # if curses.tigetstr('civis') is not None: #@UndefinedVariable 1201 | # curses.curs_set(0) #@UndefinedVariable 1202 | 1203 | def _init_key_listener(): 1204 | """Set up the curses key listener thread.""" 1205 | 1206 | def _key_listener(): 1207 | """Run the curses pause and resume key listener.""" 1208 | 1209 | curses.noecho() #@UndefinedVariable 1210 | self._win.nodelay(False) 1211 | 1212 | pause_key = params.DISPLAY_PAUSE_KEY 1213 | alert = 'paused' 1214 | 1215 | while True: 1216 | time.sleep(0.1) 1217 | # Techncially, sleep should not be necessary here 1218 | # because non-blocking mode is previously set by means 1219 | # of nodelay(False). 1220 | # Nevertheless, sleep was found to avoid getkey/getch 1221 | # from crashing (without any Exception) in a host with 1222 | # version 5.5-24.20060715 of ncurses. Another host 1223 | # (with version 5.7-3.20090208 of ncurses) was not 1224 | # observed to have this bug even without sleep. 1225 | # Key presses were observed to always be registered 1226 | # despite the sleep. 1227 | if self._win.getkey() == pause_key: 1228 | self._active = not self._active 1229 | with self._disp_lock: 1230 | if not self._active: 1231 | self._ins_alert(alert) 1232 | else: 1233 | self._del_alert() 1234 | # This is useful in the event the next 1235 | # normal update to the window is several 1236 | # seconds later. 1237 | 1238 | self._active = True 1239 | self._disp_lock = threading.Lock() 1240 | 1241 | _key_listener_thread = threading.Thread(group=None, 1242 | target=_key_listener, 1243 | name='KeyListener') 1244 | _key_listener_thread.daemon = True 1245 | _key_listener_thread.start() 1246 | 1247 | _init_key_listener() 1248 | 1249 | def _ins_alert(self, alert): 1250 | """Insert the supplied alert str into the second row. Any prior alert 1251 | is first deleted. 1252 | """ 1253 | 1254 | self._del_alert() 1255 | # Delete previous alert so that multiple alerts are not displayed 1256 | # at once. 1257 | self._alert_msg = alert 1258 | # Store current alert to make it available for later deletion. 1259 | 1260 | # Insert alert 1261 | if alert: 1262 | w = self._win 1263 | try: 1264 | w.insstr(1, 0, '() ') 1265 | w.insstr(1, 1, alert, curses.A_UNDERLINE) #@UndefinedVariable 1266 | except: pass 1267 | 1268 | def _del_alert(self): 1269 | """Delete the most recent alert str from the second row.""" 1270 | 1271 | if self._alert_msg: 1272 | try: 1273 | for _ in range(len(self._alert_msg) + 3): 1274 | self._win.delch(1, 0) 1275 | except: pass 1276 | self._alert_msg = '' 1277 | 1278 | def _write_initial_status(self): 1279 | """Write the initial collection status.""" 1280 | 1281 | self.logger.info('Writing initial status...') 1282 | with self._disp_lock: 1283 | nodeset = params.GPFS_NODESET or 'first available' 1284 | status_template = ('{}\n\nCollecting initial data for {} nodeset ' 1285 | 'from {}.\n\nWait {:.0f}s.') 1286 | status = status_template.format(params._PROGRAM_NAME, 1287 | nodeset, 1288 | params.MMPMON_HOST, 1289 | params.MONITORING_INTERVAL_SECS*2) 1290 | # params.MONITORING_INTERVAL_SECS is multiplied by 2 because 1291 | # data is fully received for an iteration only after the next 1292 | # iteration has internally begun to be received. 1293 | 1294 | self._write(status) 1295 | 1296 | def _write_recs(self): 1297 | """Write individual records.""" 1298 | 1299 | self.logger.info('Writing records...') 1300 | self._recgrps = RecordGroupDeltaIterator() 1301 | for recgrp in self._recgrps: 1302 | if self._active and self._disp_lock.acquire(False): 1303 | self._recgrp_output_str = self._format_output(recgrp) 1304 | self._write(self._recgrp_output_str) 1305 | self._disp_lock.release() 1306 | 1307 | # Allow time for the final update to be seen 1308 | time.sleep(params.MONITORING_INTERVAL_SECS) 1309 | 1310 | def _format_output(self, recgrp): 1311 | """Return the formatted string to display to the screen.""" 1312 | 1313 | strftime = lambda dt: dt.strftime(self._d_t_fmt).replace(' ', ' ') 1314 | # replace is used above to for example replace 'Feb 3' to 'Feb 3' 1315 | 1316 | datetime_now = datetime.datetime.now() 1317 | recgrp_timestamp_age = datetime_now - recgrp.timestamp 1318 | recgrp_timestamp_age = recgrp_timestamp_age.total_seconds() 1319 | 1320 | # Determine header 1321 | title = '{} [updated {}]'.format(params._PROGRAM_NAME, 1322 | strftime(datetime_now)) 1323 | status_template = ('Displaying activity for {:.1f}s before the past ' 1324 | '{:.1f}s.\n') 1325 | status = status_template.format(recgrp.time_duration_secs, 1326 | recgrp_timestamp_age) 1327 | header = '\n'.join((title, status)) 1328 | 1329 | # Determine table string 1330 | num_avail_lines = self._win.getmaxyx()[0] - header.count('\n') 1331 | num_avail_lines = max(num_avail_lines, 0) 1332 | tables_str = recgrp.tables_str(format_=params.TABLE_TYPE, 1333 | num_avail_lines=num_avail_lines) 1334 | 1335 | return header + tables_str 1336 | 1337 | def _write(self, str_): 1338 | """Update the display with the provided string.""" 1339 | 1340 | w = self._win 1341 | w.erase() 1342 | 1343 | try: 1344 | w.addstr(str(str_)) 1345 | w.addstr(0, 0, params._PROGRAM_NAME, 1346 | curses.A_BOLD) #@UndefinedVariable 1347 | except: pass 1348 | # The try except block was found to prevent occasional errors by 1349 | # addstr, but not if the block enclosed all w actions, which is 1350 | # unexpected. 1351 | 1352 | w.refresh() 1353 | 1354 | 1355 | if __name__ == '__main__': 1356 | 1357 | logger = logging.getLogger(params._PROGRAM_NAME_SHORT) 1358 | 1359 | try: 1360 | ArgParser() 1361 | DiagnosticLoggerSetup() 1362 | Display() 1363 | 1364 | except (KeyboardInterrupt, errors.Error, Exception) as exception: 1365 | 1366 | try: 1367 | logger.exception(exception) 1368 | except AttributeError: 1369 | # Likely cause: AttributeError: type object 'NullHandler' has no 1370 | # attribute 'level' 1371 | pass 1372 | 1373 | if isinstance(exception, KeyboardInterrupt): 1374 | exit() 1375 | elif isinstance(exception, errors.Error) and exception.args: 1376 | exit('\n'.join(exception.args)) 1377 | else: 1378 | raise 1379 | --------------------------------------------------------------------------------