├── gtop-example.gif ├── gtop-0.99-screenshot.gif ├── gtop-0.99-screenshot.jpg ├── gtop user guide - Community.odt ├── pkgs ├── gtop-0.99-3.fc17.x86_64.rpm ├── gtop-1.0-0.fc17.x86_64.rpm └── gtop-1.0-0.rh6.x86_64.rpm ├── .gitignore ├── snmpd.conf_gtop ├── gtoprc.xml ├── gtop_iputils.py ├── gtop_utils.py ├── CHANGELOG ├── README.md ├── README ├── LICENSE └── gtop.py /gtop-example.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcuzner/gluster-monitor/HEAD/gtop-example.gif -------------------------------------------------------------------------------- /gtop-0.99-screenshot.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcuzner/gluster-monitor/HEAD/gtop-0.99-screenshot.gif -------------------------------------------------------------------------------- /gtop-0.99-screenshot.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcuzner/gluster-monitor/HEAD/gtop-0.99-screenshot.jpg -------------------------------------------------------------------------------- /gtop user guide - Community.odt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcuzner/gluster-monitor/HEAD/gtop user guide - Community.odt -------------------------------------------------------------------------------- /pkgs/gtop-0.99-3.fc17.x86_64.rpm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcuzner/gluster-monitor/HEAD/pkgs/gtop-0.99-3.fc17.x86_64.rpm -------------------------------------------------------------------------------- /pkgs/gtop-1.0-0.fc17.x86_64.rpm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcuzner/gluster-monitor/HEAD/pkgs/gtop-1.0-0.fc17.x86_64.rpm -------------------------------------------------------------------------------- /pkgs/gtop-1.0-0.rh6.x86_64.rpm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcuzner/gluster-monitor/HEAD/pkgs/gtop-1.0-0.rh6.x86_64.rpm -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | 21 | # Installer logs 22 | pip-log.txt 23 | 24 | # Unit test / coverage reports 25 | .coverage 26 | .tox 27 | nosetests.xml 28 | 29 | # Translations 30 | *.mo 31 | 32 | # Mr Developer 33 | .mr.developer.cfg 34 | .project 35 | .pydevproject 36 | -------------------------------------------------------------------------------- /snmpd.conf_gtop: -------------------------------------------------------------------------------- 1 | syslocation "testlab" 2 | syscontact INF 3 | # 4 | # 5 | com2sec local localhost gluster 6 | com2sec other default gluster 7 | # 8 | group RWGroup v2c local 9 | group ROGroup v1 other 10 | group ROGroup v2c other 11 | # 12 | view all included .1 80 13 | # 14 | # context sec.model sec.level prefix read write notif 15 | access RWGroup "" v2c noauth exact all all all 16 | access ROGroup "" v2c noauth exact all none none 17 | # 18 | # Logging - comment this out to show all connections for debuging 19 | dontLogTCPWrappersConnects yes 20 | -------------------------------------------------------------------------------- /gtoprc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /gtop_iputils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # gtop - A performance and capacity monitoring program for glusterfs clusters 4 | # 5 | # gtop-ip-utils : generic IP methods/classes called by the main gtop program 6 | # 7 | # Copyright (C) 2013 Paul Cuzner 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | # 21 | 22 | import socket 23 | import netsnmp 24 | 25 | class SNMPsession: 26 | 27 | def __init__(self, 28 | oid='sysdescr', 29 | version=2, 30 | destHost='localhost', 31 | community='gluster'): 32 | 33 | self.oid=oid 34 | self.version=version 35 | self.destHost=destHost 36 | self.community=community 37 | 38 | def query(self): 39 | """ Issue the snmpwalk. If it fails the output is empty, not exception is thrown, so you need to check 40 | the returned value to see if it worked or not ;o) 41 | """ 42 | 43 | result = [] 44 | # result is a tuple of string values 45 | snmpOut = netsnmp.snmpwalk(self.oid, Version=self.version, DestHost=self.destHost, Community=self.community, Retries=0, Timeout=100000) 46 | 47 | # convert any string element that is actually a number to a usable number (int) 48 | for element in snmpOut: 49 | if element == None: 50 | result.append(element) 51 | elif element.isdigit(): 52 | result.append(int(element)) 53 | else: 54 | result.append(element) 55 | 56 | return result 57 | 58 | def validIPv4(ip): 59 | """ Attempt to use the inet_aton function to validate whether a given IP is valid or not """ 60 | 61 | try: 62 | t = socket.inet_aton(ip) # try and convert the string to a packed binary format 63 | result = True 64 | except socket.error: # if it doesn't work address string is not valid 65 | result = False 66 | 67 | return result 68 | 69 | 70 | def forwardDNS(name): 71 | """ Use socket module to find name from IP, or just return empty""" 72 | 73 | try: 74 | result = socket.gethostbyname(name) # Should get the IP for NAME 75 | except socket.gaierror: # Resolution failure 76 | result = "" 77 | 78 | return result 79 | 80 | def reverseDNS(ip): 81 | """ Use socket module to find name from IP, or just return the IP""" 82 | try: 83 | out = socket.gethostbyaddr(ip) # returns 3 member tuple 84 | name = out[0] 85 | result = name.split('.')[0] # only 1st entry is of interest, and only the 1st qualifier 86 | except: 87 | result = "" 88 | 89 | return result 90 | -------------------------------------------------------------------------------- /gtop_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # gtop - A performance and capacity monitoring program for glusterfs clusters 4 | # 5 | # gtop-utils : generic methods called by the main gtop program 6 | # 7 | # Copyright (C) 2013 Paul Cuzner 8 | # 9 | # This program is free software: you can redistribute it and/or modify 10 | # it under the terms of the GNU General Public License as published by 11 | # the Free Software Foundation, either version 3 of the License, or 12 | # (at your option) any later version. 13 | # 14 | # This program is distributed in the hope that it will be useful, 15 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | # GNU General Public License for more details. 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | # 21 | import subprocess 22 | import struct, datetime 23 | from subprocess import PIPE,Popen # used in screenSize and issueCMD 24 | 25 | def convertBytes(inBytes): 26 | """ 27 | Routine to convert a given number of bytes into a more human readable form 28 | 29 | Input : number of bytes 30 | Output : returns a MB / GB / TB value for bytes 31 | 32 | """ 33 | 34 | 35 | bytes = float(inBytes) 36 | if bytes >= 1125899906842624: 37 | size = round(bytes / 1125899906842624) 38 | #displayBytes = '%.1fP' % size 39 | displayBytes = '%dP' % size 40 | elif bytes >= 1099511627776: 41 | size = round(bytes / 1099511627776) 42 | displayBytes = '%dT' % size 43 | elif bytes >= 1073741824: 44 | size = round(bytes / 1073741824) 45 | displayBytes = '%dG' % size 46 | elif bytes >= 1048576: 47 | size = int(round(bytes / 1048576)) 48 | displayBytes = '%dM' % size 49 | elif bytes >= 1024: 50 | size = int(round(bytes / 1024)) 51 | displayBytes = '%dK' % size 52 | else: 53 | displayBytes = '%db' % bytes 54 | 55 | return displayBytes 56 | 57 | 58 | def issueCMD(cmd=""): 59 | """ Issue cmd to the system, and return output to caller as a list""" 60 | 61 | cmdWords = cmd.split() 62 | out = subprocess.Popen(cmdWords,stdout=PIPE, stderr=PIPE) 63 | (response, errors)=out.communicate() # Get the output...response is a byte 64 | # string that includes \n 65 | 66 | return response.split('\n') # use split to return a list 67 | 68 | 69 | #def oct2Tuple(dateOctet): 70 | # """ This function call converts the SNMP datetime octet into a human readable 71 | # tuple. 72 | # """ 73 | # 74 | # thisOct = str(dateOctet[0]) # convert to str first 75 | # octLen = len(thisOct) 76 | # fmt = dict({8:'>HBBBBBB', 11:'>HBBBBBBcBB'}) 77 | # 78 | # if octLen == 8 or octLen == 11: 79 | # dateTuple = struct.unpack(fmt[octLen],thisOct) 80 | # return dateTuple 81 | # else: 82 | # return [] 83 | # 84 | 85 | def oct2DateTime(dateOctet): 86 | """ receive an snmp date octet string and convert and return a datetime object 87 | """ 88 | 89 | thisOct = str(dateOctet[0]) 90 | 91 | # SNMP returns an 11 byte str that includes UTC offset. Not interesting in that 92 | # so when we return the datetime object, we only return first 6 items (yy,mm,dd,hh,mm,ss) 93 | thistuple=struct.unpack('>HBBBBBBcBB',thisOct) 94 | t = datetime.datetime(*thistuple[:6]) 95 | 96 | return t 97 | 98 | #>> import datetime 99 | #>> a = datetime.datetime.now() 100 | #>> b = datetime.datetime.now() 101 | #>> c = b - a 102 | #datetime.timedelta(0, 8, 562000) 103 | #>>> divmod(c.days * 86400 + c.seconds, 60) 104 | #(0, 8) # 0 minutes, 8 seconds 105 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | Change Log 2 | 3 | Investigate 4 | - add help screen overlay to show the commands (greg Olsen) 5 | - screen resize. When detected, the dh and vh settings could be recalculated to resize the areas in the UI? 6 | - look at pass_persist to expose IOPS to snmp - see http://www.woofpuppy.com/2012/05/exposing-iostat-data-via-snmp-in.html 7 | - add IOPS to rollup for cluster in info window 8 | - add total IOPS to each node stats - UCD-DISKIO-MIB 9 | - could add the snmpset for the nicstats to the start up process - check the setting, and warn if necessary - DROPPED 10 | - ip discards total for each node to pick up network errors 11 | - add sysUpTimeInstance to each of the nodes 12 | - change symbols used to be ascii for tty consoles - > up, | down, ? unknown for example DONE 13 | - add colour 14 | - Using a volume status - online, degraded, restricted, offline, stopped 15 | - changing volume gathering for glusterfs commands - status detail and info and merge the contents together 16 | instead of using the snmp method. May simplify and reduce the code base. 17 | 18 | 19 | 20 | 1.0.0 <-- Current 21 | - fixed batch mode alignment - DONE 22 | - added --bg-mode (-b) to show nodes(default), summary, all and --format (-f) for raw or readable(default) 23 | - Documentation updates to README 24 | 25 | 0.99-3 26 | - fixed bug highlighted with 3.4 changes to the order of parameters in the volfiles 27 | 28 | 0.99-2 29 | - fixes applied to account for changed SNMP behaviour on Fedora 17 and above (host resources MIB doesn't keep the 30 | hrStorage items in sync across Descr / Size and Used) 31 | - included the older glusterfs 3.2 syntax in the daemon monitoring (-f in 3.2, -s in 3.3!) 32 | - changes to spec file to make rc.local changes optional, and dependency on glusterfs is now 3.2 33 | 34 | 0.99 35 | - started to split up the code to make it more manageable - gtop_utils, gtop_iputils 36 | - added checks for ctdb, samba, nfs, self heal, georep on every node scan and updated the node display 37 | - changed status icons based on terminal type, xterm has better unicode support so use if available 38 | - added get for hrSystemDate for each node to enable clock skew detection between nodes, with 39 | initial logic to compare time across node sample time stamps - shows when ntp drift or daemon 40 | is not running 41 | 42 | 43 | 0.98 44 | - change the volume and data sections from windows to pads to support scrolling so gtop can support large clusters 45 | - change volume area to be scrollable ( up and down keys) 46 | - change node area to be scrollable (+ and - keys) 47 | - updated the symbols used for node up/down and highlighting to account for console (vt) and xterm unicode and 48 | colour differences 49 | 50 | 51 | 0.95 52 | - extended the sort capability to the user allowing the on screen data to be sorted as follows; 53 | . volume info (v, toggles name / f toggles freespace / s toggles size) 54 | . system data (n nodename / c toggles CPU% . i netin / o netout / r disk reads / w disk writes) 55 | - expanded config file to provide run time overrides (snmp name, screen area ratio's minimums, disk blocksize/sector) 56 | - switched to 64bit network counters (SNMP HC OIDs), and added fix to catch counter rollovers/overflows in nic stats 57 | 58 | 0.92 59 | - replace the use of python threads with the multiprocssing model to make the calls to snmpwalk non-blocking (async) 60 | - added numretries=0 and timeout (1sec) parms to snmp class as default for every snmpwalk session 61 | - if snmp fails for a host - reset the sys stats to 0 - and continue to try and pool to pick up when host comes back online 62 | - volume information is sorted alphabetically by name for consistent display 63 | 64 | 0.91 65 | - replace curses A_REVERSE for volume bars with unicode block symbols making code simpler 66 | - add status symbol to represent the state of each node in interactive mode - up,down,unknown 67 | 68 | 69 | 0.9 ../02/2013 - To Do List 70 | - Catching xterm resize exception and terminating gracefully. Python 2.7 has features making this easier to handle DONE 71 | - use the volume list and node list to dynamicaly build the screen window sizes instead of them being hard set - DONE 72 | - Add -g runtime option - DONE 73 | - Add function to read external XML config file to define groups of servers to scan (~/gtoprc.xml)--> DONE 74 | - glusterpeers updated (simplified using join) --> DONE 75 | - Errors written to stdout now all prefixed ERR for consistency and 'callout' --> DONE 76 | - relayout windows just using full width horizontal areas - cluster / volumes / systems - DONE 77 | - add a rollup of metrics to the info window and relayout to 3 horizontal areas - info > volume > nodes -DONE 78 | -disk read/write - DONE 79 | -netin netout - DONE 80 | - avg/peak CPU - DONE 81 | - total usable capacity - configured and free - DONE 82 | 83 | 84 | 0.85 ../01/2013 85 | - Changed output logic to make more reuseable 86 | - added curses support, CTRL-C or q/Q is available 87 | - volume and cluster info areas added to the standard host data information 88 | - removed keyscan (Console class/methods) since curses now being used 89 | - added display of core count and server memory to host details 90 | - added support for striped volumes 91 | - added update to the info window for peer status, with warning if active < cluster size 92 | 93 | 94 | 0.81 25/01/2013 95 | - merge getclusterpeers into a cluster class 96 | - added issueCMD function, and updated screenSize to use issueCMD - DONE 97 | - changed references from RHS to gluster - DONE 98 | - creating host objects earlier simplifying code - DONE 99 | - changed get peer list to use gluster cli through issueCMD interface - DONE 100 | - changed thread object to accept a type, to dictate which data function to run - DONE 101 | - added xlator class and volume class and methods...DONE 102 | - added get data code for filesystem utilisation and GLUSTERvol updates - DONE 103 | - switched to using a 1 second pause and timer to manage the data gathering allowing different stats 104 | to be gathered at different points - DONE 105 | 106 | 0.7 ../01/2013 107 | - First internal release for peer review 108 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #gluster-monitor - gtop 2 | 3 | This repo hosts an SNMP based CLI tool for monitoring capacity and node performance of a glusterfs cluster 4 | 5 | ##Background 6 | 7 | gtop is a python program written to provide a means of monitoring the high level activity 8 | within a gluster cluster. 9 | 10 | Gluster itself does not currently expose performance metrics so in order to provide a meaningful 11 | indication of workload, the node's system statistics are gathered over SNMP and aggregated. The data is presented in thre areas in the UI 12 | * *Cluster Area* - aggregated view of total load 13 | * *Volume Area* - capacity view for the cluster 14 | * *Node Area* - node performance metrics averaged over a 5 seconds sample interval 15 | 16 | The animated image below shows how the UI looks, and also follows a workflow to illustrate the way that node states can transition depending upon glusterd and snmp availability. 17 | 18 | ![here] (/gtop-example.gif "Animated gtop display") 19 | 20 | 21 | 22 | ##Installation 23 | 24 | The following packages need to be installed on each of the gluster nodes 25 | 26 | * net-snmp 27 | * net-snmp-utils 28 | * net-snmp-python 29 | 30 | The snmpd daemon needs to be started at boot, and have a known community string defined 31 | to allow gtop to poll for data. An example of a working snmpd.conf is provided in the repo. 32 | 33 | It is recommended that gtop is installed on all gluster nodes. The gtop script requires the following scripts to be found in the user's PATH 34 | - gtop.py 35 | - gtop_utils.py 36 | - gtop_iputils.py 37 | 38 | Optionally a configuration file can be placed in the users home directory called gtoprc.xml. An example of this file is provided in the repo, and can be useful when applying overrides to the script. 39 | 40 | ##Usage 41 | 42 | *gtop* uses the optionparser module to enable the tool to run in two modes 43 | 44 | 1. UI : This is the default, when run on a gluster node. 45 | 2. BATCH : by starting gtop with a -s or -g flag, the program will only gather system stats and write them for stdout. 46 | 47 | The options available on the command can be shown by invoking >gtop -h 48 | ``` 49 | [root@rhs5-1 ~]# gtop -h 50 | Usage: gtop [options] argument 51 | 52 | This program uses snmp to gather and present various operational metrics 53 | from gluster nodes to provide a single view of a cluster, that refreshes 54 | every 5 seconds. 55 | 56 | Options: 57 | --version show program's version number and exit 58 | -h, --help show this help message and exit 59 | -n, --no-heading suppress headings 60 | -s SERVERLIST, --servers=SERVERLIST 61 | Comma separated list of names/IP (default uses 62 | gluster's peers file) 63 | -g GROUPNAME, --server-group=GROUPNAME 64 | Name of a server group define in the users XML config 65 | file) 66 | ``` 67 | 68 | 69 | In either mode, the program first looks for a configuration file in the users 70 | home directory - gtoprc.xml. This file provides overrides for some gtop settings - 71 | snmp community string, disk block size, and also allows server groups to be defined 72 | to simplify invocation for batch mode. 73 | 74 | 75 | 76 | ###UI Mode 77 | The UI uses the ncurses environment to handle the screen display, and provides a console 78 | that is split into 3 main areas; 79 | 80 | - Cluster Info : The top section of the display shows, cluster wide metrics such as 81 | node information, cpu average/peak, and total network/disk bandwidth. Added in 0.99, the cluster area also 82 | shows a time skew field. This indicates the max time difference across the nodes in the cluster. Normally this 83 | value is <= the sample interval (5s) - but if ntpd is not configured larger skews can be seen. The reason for 84 | introducing this feature is to help identify geo-replication issues - since geo-replication requires a common time 85 | source for all nodes/bricks to work correctly. 86 | - Volume Info : The middle section's focus is on the volumes provided by gluster. Each 87 | volume entry shows attributes such as # bricks, Usable Size, freespace 88 | and includes a simple bar chart illustrating % utilised. 89 | - Node Info : The bottom of the screen provides the system metrics for each node, and some 90 | indication as to the physical configuration. Each node entry shows; cores/threads, RAM, 91 | followed by utilisation metrics covering CPU Busy, Memory, network and disk and includes daemon 92 | monitoring flags for CTDB, Samba, NFS, Self-Heal and Geo-Replication 93 | 94 | Once launched the volume and Node areas support sorting (forward and reverse), based on specific keys; 95 | 96 | *Volume Area* 97 | F/f : Freespace 98 | V/v : volume name 99 | U/u : UsableSize 100 | 101 | *Node Area* 102 | N/n : node name 103 | C/c : CPU busy 104 | I/i : Network in average 105 | O/o : Network out average 106 | R/r : Disk Read 107 | W/w : Disk Write 108 | 109 | In addition to sorting, the node and volume areas are scrollable to cater for large cluster environments. The node area 110 | is scrolled using the + or - keys, and the volume area uses the up/down arrow keys. 111 | 112 | 113 | To quit the UI, use 'q' or CTRL-C. 114 | 115 | 116 | ###BATCH Mode 117 | 118 | Running in batch mode can provide a remote view of the cluster, or potentially allow multiple clusters 119 | to be grouped and displayed together when using the server group definitions in the configuration file. 120 | 121 | gtop in batch mode simply writes the node statistics only to stdout, and so could be redirected to a file 122 | to collect system stats for later analysis in a spreadsheet, or processing with gnuplot, or matplotlib. 123 | 124 | To quit batch mode, use CTRL-C. 125 | 126 | A User Guide is also provided in Libreoffice (.odt) format. 127 | 128 | ## Known Issues 129 | 130 | The program's design makes the following compromises; 131 | 132 | 1. The system stats are refreshed by the snmp agent that is hard set to 5 second 133 | sample intervals. This limits the granularity of gtop for problem determination and 134 | correlation with client side metrics. 135 | 136 | 2. snmpd needs to be running on each of the gluster nodes. Under load (80+% CPU), 137 | the snmpd daemon can fail to respond in a timely manner for gtop. In these circumstances 138 | gtop resets the stats for the node and marks the node as unknown for that sample run. Nodes 139 | marked as not responding continue to be polled, so as and when they 'recover' data is 140 | made available in the interface. 141 | 142 | It's also worth noting that the netsnmp bindings for python are synchronous, which can block 143 | the data gathering process. To address this, gtop uses the multiprocessing module, placing the snmp interation 144 | in separate processes - this way a delay on one node's sample does not impact the other snmp gathering 145 | sessions. 146 | 147 | As a result of this approach, when gtop starts you wil see the following types of processes active; 148 | - parent process started by the user 149 | - subprocess handling memory sharing between parent and child processes 150 | - n x subprocesses for node gathering. 151 | 152 | The side effect for this approach is better scalability and more effective use of multiple cores. 153 | 154 | 155 | 156 | ##Feedback 157 | 158 | Comments and contributions to the code are welcome and encouraged. 159 | 160 | 161 | Author: paul dot cuzner at gmail dot com 162 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | GTOP README 2 | 3 | Author: Paul Cuzner 4 | Date: May 2013 5 | License: GPLv3+ 6 | 7 | 8 | Background 9 | ---------- 10 | gtop is a python program was written to provide a means of monitoring the high level activity 11 | within an glusterfs cluster. Glusterfs itself does not currently expose performance 12 | metrics so in order to provide a meaningful indication of workload this program gathers 13 | each node's system statistics over SNMP and presents them to the admin. 14 | 15 | Example Output 16 | +--------------------------------------------------------------------------------+ 17 | |gtop - 3.3.0.7rhs 2 nodes, 2 active CPU%: 1 Avg, 1 peak Skew: 0s 15:34:28| 18 | |Activity: Network: 47K in, 48K out Disk: 0b reads, 9K writes | 19 | |Storage:10 volumes, 20 bricks / 23G raw, 14G usable, 3G used, 11G free | 20 | |Volume Bricks Type Size Used Free Volume Usage | 21 | |ctdb 2 R 491M 25M 466M █ 5% | 22 | |ftp 2 R 991M 283M 709M █████ 28% | 23 | |repl 2 R 1015M 195M 820M ███ 19% | 24 | |smallfiles 2 R 6G 2G 4G ███████ 39% | 25 | |temp1 2 D 1007M 51M 955M █ 5% | 26 | |temp2 2 D 1007M 51M 955M █ 5% | 27 | |temp3 2 D 1007M 51M 955M █ 5% | 28 | |temp4 2 D 1007M 51M 955M █ 5% | 29 | |temp5 2 D 1007M 51M 955M █ 5% | 30 | |temp6 2 D 1007M 51M 955M █ 5% | 31 | | | 32 | | CPU Memory % Daemons Network Disk I/O | 33 | |S Gluster Node C/T % RAM Real|Swap C-S-N-H-G In | Out Reads | Writes| 34 | |▲ rhs5-1 2 1 997M 62 0 Y . Y Y . 12K 11K 0b 3K | 35 | |▲ rhs5-2 2 1 997M 61 0 Y . Y Y . 35K 37K 0b 6K | 36 | +--------------------------------------------------------------------------------+ 37 | 38 | Features 39 | -------- 40 | gtop gathers various metrics over SNMP, and gluster configuration data by reading configuration 41 | files (if available) from the node the program is executed on. 42 | 43 | This data gathering enables the following 44 | * Aggregated performance - cpu, network and disk IO 45 | * Overall capacity - raw and usable defined by the volumes in the cluster 46 | * skew - time variation across the node samples (helps to identify ntp misconfiguration) 47 | * Volume Details - volume type, together with capacity utilisation 48 | * Node Details - per node infomation detailing performance and daemon state 49 | * Node state - each node has a status indicator, showing when glusterd is 50 | inactive, or when snmpd is non-responsive. 51 | 52 | The above information is provided in an ncurses UI, but a batch mode option is available that 53 | provides the performance metrics only (-b or -s invocation parameter) 54 | 55 | 56 | 57 | Installation 58 | ------------ 59 | * Pre-requisites packages 60 | The following packages need to be installed on each of the glusterfs nodes 61 | - net-snmp 62 | - net-snmp-utils 63 | - net-snmp-python 64 | 65 | * Installation files 66 | The following files are needed for gtop to function 67 | - gtop.py : main program 68 | - gtop_iputils : module providing some of the general purpose IP utilities used by gtop 69 | - gtop_utils : module providing general purpose functions that could be reused in other programs 70 | - snmpd.conf_example : example snmpd.conf file that allows gtop to gather statistics 71 | - gtoprc.xml : sample configuration file for gtop, that provides a means of overriding some 72 | configuration items at run time 73 | 74 | * Setup Steps 75 | 76 | All Nodes 77 | 1. Ensure pre-requisite packages (above) are installed 78 | 2. copy the gtop tar file to the /root/ directory 79 | 3. untar with tar -xvzf, which will create a gluster-monitor directory 80 | 4. Save the current snmpd.conf file, and replace with the example provided in the gluster-monitor directory 81 | 5. enable snmpd to start at boot with chkconfig 82 | 6. [Recommended] Update rc.local file to allow the network stats to be refreshed every second by adding 83 | snmpset -c -v2c 127.0.0.1 1.3.6.1.4.1.8072.1.5.3.1.2.1.3.6.1.2.1.2.2 i 1 84 | 7. start snmpd (service snmpd start), and run the snmpset command 85 | 86 | Single node or All nodes 87 | 1. cd to the gluster-monitor directory (e.g. cd /root/gluster-montor) 88 | 2. run the tool by executing ./gtop.py 89 | 3. [Optional] Add a symlink to gtop.py call gtop, to make execution easier 90 | 4. [Optional] copy and update the gtoprc.xml file to /root if you'd like to change some of the 91 | run time behaviours or establish server groups when running in batch mode 92 | 93 | 94 | Usage 95 | ----- 96 | 97 | * GUI 98 | The UI uses the ncurses environment to handle the screen display, and provides a console 99 | that is split into 3 main areas; 100 | 101 | - Cluster Info : The top section of the display shows, cluster wide metrics such as 102 | node information, cpu average/peak, and total network/disk bandwidth 103 | - Volume Info : The middle section's focus is on the volumes provided by gluster. Each 104 | volume entry shows attributes such as # bricks, Usable Size, freespace 105 | and includes a simple bar chart illustrating % utilised. 106 | - Node Info : The bottom of the screen provides the system metrics for each node, and some 107 | indication as to the physical configuration. 108 | Each node entry shows; cores/threads, RAM, followed by utilisation metrics 109 | covering CPU Busy, Memory, network and disk and daemon status checks for 110 | ctdb, samba, nfs, self heal and geo-replication 111 | 112 | Once launched the volume and Node areas support sorting (toggling between forward and reverse) 113 | based on specific keys; 114 | 115 | Volume Area 116 | F/f : Freespace 117 | V/v : volume name 118 | U/u : UsableSize 119 | 120 | Node Area 121 | N/n : node name 122 | C/c : CPU busy 123 | I/i : Network in average 124 | O/o : Network out average 125 | R/r : Disk Read 126 | W/w : Disk Write 127 | 128 | Both the volume area and node area are scrollable, to cater for complex deployments. Each area has 129 | a highlighted row that indicates the current cursor position. Moving the cursor in the volume area 130 | is done with the up and down arrows. Within the node area, the + and - keys are used. 131 | 132 | To quit the UI, 'q' or CTRL-C is supported. 133 | 134 | 135 | * Batch Mode 136 | Running in batch mode can provide a remote view of the cluster, or potentially allow multiple clusters 137 | to be grouped and displayed together when using the server group definitions in the configuration file. 138 | 139 | gtop in batch mode simply writes the node statistics only to stdout, and so could be redirected to a file 140 | to collect system stats for later analysis in a spreadsheet, or processing with gnuplot, or matplotlib. 141 | 142 | To quit batch mode, use CTRL-C. 143 | 144 | 145 | Syntax 146 | ------ 147 | [root@rhs5-1 ~]# gtop.py -h 148 | Usage: gtop.py [options] argument 149 | 150 | This program uses snmp to gather and present various operational metrics 151 | from gluster nodes to provide a single view of a cluster, that refreshes 152 | every 5 seconds. 153 | 154 | Options: 155 | --version show program's version number and exit 156 | -h, --help show this help message and exit 157 | -n, --no-heading suppress headings 158 | -s SERVERLIST, --servers=SERVERLIST 159 | Comma separated list of names/IP (default uses 160 | gluster's peers file) 161 | -b BGMODE, --bg-mode=BGMODE 162 | Which data to display in 'batch' mode ['nodes', 'all', 163 | 'summary'], (default is nodes) 164 | -f DATAFORMAT, --format=DATAFORMAT 165 | Output type raw or readable(default) 166 | -g GROUPNAME, --server-group=GROUPNAME 167 | Name of a server group define in the users XML config 168 | file) 169 | 170 | 171 | 172 | Upstream Project 173 | ---------------- 174 | The gtop program is developed within the community and can be found on gluster forge 175 | --> https://forge.gluster.org/gtop 176 | 177 | Packages are available in the repo under the pkgs directory for fedora, and RHEL6. 178 | 179 | 180 | Further Information 181 | ------------------- 182 | For further information, consult the user guide in the gluster forge git repository. 183 | 184 | 185 | Feedback 186 | -------- 187 | Comments and feedback can be posted through gluster forge. 188 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /gtop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # gtop - A performance and capacity monitoring program for glusterfs clusters 4 | # 5 | # Copyright (C) 2013 Paul Cuzner 6 | # 7 | # This program is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # This program is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU General Public License for more details. 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | # 19 | # 20 | # Usage 21 | # It is assumed that if you run the program on a gluster node, you want the interactive mode to get volume info and glusterd 22 | # checks. If this is not needed, the user uses the -s (server list) or -g (group) option to start gathering and displaying 23 | # the system stats for those systems 24 | # 25 | # Dependencies 26 | # 1. snmp packages - net-snmp / net-snmp-utils (for snmpset) and net-snmp-python on each gluster node 27 | # 2. a working snmpd daemon (a sample snmpd.conf file is provided 28 | # 3. [Optional] Update to rc.local on older systems to ensure network stats 29 | # are consistent (RHEL6) 30 | # >snmpset -c RHS -v2c 127.0.0.1 1.3.6.1.4.1.8072.1.5.3.1.2.1.3.6.1.2.1.2.2 i 1 31 | # 4. All gluster nodes are assumed to be registered in DNS 32 | # - also worthwhile using rc.local to execute the following to ensure NIC metrics are consistent with dstat/ifstat 33 | # 34 | # Data Refresh 35 | # This program relies on the SNMP agent on each node. SNMP is hard coded for a 5 second refresh rate 36 | # which means this tool inherits this level of granularity. 37 | # 38 | # References 39 | # https://net-snmp.svn.sourceforge.net/svnroot/net-snmp/trunk/net-snmp/python/README 40 | # http://www.ibm.com/developerworks/aix/library/au-netsnmpnipython/ 41 | # http://www.ibm.com/developerworks/aix/library/au-multiprocessing/ 42 | # 43 | # Return Codes 44 | # 00 .. completed successfully 45 | # 04 .. parameter error program aborted during invocation 46 | # 08 .. program started but xwindow size os too small for the UI to be displayed 47 | # 48 | 49 | import os, sys 50 | import math # only used for rounding up 51 | import threading # object based module to handle multithreading 52 | 53 | import netsnmp 54 | import locale # enabling curses display of unicode chars 55 | 56 | import traceback # tracing exceptions 57 | import datetime 58 | 59 | # modules and packages used for XML 60 | from xml.dom import minidom 61 | import xml.parsers.expat 62 | 63 | from time import strftime,gmtime, sleep 64 | import time 65 | 66 | import re # regex module used for whitelisting interface names 67 | 68 | from optparse import OptionParser # command line option parsing 69 | 70 | from multiprocessing import Process, Queue, current_process, Pipe, Manager 71 | 72 | 73 | import syslog # Used for pushing error msgs to the syslog 74 | 75 | import curses # ncurses interface 76 | 77 | from gtop_utils import convertBytes, issueCMD, oct2DateTime 78 | from gtop_iputils import SNMPsession, forwardDNS, reverseDNS, validIPv4 79 | 80 | 81 | 82 | class GLUSTERvol: 83 | def __init__(self, name=""): 84 | """ Initialise an instance of a new gluster volume """ 85 | 86 | 87 | 88 | self.name = name 89 | 90 | self.fmtdName = name if len(name)<17 else name[:15] + ">" 91 | 92 | self.fmtdName 93 | self.volType = "" 94 | self.numBricks = 0 95 | self.rawSize = 0 96 | self.usableSize = 0 97 | self.usedSize = 0 98 | self.freeSpace = 0 99 | self.graph =[] 100 | #self.highlight = False 101 | 102 | def printVol(self): 103 | """ DEBUG routine used, to show the volumes attributes """ 104 | 105 | print self.name 106 | print "\tBricks " + str(self.numBricks) 107 | print "\tType " + str(self.volType) 108 | print "\tRaw Space " + str(self.rawSize) 109 | print "\tUsable " + convertBytes(self.usableSize) + " (" + str(self.usableSize) + ")" 110 | print "\tUsed " + convertBytes(self.usedSize) + " (" + str(self.usedSize) + ")" 111 | print "\nBricks used by this volume" 112 | 113 | self.printBricks() 114 | 115 | 116 | def printBricks(self): 117 | """ DEBUG method to show the bricks assigned to a given volume """ 118 | 119 | for xl in self.graph: 120 | if xl.type == "Brick": 121 | print xl.options['remote-host'] + " " + \ 122 | xl.options['remote-subvolume'] + " " + \ 123 | "Size " + str(xl.size) + " " + \ 124 | "Used " + str(xl.used) 125 | 126 | def formatVol(self): 127 | """ format volume data for display on the UI """ 128 | 129 | volData = self.fmtdName.ljust(16) + " " + \ 130 | str(self.numBricks).rjust(4) + " " + \ 131 | volTypeShort[self.volType] + " " + \ 132 | convertBytes(self.usableSize).rjust(5) + " " + \ 133 | convertBytes(self.usedSize).rjust(5) + " " + \ 134 | convertBytes(self.freeSpace).rjust(5) 135 | 136 | if self.usableSize == 0: 137 | pctUsed = 0 138 | numBlocks = 1 139 | else: 140 | pctUsed = int((self.usedSize / float(self.usableSize)) *100) 141 | numBlocks = pctUsed / pctPerBlock 142 | 143 | if numBlocks < 1: 144 | numBlocks = 1 145 | 146 | # Use '>' initially so each 'block' will only be 1 char (encoding to unicode block occupies 147 | # 3 characters of text in the string, so using > keeps the formatting correct 148 | bar = ">"*numBlocks 149 | 150 | # Add the bar to the volume data, including a spacer added to the end 151 | volData = volData + " " + bar + " " + str(pctUsed) + "%" 152 | 153 | spacer = 79 - len(volData) 154 | volData += " "*spacer 155 | 156 | # once the spacer is added convert the > symbol to a unicode 'block' symbol 157 | volData = volData.replace('>',block.encode('utf_8')) 158 | 159 | return volData 160 | 161 | def updateVol(self): 162 | """ Update the volume space information, based on the usage of the underlying bricks 163 | and the types of translators used by the volume. The routine relies on the definition of the 164 | vol file and the current peer names being consistent. 165 | 166 | For example, if the cluster was formed using DNS names, and later uses IP - the vol file may 167 | still have entries there (remote-host field) referencing names; this routine attempts to use 168 | the current name (which would be IP based) to match against a brick which fails - result is 169 | the output shows 0b against all volumes! 170 | """ 171 | self.rawSize = 0 # reset raw size to recalculate based 172 | # on current observation 173 | 174 | for xl in self.graph: # look at this volumes Xlators 175 | 176 | if xl.type == "Brick": # if this Xlator is a brick just add 177 | self.rawSize += xl.size # to raw total of volume 178 | 179 | elif xl.type == "Replicated": 180 | usable=[] 181 | used=[] 182 | # this is a replica set, so we iterate over 183 | # brick subvolumes 184 | for brick in xl.subvolumes: 185 | if brick.size >= 0: 186 | usable.append(brick.size) 187 | 188 | used.append(brick.used) 189 | xl.size = max(usable) # all bricks in a replica should be of 190 | xl.used = max(used) # equal size, but taking the max incase any of the bricks 191 | # are offline at scan time. 192 | 193 | elif xl.type == "Distributed" or xl.type == "Striped": 194 | 195 | xl.size = 0 # reset the size/used, ready to recalculate 196 | xl.used = 0 # from current child subvolumes 197 | for child in xl.subvolumes: 198 | xl.size += child.size 199 | xl.used += child.used 200 | 201 | else: 202 | pass 203 | 204 | 205 | for xl in self.graph: # with the sizes calculated, propogate the 206 | if xl.parent == None: # top level XL objects values to the Volume 207 | self.usableSize = xl.size 208 | self.usedSize = xl.used 209 | self.freeSpace = self.usableSize - self.usedSize 210 | 211 | 212 | 213 | class Xlator(): 214 | def __init__(self, name=""): 215 | self.volname = "" 216 | self.name=name 217 | self.type="" 218 | self.parent=None 219 | self.subvolumes = [] 220 | self.options = {} 221 | self.size = 0 222 | self.used = 0 223 | 224 | 225 | class Cluster: 226 | 227 | def __init__(self): 228 | self.nodes = [] # list of peer node objects in the cluster 229 | self.evictNodes=[] # when nodes drop out of the main list catch them here for diagnostics 230 | self.nodeNames = [] # displayable node names in the cluster 231 | self.peerCount = 0 232 | self.processList = [] 233 | self.version = "" # version of glusterfs on the running host 234 | self.activeNodes = 0 235 | self.volumes=[] # list of volumes within the cluster 236 | self.brickXref={} # dict pointing a brick to the volume that owns it 237 | self.brick2Xlator={} # dict pointing a brick path to the relevant translator 238 | self.avgCPU = 0 239 | self.peakCPU = 0 240 | self.aggrNetIn = 0 241 | self.aggrNetOut = 0 242 | self.aggrDiskR = 0 243 | self.aggrDiskW = 0 244 | self.rawCapacity = 0 245 | self.usableCapacity = 0 246 | self.usedCapacity = 0 247 | self.freeCapacity = 0 248 | 249 | 250 | def addHost(self,hostName): 251 | """ Receive a node to add to the clusters node list """ 252 | 253 | 254 | newnode = GLUSTERhost(hostName=hostName) 255 | self.nodes.append(newnode) 256 | self.nodeNames.append(hostName) 257 | 258 | def validateServers(self,serverList): 259 | """ This function takes a list of servers (comma separated string), and attempts to 260 | validate the server name/IP and create glusterHOST objects for each valid server 261 | """ 262 | 263 | svrs = serverList.split(',') 264 | 265 | if svrs: 266 | for thisSvr in svrs: 267 | name2Add = serverOK(thisSvr) 268 | if name2Add: 269 | self.addHost(hostName=name2Add) 270 | else: 271 | print "Can't resolve supplied server name of " + thisSvr 272 | 273 | def getGlusterPeers(self): 274 | """ Look for the glusterfs peers directory to confirm whether gluster is installed, if so 275 | read the peer files to pick out the hostname, building a string of servers to push to 276 | the validateServers function 277 | """ 278 | 279 | peers = [] 280 | 281 | if os.path.exists(peersDir): # Does path exist? 282 | 283 | for nodeCfg in os.listdir(peersDir): # Yes, so process each file 284 | nodeCfgPath = os.path.join(peersDir,nodeCfg) 285 | for line in open(nodeCfgPath): # looking for the hostname keyword 286 | 287 | p = line.strip().split('=') 288 | if p[0] == 'hostname1': # to build the server list 289 | peers.append(p[1]) 290 | 291 | peers.append(os.getenv('HOSTNAME').split('.')[0]) # Add this host to the list 292 | self.peerCount = len(peers) 293 | peersList = ",".join(peers) 294 | self.validateServers(peersList) 295 | 296 | 297 | 298 | def getGlusterVols(self): 299 | """ Open this hosts gluster vol file to build volume objects and then 300 | attach them to the cluster object via a list 301 | 302 | This function is derived from the work Niels did on the 'lsgvt' script 303 | 304 | """ 305 | 306 | types = {'cluster/distribute' : 'Distributed', 307 | 'cluster/stripe' : 'Striped', 308 | 'cluster/replicate' : 'Replicated', 309 | 'protocol/client' : 'Brick'} 310 | 311 | #----------------------------------------------------------------------------------- 312 | # build the volume objects from the volfiles 313 | # output is 314 | # 1. a list of volume objects 315 | # 2. a dict pointing a given brick to a volume object that contains the brick 316 | #----------------------------------------------------------------------------------- 317 | for thisDir in os.listdir(volDir): 318 | volFile = os.path.join(volDir,thisDir,thisDir + "-fuse.vol") 319 | thisVol = GLUSTERvol(name=thisDir) 320 | self.volumes.append(thisVol) 321 | 322 | stack =[] # List to hold the translators found for this volume 323 | layout = [] # list holding data layout XL types e.g. distributed 324 | 325 | xl = None 326 | 327 | for line in open(volFile): 328 | words = line.split() 329 | 330 | if not words: continue 331 | 332 | if words[0] == 'volume': 333 | xl = Xlator() 334 | xl.volname = thisDir 335 | xl.name = words[1] 336 | 337 | elif words[0] == 'type': 338 | 339 | if words[1] in types.keys(): 340 | xl.type = types[words[1]] 341 | 342 | if xl.type == "Brick": 343 | thisVol.numBricks += 1 # increase the brick count 344 | 345 | else: # valid Xlator, so just add the type 346 | if xl.type in layout: # to layout list for propogation to 347 | pass # owning volume object 348 | else: 349 | layout.append(xl.type) 350 | 351 | elif words[0] == 'option': 352 | xl.options[words[1]] = words[2] 353 | 354 | elif words[0] == 'subvolumes': 355 | xl.subvolumes = words[1:] 356 | 357 | elif words[0] == 'end-volume': 358 | # only keep xlators that describe the volume layout 359 | if xl.type in types.values(): 360 | 361 | if xl.type == "Brick": 362 | # Grab this translators hostname and filesystem name (brick) 363 | thisHost = xl.options['remote-host'] 364 | thisPath = xl.options['remote-subvolume'] 365 | 366 | ptr = thisHost + ":" + thisPath 367 | 368 | # the gCluster object maintains a list of bricks to translators 369 | # used for file system size information tracking/calculations 370 | self.brickXref[ptr] = thisVol 371 | self.brick2Xlator[ptr] = xl 372 | 373 | stack.append(xl) 374 | xl = None 375 | 376 | # replace the subvolumes 'volname' by the xlator object 377 | for xl in stack: 378 | xl.subvolumes = [_xl for _xl in stack if _xl.name in xl.subvolumes] 379 | for subvol in xl.subvolumes: 380 | subvol.parent = xl 381 | 382 | 383 | thisVol.graph = list(stack) 384 | layout.reverse() # Add the volume type description to the 385 | thisVol.volType = '-'.join(layout) # volume object 386 | 387 | 388 | 389 | def getVersion(self): 390 | """ Simple function to retrieve the version of gluster running on the node """ 391 | 392 | versionInfo = issueCMD(cmd="glusterfsd --version") 393 | # First line of the output looks like this 394 | # glusterfs 3.3.0.5rhs built on Nov 8 2012 22:30:35 395 | 396 | self.version = versionInfo[0].split()[1] 397 | 398 | def updateActive(self): 399 | """ Maintain the cluster objects active node count based on the state of all 400 | the nodes in the cluster """ 401 | 402 | self.activeNodes = 0 403 | for node in self.nodes: 404 | if node.state == 'connected': 405 | self.activeNodes += 1 406 | 407 | def updateStats(self): 408 | """ Process the nodes in the cluster, to create an aggregate view of the 409 | clusters throughput for display in the information window (top 3 lines 410 | of the console """ 411 | 412 | cpuStats = [] 413 | totalNetIn = 0 414 | totalNetOut = 0 415 | totalDiskR = 0 416 | totalDiskW = 0 417 | 418 | # Process each node in the cluster 419 | for node in gCluster.nodes: 420 | cpuStats.append(node.cpuBusyPct) 421 | totalNetIn += node.netInRate 422 | totalNetOut += node.netOutRate 423 | totalDiskR += node.blocksReadAvg 424 | totalDiskW += node.blocksWriteAvg 425 | 426 | # Use the updated stats to derive averages and aggregates for the cluster 427 | if cpuStats: 428 | 429 | gCluster.avgCPU = int(sum(cpuStats)/len(cpuStats)) 430 | gCluster.peakCPU = max(cpuStats) 431 | gCluster.aggrNetIn = totalNetIn 432 | gCluster.aggrNetOut = totalNetOut 433 | gCluster.aggrDiskR = totalDiskR 434 | gCluster.aggrDiskW = totalDiskW 435 | 436 | else: 437 | 438 | gCluster.avgCPU = 0 439 | gCluster.peakCPU = 0 440 | gCluster.aggrNetIn = 0 441 | gCluster.aggrNetOut = 0 442 | gCluster.aggrDiskR = 0 443 | gCluster.aggrDiskW = 0 444 | 445 | pass 446 | 447 | def formatStats(self,prefix=""): 448 | """ Format the aggregate stats maintained in updateStats for display in batch mode """ 449 | 450 | if FORMAT == "readable": 451 | displayStats = prefix + " < ALL >".ljust(15) + " " \ 452 | + " " \ 453 | + str(self.avgCPU).rjust(3) + " " \ 454 | + " " \ 455 | + " " \ 456 | + " " \ 457 | + convertBytes(self.aggrNetIn).rjust(5) + " " \ 458 | + convertBytes(self.aggrNetOut).rjust(5) + " " \ 459 | + convertBytes(self.aggrDiskR*BLOCKSIZE).rjust(5) + " " \ 460 | + convertBytes(self.aggrDiskW*BLOCKSIZE).rjust(5) 461 | else: 462 | displayStats = prefix + "," + "," \ 463 | + "," \ 464 | + str(self.avgCPU) \ 465 | + "," \ 466 | + "," \ 467 | + "," \ 468 | + str(self.aggrNetIn) + "," \ 469 | + str(self.aggrNetOut) + "," \ 470 | + str(self.aggrDiskR*BLOCKSIZE) + "," \ 471 | + str(self.aggrDiskW*BLOCKSIZE) 472 | # 473 | return displayStats 474 | 475 | def SNMPcheck(self): 476 | """ Try to do a high level snmpwalk to see if snmp is listening """ 477 | 478 | servers = list(self.nodes) # Create a fresh copy of the list 479 | 480 | 481 | for node in servers: # Process each server 482 | target = node.hostName 483 | print "---> " + target + "", 484 | s = SNMPsession(destHost=target,community=SNMPCOMMUNITY) 485 | s.oid=netsnmp.Varbind('sysDescr') 486 | validSNMP = s.query() # Try a walk to see if SNMP responds 487 | 488 | if validSNMP: 489 | print "OK" 490 | else: 491 | print "not reachable over SNMP, dropping " + target + " from list" 492 | servers.remove(node) 493 | 494 | if len(servers) < len(self.nodes): # if there has been a change, update the 495 | self.nodes = list(servers) # cluster objects server list 496 | 497 | def dump(self): 498 | """ DEBUG routine to show what objects and attributes the cluster currently has """ 499 | 500 | if self.volumes: 501 | print str(len(self.volumes)) + " volumes found:" 502 | for volume in self.volumes: 503 | volume.printVol() 504 | 505 | for n in self.nodes: 506 | print n.hostName 507 | print n.state 508 | print n.timeStamp 509 | 510 | print "active nodes " + str(self.activeNodes) 511 | 512 | print "evicted nodes " 513 | for n in self.evictNodes: 514 | print n.hostName 515 | print n.state 516 | print n.errMsg 517 | 518 | 519 | 520 | def screenSize(): 521 | """ Routine which uses stty to determine the size of the console window, Only used in 522 | batch mode to trigger the headers to be re-displayed 523 | 524 | Requires - Linux stty command 525 | """ 526 | 527 | data = issueCMD('stty size') # returns a single string "y x" 528 | dimensions = data[0].split() # split it up 529 | y = int(dimensions[0]) 530 | x = int(dimensions[1]) 531 | 532 | return y,x 533 | 534 | 535 | 536 | 537 | class GLUSTERhost: 538 | """ Class for gluster nodes, holding the hosts data and containing the methods 539 | to populate and manage the data 540 | """ 541 | def __init__(self, hostName=None,state='unknown'): 542 | # Need to audit the variable declarations, some may not be used.. 543 | 544 | self.hostName = hostName # used 545 | 546 | # look at the hostname and determine how to format it for 547 | # display 548 | if '.' in self.hostName: 549 | # fqdn for hostname, so just extract host name 550 | self.fmtdName = self.hostName.split('.')[0] 551 | else: 552 | self.fmtdName = self.hostName 553 | 554 | if len(self.fmtdName) > 14: 555 | self.fmtdName = self.fmtdName[:14] + ">" 556 | else: 557 | self.fmtdName = self.fmtdName.ljust(15) 558 | 559 | 560 | self.hostActive = True # used 561 | self.state = state # used 562 | self.peers = 0 563 | #self.highlight = False 564 | self.reset() 565 | 566 | 567 | def reset(self): 568 | self.cpuSysPct = 0 569 | self.cpuWaitPct = 0 570 | self.cpuUserPct = 0 571 | self.cpuIdlePct = 0 572 | self.cpuBusyPct = 0 # Not USED 573 | self.cpuSys = 0 574 | self.cpuUser = 0 575 | self.cpuIdle = 0 576 | self.cpuWait = 0 577 | self.diffUser = 0 578 | self.diffSys = 0 579 | self.diffWait = 0 580 | self.diffIdle = 0 581 | self.memTotal = 0 # used 582 | self.memAvail = 0 # used 583 | self.memUsedPct = 0 # used 584 | self.swapTotal = 0 # used 585 | self.swapAvail = 0 # used 586 | self.swapUsedPct = 0 # used 587 | self.blocksReadAvg = 0 # used 588 | self.blocksWriteAvg = 0 # used 589 | self.netIn = 0 # used 590 | self.netInRate = 0 # used 591 | self.netOutRate = 0 # used 592 | self.netOut = 0 # used 593 | self.lcpuSys = 0 594 | self.lcpuUser = 0 595 | self.lcpuIdle = 0 596 | self.lcpuWait = 0 597 | self.lblocksRead = 0 # used 598 | self.lblocksWritten = 0 # used 599 | self.lnetIn = 0 # used 600 | self.lnetOut = 0 # used 601 | self.ltotalChange = 0 602 | self.nicList = [] # used 603 | self.brickfsOffsets = [] # used 604 | self.procCount = 0 # used 605 | self.errMsg = '' 606 | self.brickInfo = {} # used, size[0] and used[1] info for each brick 607 | self.ctdb = "." # used 608 | self.samba = "." # used 609 | self.nfs = "." # used 610 | self.selfHeal = "." # used 611 | self.georep = "." # used 612 | self.timeStamp = None # used 613 | 614 | return 615 | 616 | def getData(self): 617 | 618 | # Default is to assume snmp will work, and then turn off this state if 619 | # an error occurs 620 | self.hostActive = True 621 | 622 | s = SNMPsession(destHost=self.hostName,community=SNMPCOMMUNITY) 623 | 624 | if self.procCount == 0: # On 1st run, get the number of processors for this host 625 | s.oid=netsnmp.Varbind('hrDeviceType') 626 | # count hrDeviceProcessor occurances 627 | self.procCount = s.query().count('.1.3.6.1.2.1.25.3.1.3') 628 | 629 | #------------------------------------------------------------------------------------------------------ 630 | # Get the memory usage stats from the server, and add to the memory stats 631 | #------------------------------------------------------------------------------------------------------ 632 | s.oid = netsnmp.Varbind('memory') 633 | memInfo = s.query() 634 | 635 | if memInfo: # if this is empty, host has stopped answering 636 | self.swapTotal = memInfo[2] 637 | self.swapAvail = memInfo[3] 638 | self.memTotal = memInfo[4] 639 | self.memAvail = memInfo[5] 640 | self.swapUsedPct = 0 if int(self.swapTotal) == 0 else int(round((self.swapTotal - self.swapAvail)/float(self.swapTotal)*100)) 641 | self.memUsedPct = int(round((self.memTotal - self.memAvail)/float(self.memTotal)*100)) 642 | else: 643 | self.errMsg = "snmp query for memory failed" 644 | self.hostActive = False 645 | return 646 | 647 | #------------------------------------------------------------------------------------------------------ 648 | # Grab this systems current datetime 649 | #------------------------------------------------------------------------------------------------------ 650 | s.oid = netsnmp.Varbind('hrSystemDate') 651 | dateOct = s.query() # SNMP returns this as an octet string 652 | if dateOct: 653 | self.timeStamp = oct2DateTime(dateOct) 654 | #syslog.syslog("sent data to main process for " + self.timeStamp) 655 | #print self.timeStamp 656 | else: 657 | self.errMsg = "SNMP query for the datestamp - hrSystemDate - failed" 658 | self.hostActive = False 659 | return 660 | 661 | 662 | #------------------------------------------------------------------------------------------------------ 663 | # Process the systemStats table 664 | # NB. SNMP agent only polls every 5 seconds, current and lat have to be compared to calculate consumption 665 | # SNMP data not that reliable for CPU info, so need to add try/except clauses 666 | #------------------------------------------------------------------------------------------------------ 667 | 668 | s.oid = netsnmp.Varbind('systemStats') # Grab the whole stats table 669 | systemStats = s.query() 670 | 671 | if systemStats: # check we have data to process 672 | 673 | userDiff,sysDiff,waitDiff,idleDiff,totalDiff = 0,0,0,0,0 674 | 675 | if self.lcpuUser == 0: # First run clause 676 | self.lcpuUser = systemStats[11] 677 | else: 678 | 679 | try: 680 | userDiff = systemStats[11] - self.lcpuUser 681 | if userDiff == 0: 682 | userDiff = self.diffUser # use value from last poll 683 | else: 684 | self.diffUser = userDiff 685 | self.lcpuUser = systemStats[11] 686 | except IndexError: 687 | userDiff = self.diffUser 688 | 689 | 690 | if self.lcpuSys == 0: 691 | self.lcpuSys = systemStats[13] 692 | else: 693 | try: 694 | sysDiff = systemStats[13] - self.lcpuSys 695 | if sysDiff == 0: 696 | sysDiff = self.diffSys # use value from last poll 697 | else: 698 | self.diffSys = sysDiff 699 | self.lcpuSys = systemStats[13] 700 | except IndexError: 701 | sysDiff = self.diffSys 702 | 703 | 704 | if self.lcpuWait == 0: 705 | self.lcpuWait = systemStats[15] 706 | else: 707 | 708 | try: 709 | waitDiff = systemStats[15] - self.lcpuWait 710 | if waitDiff == 0: 711 | waitDiff = self.diffWait # use value from last poll 712 | else: 713 | self.diffWait = waitDiff 714 | self.lcpuWait = systemStats[15] 715 | except IndexError: 716 | waitDiff = self.diffWait 717 | 718 | if self.lcpuIdle == 0: 719 | self.lcpuIdle = systemStats[14] 720 | else: 721 | try: 722 | idleDiff = systemStats[14] - self.lcpuIdle 723 | if idleDiff == 0: 724 | idleDiff = self.diffIdle # use value from last poll 725 | else: 726 | self.diffIdle = idleDiff 727 | self.lcpuIdle = systemStats[14] 728 | except IndexError: 729 | idleDiff = self.diffIdle 730 | 731 | totalDiff = userDiff + sysDiff + waitDiff + idleDiff 732 | 733 | if totalDiff > 0: # Changes detected, updated counters 734 | self.cpuUserPct = (userDiff / ((float(refreshRate) * 100) * self.procCount))*100 735 | self.cpuSysPct = (sysDiff / ((float(refreshRate) * 100) * self.procCount))*100 736 | self.cpuWaitPct = (waitDiff / ((float(refreshRate) * 100) * self.procCount))*100 737 | self.cpuIdlePct = (idleDiff / ((float(refreshRate) * 100) * self.procCount))*100 738 | self.cpuBusyPct = int(self.cpuUserPct + self.cpuSysPct + self.cpuWaitPct) 739 | 740 | # After SNMP starts the numbers can be a little wierd. Catch them here and just reset to 0 741 | if self.cpuBusyPct > 100: 742 | self.cpuBusyPct = 0 743 | 744 | 745 | 746 | #---------------------------------------------------------------------------------------- 747 | # Process high level IO stats ---> FIXME Add a try and except for IndexError 748 | # SNMP block data is not available immediately 749 | # takes about 30 secs for snmp agent to respond with so scans within this time frame, 750 | # will not populate list items 18 and 19 - which would trigger the IndexError exception 751 | #---------------------------------------------------------------------------------------- 752 | if len(systemStats) >= 18: 753 | 754 | if self.lblocksRead == 0: 755 | self.lblocksRead= systemStats[19] 756 | else: 757 | blocksChanged = systemStats[19] - self.lblocksRead 758 | self.lblocksRead = systemStats[19] 759 | self.blocksReadAvg = blocksChanged / refreshRate 760 | 761 | if self.lblocksWritten == 0: 762 | self.lblocksWritten = systemStats[18] 763 | else: 764 | blocksChanged = systemStats[18] - self.lblocksWritten 765 | self.lblocksWritten = systemStats[18] 766 | self.blocksWriteAvg = blocksChanged / refreshRate 767 | 768 | 769 | 770 | else: 771 | self.errMsg = "SNMP query for system stats failed" 772 | self.hostActive = False 773 | return # Leave the getData thread 774 | 775 | 776 | #------------------------------------------------------------------------------------------------------ 777 | # Process the network stats data and add to this gluster host 778 | # Using interface table (iftable) - .1.3.6.1.2.1.2.2 779 | # nscache entry update for this is at .1.3.6.1.4.1.8072.1.5.3.1 concat with iftable oid 780 | # 781 | # You could therefore lower the 5 sec snmp update for if data using snmpset since this oid is managed 782 | # by within nscache table 783 | # i.e --> snmpset -c gluster -v2c 127.0.0.1 1.3.6.1.4.1.8072.1.5.3.1.2.1.3.6.1.2.1.2.2 i 1 784 | # if the stats look like they have wholes in (0b), when there should have been load, use the snmpset on 785 | # each node (could at this to the snmpd startup preferably the rc.local file 786 | #------------------------------------------------------------------------------------------------------ 787 | if not self.nicList: # Only run this the first time a host is polled 788 | # to get a list of NICs to use for the aggregation 789 | s.oid = netsnmp.Varbind('ifName') # Query ifName table, then look for phys interfaces 790 | interfaces = s.query() # we want to use based on the whiteList global var 791 | ctr = 0 792 | for ifname in interfaces: 793 | if re.match(whiteList,ifname): 794 | self.nicList.append(ctr) 795 | ctr += 1 796 | 797 | # Use 64bit network counters. -ve values will occur when the difference between current is at the start 798 | # of the 64 range, and last reading was at the end. This is caught and corrected 799 | s.oid = netsnmp.Varbind('ifHCInOctets') 800 | netInData = s.query() 801 | if netInData: 802 | 803 | netIn = sum([netInData[idx] for idx in self.nicList]) 804 | 805 | if self.lnetIn == 0: 806 | self.lnetIn = netIn 807 | self.netInRate = 0 808 | else: 809 | 810 | if netIn > self.lnetIn: 811 | bytesChanged = netIn - self.lnetIn 812 | else: 813 | 814 | # bytesChanged = (4294967296 - self.lnetIn) + netIn # for counter32 variant 815 | bytesChanged = (18446744073709600000 - self.lnetIn) + netIn 816 | 817 | self.lnetIn = netIn 818 | self.netInRate = bytesChanged / float(refreshRate) 819 | else: 820 | self.errMsg = "ERR: snmp query for memory net in data failed" 821 | self.hostActive = False 822 | return # Leave the getData thread 823 | 824 | # Using 64bit High capacity (HC) network counters - as above 825 | s.oid = netsnmp.Varbind('ifHCOutOctets') 826 | netOutData = s.query() 827 | if netOutData: 828 | 829 | netOut = sum([netOutData[idx] for idx in self.nicList]) 830 | 831 | if self.lnetOut == 0: 832 | self.lnetOut = netOut 833 | self.netOutRate = 0 834 | else: 835 | 836 | if netOut > self.lnetOut: 837 | bytesChanged = netOut - self.lnetOut 838 | else: 839 | bytesChanged = (18446744073709600000 - self.lnetOut) + netOut 840 | 841 | self.lnetOut = netOut 842 | self.netOutRate = bytesChanged / float(refreshRate) 843 | else: 844 | self.errMsg = "ERR: snmp query for net out data failed" 845 | self.hostActive = False 846 | return 847 | 848 | 849 | 850 | def getState(self): 851 | """ Find out whether key gluster processes are active. 852 | 853 | """ 854 | #print "getting state information" 855 | s = SNMPsession(destHost=self.hostName,community=SNMPCOMMUNITY) 856 | s.oid = netsnmp.Varbind('hrSWRunName') # .1.3.6.1.2.1.25.4.2.1.2 857 | processList = s.query() 858 | 859 | if processList: 860 | if 'glusterd' in processList: 861 | self.state = 'connected' 862 | else: 863 | self.state = 'disconnected' 864 | if 'ctdbd' in processList: 865 | self.ctdb = 'Y' 866 | else: 867 | self.ctdb = '.' 868 | if 'smbd' in processList: 869 | self.samba = 'Y' 870 | else: 871 | self.samba = '.' 872 | 873 | else: 874 | self.errMsg = "query for process list bombed" 875 | self.hostActive = False 876 | return 877 | 878 | # query of the hrSWRunName gives us the name of the process, but to look 879 | # for gluster nfs and gluster self heal pids we need the hrSWRunParameters 880 | 881 | s.oid = netsnmp.Varbind('hrSWRunParameters') # .1.3.6.1.2.1.25.4.2.1.5 882 | paramList = s.query() 883 | 884 | self.nfs = "." 885 | self.selfHeal = "." 886 | self.georep = "." 887 | 888 | if paramList: 889 | 890 | # Look at the list of param's for all the processes 891 | for parm in paramList: 892 | 893 | # Ignore items that are not string objects 894 | if isinstance(parm, basestring): 895 | 896 | if parm[:2] in ["-f", "-s"]: 897 | 898 | if "nfs" in parm: 899 | self.nfs = "Y" 900 | elif "glustershd" in parm: 901 | self.selfHeal = "Y" 902 | elif "gsyncd.py" in parm: 903 | self.georep = "Y" 904 | 905 | else: 906 | 907 | self.errMsg = "query for param list from process table failed" 908 | self.hostActive = False 909 | return 910 | 911 | 912 | 913 | def getDiskInfo(self, nameSpace): 914 | """ Use SNMP to get the current usage across mounted filesystems """ 915 | 916 | s = SNMPsession(destHost=self.hostName,community=SNMPCOMMUNITY) 917 | # first time through look through the filesystem 918 | if not self.brickfsOffsets: # descriptions, and if any match our bricks 919 | # record the offset in the brickfsOffset list 920 | 921 | s.oid = netsnmp.Varbind('hrStorageDescr') # .1.3.6.1.2.1.25.2.3.1.3 922 | filesystems = s.query() 923 | 924 | if filesystems: 925 | 926 | # Start at the end of the list and work backwards. Going forwards is problematic since 927 | # some systems don't report descr/size/used in sync. For example, in F17 descr and size 928 | # provide a field for Shared Memory, but used does not so using an index that starts at 929 | # the beginning results in index out of range conditions. 930 | ctr = -1 931 | for fs in reversed(filesystems): 932 | ptr = self.hostName + ":" + fs 933 | 934 | if nameSpace.gCluster.brickXref.has_key(ptr): 935 | self.brickfsOffsets.append([ctr,ptr]) 936 | 937 | self.brickInfo[ptr]=[0,0] 938 | ctr +=-1 939 | else: 940 | self.errMsg = "query to filesystems descr failed" 941 | self.hostActive = False 942 | return 943 | 944 | #print "diskinfo has found " + str(len(self.brickfsOffsets)) + " matching bricks" # DEBUG 945 | 946 | 947 | 948 | s.oid = netsnmp.Varbind('hrStorageSize') # .1.3.6.1.2.1.25.2.3.1.5 949 | 950 | sizeData = s.query() 951 | 952 | if sizeData: 953 | for ctr,ptr in self.brickfsOffsets: 954 | 955 | 956 | #if ctr <= len(sizeData): 957 | 958 | # The sizes returned by the query are in allocation units, which is 4k 959 | # so by multipling by 4096 gives bytes 960 | self.brickInfo[ptr][0] = int(sizeData[ctr]) * 4096 961 | 962 | else: 963 | self.errMsg = "query for filesystem size data failed" 964 | self.hostActive = False 965 | return 966 | 967 | 968 | s.oid = netsnmp.Varbind('hrStorageUsed') # .1.3.6.1.2.1.25.2.3.1.6 969 | usedData = s.query() 970 | 971 | if usedData: 972 | for ctr,ptr in self.brickfsOffsets: 973 | 974 | #if ctr<= len(usedData): 975 | self.brickInfo[ptr][1] = int(usedData[ctr]) * 4096 976 | 977 | 978 | else: 979 | self.hostActive = False 980 | self.errMsg = "query for filesystem used failed" 981 | return 982 | 983 | 984 | 985 | def formatData(self,prefix=""): 986 | """ Function to format a hosts statistics ready for display to the UI or stdout """ 987 | 988 | 989 | if interactiveMode: 990 | 991 | displayStats = nodeStatus[self.state].encode('utf-8') + " " + self.fmtdName + " " \ 992 | + str(self.procCount).rjust(3) + " " \ 993 | + str(self.cpuBusyPct).rjust(3) + " " \ 994 | + convertBytes((self.memTotal*1024)).rjust(5) + " " \ 995 | + str(self.memUsedPct).rjust(3) + " " \ 996 | + str(self.swapUsedPct).rjust(3) + " " \ 997 | + self.ctdb + " " \ 998 | + self.samba + " " \ 999 | + self.nfs + " " \ 1000 | + self.selfHeal + " " \ 1001 | + self.georep + " " \ 1002 | + convertBytes(self.netInRate).rjust(5) + " " \ 1003 | + convertBytes(self.netOutRate).rjust(5) + " " \ 1004 | + convertBytes(self.blocksReadAvg*BLOCKSIZE).rjust(5) + " " \ 1005 | + convertBytes(self.blocksWriteAvg*BLOCKSIZE).rjust(5) + " " 1006 | 1007 | else: 1008 | if FORMAT == 'readable': 1009 | displayStats = prefix + " " + self.fmtdName + " " \ 1010 | + str(self.procCount).rjust(3) + " " \ 1011 | + str(self.cpuBusyPct).rjust(3) + " " \ 1012 | + convertBytes((self.memTotal*1024)).rjust(5) + " " \ 1013 | + str(self.memUsedPct).rjust(3) + " " \ 1014 | + str(self.swapUsedPct).rjust(3) + " " \ 1015 | + convertBytes(self.netInRate).rjust(5) + " " \ 1016 | + convertBytes(self.netOutRate).rjust(5) + " " \ 1017 | + convertBytes(self.blocksReadAvg*BLOCKSIZE).rjust(5) + " " \ 1018 | + convertBytes(self.blocksWriteAvg*BLOCKSIZE).rjust(5) 1019 | else: 1020 | displayStats = prefix + "," + self.hostName + "," \ 1021 | + str(self.procCount) + "," \ 1022 | + str(self.cpuBusyPct) + "," \ 1023 | + str(self.memTotal*1024) + "," \ 1024 | + str(self.memUsedPct) + "," \ 1025 | + str(self.swapUsedPct) + "," \ 1026 | + str(self.netInRate) + "," \ 1027 | + str(self.netOutRate) + "," \ 1028 | + str(self.blocksReadAvg*BLOCKSIZE) + "," \ 1029 | + str(self.blocksWriteAvg*BLOCKSIZE) 1030 | 1031 | return displayStats 1032 | 1033 | 1034 | 1035 | 1036 | def printHeader(headerType='readable'): 1037 | 1038 | if headerType == "readable": 1039 | global screenX, ScreenY 1040 | screenY,screenX = screenSize() # test the screen size again incase window is resized 1041 | hdrs=[] 1042 | 1043 | hdrs.append(" CPU Memory % Network AVG Disk I/O AVG") 1044 | hdrs.append(" Time Gluster Node C/T % RAM Real Swap In Out Reads Writes") 1045 | hdrs.append("-------- --------------- --- --- ----- ----|---- ------|------ ------|------") 1046 | 1047 | for line in hdrs: 1048 | print line 1049 | 1050 | triggerRow = screenY - len(hdrs) 1051 | 1052 | return triggerRow 1053 | 1054 | else: 1055 | print "TimeStamp,GlusterNode,Cores,CPU%,RAM,Real%,Swap%,NetInBytes,NetOutBytes,DiskReadAVG,DiskWriteAVG" 1056 | 1057 | 1058 | def serverOK(server): 1059 | """ check a given name/ip is ok to use, if not return blank """ 1060 | 1061 | result = '' 1062 | 1063 | if validIPv4(server): # format is IPv4, so 1064 | dnsName = reverseDNS(server) # try and get a friendly DNS name and use that 1065 | if dnsName: 1066 | result = dnsName 1067 | else: # but if that fails,. just use the valid IPv4 1068 | result = server 1069 | 1070 | elif forwardDNS(server): # svr is not a valid IPv4 name, so assume it is a name and check DNS 1071 | result = server 1072 | 1073 | else: 1074 | pass 1075 | 1076 | return result # return blank, server name or IP 1077 | 1078 | 1079 | def initScreen(): 1080 | 1081 | screen = curses.initscr() 1082 | #handleColors = curses.has_colors() 1083 | 1084 | curses.start_color() 1085 | curses.use_default_colors() 1086 | 1087 | screen.nodelay(1) # keyscan is non-blocking 1088 | curses.noecho() # Turn off echo to screen to allow, so keypresses can be captured 1089 | curses.cbreak() # Allow keys to be used instantly, without pressing ENTER 1090 | screen.keypad(1) # Keypad and arrow keys enabled 1091 | curses.curs_set(0) # Make cursor invisible 1092 | return screen 1093 | 1094 | 1095 | def resetScreen(screen): 1096 | """ Return the console to a known state """ 1097 | curses.nocbreak() 1098 | screen.keypad(0) 1099 | curses.echo() 1100 | curses.curs_set(2) # turn cursor back on 1101 | curses.endwin() # end window session 1102 | 1103 | def processConfigFile(fileName): 1104 | """ function that looks for a config file in the users home directory to build 1105 | server groups and set environment variables up 1106 | 1107 | Returns a list called variables, where each item is a variable assignment 1108 | a dict indexed by a group name, containing a string of comma separated names 1109 | 1110 | """ 1111 | 1112 | 1113 | serverGroups={} 1114 | variables = [] 1115 | 1116 | if os.path.exists(configFile): 1117 | try: 1118 | # Process the xml config file building a DOM structure to parse 1119 | # check if config file exists, before trying to use it 1120 | xmldoc = minidom.parse(configFile) 1121 | 1122 | # Process any parameter overrides from the config file 1123 | parmList = xmldoc.getElementsByTagName('parm') 1124 | 1125 | for parm in parmList: 1126 | 1127 | varName = str(parm.attributes.keys()[0]) 1128 | varValue = parm.attributes[varName].value 1129 | 1130 | if varValue.isdigit(): 1131 | varValue = int(varValue) 1132 | else: 1133 | varValue = "'"+ varValue + "'" 1134 | 1135 | varCmd = varName + " = " + str(varValue) 1136 | variables.append(varCmd) 1137 | 1138 | 1139 | # From the DOM, create a list of group objects 1140 | groupList = xmldoc.getElementsByTagName('group') 1141 | 1142 | # Process each group stanza 1143 | for group in groupList: 1144 | 1145 | groupName = str(group.attributes["name"].value) 1146 | 1147 | s = [] 1148 | serverList = group.getElementsByTagName('server') 1149 | 1150 | for server in serverList: 1151 | serverName = str(server.attributes['name'].value) 1152 | s.append(serverName) 1153 | 1154 | serverGroups[groupName] = ",".join(s) 1155 | 1156 | except xml.parsers.expat.ExpatError, e: 1157 | print "ERR: Config file has errors, please investigate\n" 1158 | print "XML ERROR - " + str(e) + "\n" 1159 | 1160 | else: 1161 | 1162 | # User has asked for a config file based run, but no config file exists 1163 | print "ERR: configuration file (" + configFile + ") not present, -g can not be used" 1164 | 1165 | return variables, serverGroups 1166 | 1167 | 1168 | def getGroupServers(targetGroup): 1169 | """ Look for a config file (xml) in the current directory, and return a list of 1170 | servers that correspond to the required group name 1171 | """ 1172 | 1173 | # define a list to hold the servers found in the config file for a given group 1174 | s = [] 1175 | 1176 | if os.path.exists(configFile): 1177 | 1178 | try: 1179 | # Process the xml config file building a DOM structure to parse 1180 | # check if config file exists, before trying to use it 1181 | #if os.path.exists( 1182 | xmldoc = minidom.parse(configFile) 1183 | 1184 | # From the DOM, create a list of group objects 1185 | groupList = xmldoc.getElementsByTagName('group') 1186 | 1187 | # Process each group stanza 1188 | for group in groupList: 1189 | 1190 | groupName = group.attributes["name"].value 1191 | if groupName == targetGroup: 1192 | 1193 | # found the right group, time to process the server entries 1194 | serverList = group.getElementsByTagName('server') 1195 | for server in serverList: 1196 | serverName = server.attributes['name'].value 1197 | s.append(serverName) 1198 | #print "Owning Group " + groupName + " - server " + serverName # DEBUG 1199 | break 1200 | 1201 | 1202 | 1203 | except xml.parsers.expat.ExpatError, e: 1204 | print "ERR: Config file has errors, please investigate\n" 1205 | print "XML ERROR - " + str(e) + "\n" 1206 | 1207 | else: 1208 | 1209 | # User has asked for a config file based run, but no config file exists 1210 | print "ERR: configuration file (" + configFile + ") not present, -g can not be used" 1211 | 1212 | serverString = ",".join(s) 1213 | 1214 | return serverString 1215 | 1216 | def worker(connection,nameSpace,hostName): 1217 | """ Process forked by the main process to just perform the data gathering 1218 | Once the data is collected from SNMP the resulting object is passed back 1219 | on the pipe to the main process. 1220 | """ 1221 | 1222 | thisHost = GLUSTERhost(hostName=hostName) 1223 | 1224 | while True: 1225 | try: 1226 | 1227 | # Get the system stats for this host 1228 | thisHost.getData() 1229 | 1230 | if thisHost.hostActive: 1231 | 1232 | if nameSpace.interactiveMode: 1233 | 1234 | # Get the filesystem data 1235 | thisHost.getDiskInfo(nameSpace) 1236 | 1237 | if thisHost.hostActive: 1238 | 1239 | # Get the status of the nodes (look for key processes on the node) 1240 | thisHost.getState() 1241 | 1242 | # if snmp fails in any of the above steps the hostActive flag is false, so 1243 | # change the nodes state and reset it's stats until snmp starts working again 1244 | if not thisHost.hostActive: 1245 | thisHost.state = 'unknown' 1246 | thisHost.reset() 1247 | pass 1248 | 1249 | dataFeed = thisHost 1250 | connection.send(dataFeed) 1251 | #syslog.syslog("sent data to main process for " + thisHost.hostName) # DEBUG 1252 | sleep(refreshRate) 1253 | pass 1254 | 1255 | 1256 | except KeyboardInterrupt,e: 1257 | break 1258 | 1259 | except: 1260 | break 1261 | 1262 | sys.exit(12) 1263 | 1264 | def refreshInfoWindow(win): 1265 | """ Routine to refresh the contents of the info window based on the aggregated 1266 | metrics held by the cluster object (which is fed by the node and volume objects) """ 1267 | 1268 | timestamps = [] 1269 | for node in gCluster.nodes: 1270 | if node.timeStamp is not None: 1271 | timestamps.append(node.timeStamp) 1272 | 1273 | if len(timestamps) > 0: 1274 | timestamps.sort() 1275 | # Grab the lowest and highest timestamps across the nodes 1276 | minTime = timestamps[0] 1277 | maxTime = timestamps[-1] 1278 | 1279 | delta = maxTime - minTime 1280 | deltaSecs = delta.days*86400+delta.seconds 1281 | 1282 | # Put a ceiling on the max secs of clock skew 1283 | if deltaSecs > 999: 1284 | deltaSecs = 999 1285 | 1286 | else: 1287 | deltaSecs = 0 1288 | 1289 | infoLine1_p1 = "gtop - " + gCluster.version[:11] + " " + \ 1290 | str(gCluster.peerCount).rjust(3) + " nodes," 1291 | 1292 | infoLine1_p2 = " active" + \ 1293 | " CPU%:" + str(gCluster.avgCPU).rjust(3) + " Avg," + \ 1294 | str(gCluster.peakCPU).rjust(3) + " peak" + " Skew:" + \ 1295 | str(deltaSecs).rjust(3) + "s " + \ 1296 | strftime(timeTemplate, gmtime()) 1297 | 1298 | infoLine2 = "Activity: Network:" + convertBytes(gCluster.aggrNetIn).rjust(5) + " in," + \ 1299 | convertBytes(gCluster.aggrNetOut).rjust(5) + " out" + \ 1300 | " Disk:" + convertBytes(gCluster.aggrDiskR*BLOCKSIZE).rjust(5) + " reads," + \ 1301 | convertBytes(gCluster.aggrDiskW*BLOCKSIZE).rjust(5) + " writes " 1302 | 1303 | infoLine3 = "Storage:" + str(len(gCluster.volumes)).rjust(2) + " volumes," + \ 1304 | str(len(gCluster.brickXref)).rjust(3) + " bricks / " + \ 1305 | convertBytes(gCluster.rawCapacity).rjust(5) + " raw," + \ 1306 | convertBytes(gCluster.usableCapacity).rjust(5) + " usable," + \ 1307 | convertBytes(gCluster.usedCapacity).rjust(5) + " used," + \ 1308 | convertBytes(gCluster.freeCapacity).rjust(5) + " free" 1309 | 1310 | win.addstr(0,0,infoLine1_p1) 1311 | 1312 | # If the active node count is not right, highlight the value on screen 1313 | if gCluster.activeNodes != gCluster.peerCount: 1314 | win.addstr(str(gCluster.activeNodes).rjust(3),curses.A_STANDOUT) 1315 | else: 1316 | win.addstr(str(gCluster.activeNodes).rjust(3)) 1317 | 1318 | win.addstr(infoLine1_p2) 1319 | 1320 | win.addstr(1,0,infoLine2) 1321 | win.addstr(2,0,infoLine3) 1322 | win.noutrefresh() 1323 | 1324 | return 1325 | 1326 | def refreshNodePad(pad,dh,vh,cursor,toprow): 1327 | """ Function to display the node data to the screen """ 1328 | 1329 | ypos = 0 1330 | tgt = cursor + toprow 1331 | for node in gCluster.nodes: 1332 | 1333 | # format this nodes output and display 1334 | nodeData = node.formatData() 1335 | 1336 | if ypos == tgt: 1337 | pad.addstr(ypos,0,nodeData,rowHighlight) 1338 | else: 1339 | pad.addstr(ypos,0,nodeData) 1340 | 1341 | 1342 | ypos += 1 1343 | 1344 | pad.noutrefresh(toprow,0,vh+5,0,vh+5+dh,80) 1345 | 1346 | 1347 | 1348 | def refreshVolumePad(pad,vh,cursor,toprow): 1349 | """ function to write out the volume data to a given window area on the screen """ 1350 | 1351 | ypos = 0 1352 | tgt = cursor + toprow 1353 | 1354 | for volume in gCluster.volumes: 1355 | 1356 | volData = volume.formatVol() 1357 | if ypos == tgt: 1358 | pad.addstr(ypos,0,volData,rowHighlight) 1359 | else: 1360 | pad.addstr(ypos,0,volData) 1361 | 1362 | ypos +=1 1363 | 1364 | 1365 | pad.noutrefresh(toprow,0,4,0,vh+2,80) 1366 | 1367 | return 1368 | 1369 | def getWindowSizes(screen): 1370 | """ use the volume and nodes counts to determine the volume and data window sizes """ 1371 | 1372 | # get the dimensions of the screen, and adjust height by 3 due to the fixed info area 1373 | screenh,screenw = screen.getmaxyx() 1374 | screenh -=3 1375 | 1376 | numOfNodes = len(gCluster.nodes) 1377 | numOfVolumes = len(gCluster.volumes) 1378 | 1379 | volHeight = VolumeHeight = int(screenh * (VOLUMEAREAPCT/float(100))) 1380 | maxDataHeight = int(screenh * (NODEAREAPCT/float(100))) 1381 | 1382 | 1383 | if numOfNodes < maxDataHeight: 1384 | freeLines = maxDataHeight - numOfNodes 1385 | else: 1386 | freeLines = 0 1387 | 1388 | # Add 1 to number of volumes to account for the headings line 1389 | volLinesNeeded = (numOfVolumes + 1) - VolumeHeight 1390 | if volLinesNeeded > 0 and freeLines > 0: 1391 | for loop in range(freeLines): 1392 | volHeight += 1 1393 | volLinesNeeded -= 1 1394 | if volLinesNeeded < 0: 1395 | break 1396 | 1397 | dataHeight = screenh - (infoHeight + volHeight) 1398 | 1399 | return volHeight, dataHeight 1400 | 1401 | def main(gCluster): 1402 | """ Main processing and Contol loop 1403 | """ 1404 | # Point to the mibs directory (Fedora, RHEL6) 1405 | os.environ['MIBDIRS'] = '/usr/share/snmp/mibs' 1406 | 1407 | # define a flag variable set when exception trapped to provide better diagnostics 1408 | errorType = "" 1409 | 1410 | # flag used for diagnostics 1411 | dump=False 1412 | 1413 | # Setup server process (another pid) for shared objects between processes 1414 | mgr = Manager() 1415 | 1416 | # Create a namespace that parent objects can be attached to for visibility in the child processes 1417 | ns = mgr.Namespace() 1418 | ns.gCluster = gCluster 1419 | ns.interactiveMode = interactiveMode 1420 | 1421 | for node in gCluster.nodes: 1422 | 1423 | parentCon, childCon = Pipe() 1424 | node.parentCon, node.childCon = parentCon, childCon 1425 | 1426 | 1427 | p = Process(target=worker, args=(node.childCon,ns,node.hostName)) 1428 | 1429 | p.daemon=True 1430 | p.start() 1431 | 1432 | #syslog.syslog("gtop has forked process" + str(p.pid)) # DEBUG 1433 | gCluster.processList.append(p) 1434 | 1435 | 1436 | 1437 | 1438 | if interactiveMode: 1439 | # Define a flag to describe the error - debugging only 1440 | errorType = "" 1441 | 1442 | # set locale up, so the unicode block/arrow symbols can be used in the UI 1443 | locale.setlocale(locale.LC_ALL,"") 1444 | 1445 | stdscr = initScreen() 1446 | vh,dh = getWindowSizes(stdscr) 1447 | 1448 | # used to indicate a row that should be highlighted 1449 | volumeCursor, nodeCursor = 0, 0 1450 | 1451 | 1452 | # define the variables used to toggle the sort sequence within data and volume windows 1453 | sortVolName = True 1454 | sortVolFree = False 1455 | sortVolSize = False 1456 | sortNodeName = True 1457 | sortNodeCPU = False 1458 | sortNodeNetIn = False 1459 | sortNodeNetOut = False 1460 | sortNodeDiskR = False 1461 | sortNodeDiskW = False 1462 | 1463 | infoWindow = curses.newwin(infoHeight,80,0,0) 1464 | volumePad = curses.newpad(MAXVOLS,80) 1465 | 1466 | nodePad = curses.newpad(MAXNODES,80) 1467 | 1468 | pVolTop = 0 1469 | pNodeTop = 0 1470 | refreshInfoWindow(infoWindow) 1471 | 1472 | 1473 | stdscr.addstr(3,0,"Volume Bricks Type Size Used Free Volume Usage ",titleHighlight) 1474 | stdscr.addstr(5,0,"Please wait...",curses.A_BLINK) 1475 | 1476 | stdscr.addstr(vh+3,0," CPU Memory % Daemons Network Disk I/O") 1477 | stdscr.addstr(vh+4,0,"S Gluster Node C/T % RAM Real|Swap C-S-N-H-G In | Out Reads | Writes",titleHighlight) 1478 | 1479 | stdscr.noutrefresh() 1480 | 1481 | 1482 | # flush the updates to the screen 1483 | curses.doupdate() 1484 | #exit(0) # DEBUG 1485 | else: 1486 | 1487 | # Set "batch mode" counters and write column headers to stdout 1488 | rowNum = 1 1489 | if showHeaders: 1490 | triggerRow = printHeader() 1491 | else: 1492 | printHeader(headerType='raw') 1493 | 1494 | startTime = int(time.time()) 1495 | 1496 | nodeRcvd = [] 1497 | 1498 | while True: 1499 | try: 1500 | 1501 | for node in gCluster.nodes: 1502 | 1503 | # Check if there is anything ready from the worker processes associated with each node 1504 | if node.parentCon.poll(): 1505 | 1506 | #syslog.syslog("data received on connection for " + node.hostName) 1507 | 1508 | # We have a object passed from subprocess, add this nodes name to a list to 1509 | # signify it's been seen. if there are slower processes we could get mutiple 1510 | # receives from the same host - but we should only count the most recent which is why a 1511 | # list not counter is used 1512 | if node.hostName not in nodeRcvd: 1513 | nodeRcvd.append(node.hostName) 1514 | 1515 | 1516 | # Grab the workers node object 1517 | updatedNode = node.parentCon.recv() 1518 | 1519 | # Appy the workers node attributes to the local copy of the host object 1520 | node.__dict__.update(updatedNode.__dict__) 1521 | 1522 | # Process the brick information to update the local xlator objects ready for roll-up into volume stats 1523 | for brickName in node.brickInfo: 1524 | xl = gCluster.brick2Xlator[brickName] 1525 | xl.size = node.brickInfo[brickName][0] 1526 | xl.used = node.brickInfo[brickName][1] 1527 | 1528 | if len(nodeRcvd) == len(gCluster.nodes): 1529 | 1530 | # reset the 'node seen' list 1531 | nodeRcvd = [] 1532 | 1533 | # Handle the output - UI or stdout 1534 | 1535 | if interactiveMode: 1536 | 1537 | #----------------------------------------------------------------------------------- 1538 | # Update the screen 1539 | #----------------------------------------------------------------------------------- 1540 | refreshNodePad(nodePad,dh,vh,nodeCursor,pNodeTop) 1541 | 1542 | # process the bricks/volumes to update roll-up stats 1543 | raw = 0 1544 | usable = 0 1545 | used = 0 1546 | for volume in gCluster.volumes: 1547 | volume.updateVol() 1548 | raw += volume.rawSize 1549 | usable += volume.usableSize 1550 | used += volume.usedSize 1551 | 1552 | refreshVolumePad(volumePad,vh,volumeCursor,pVolTop) 1553 | 1554 | # Set the high level capacity information for the whole cluster 1555 | gCluster.rawCapacity = raw 1556 | gCluster.usableCapacity = usable 1557 | gCluster.usedCapacity = used 1558 | gCluster.freeCapacity = usable - used 1559 | 1560 | # Update the rollup stats based on current node metrics 1561 | gCluster.updateStats() 1562 | 1563 | # Manage the active node count 1564 | gCluster.updateActive() 1565 | 1566 | refreshInfoWindow(infoWindow) 1567 | 1568 | # flush all screen changes to the physical screen 1569 | curses.doupdate() 1570 | 1571 | else: 1572 | 1573 | #----------------------------------------------------------------------------------- 1574 | # Send output to stdout 1575 | #----------------------------------------------------------------------------------- 1576 | tstamp = strftime(timeTemplate, gmtime()) 1577 | if timeStamps: 1578 | prefix = tstamp 1579 | else: 1580 | prefix = "" 1581 | 1582 | if BGMODE in ['summary','all']: 1583 | gCluster.updateStats() 1584 | displayStats = gCluster.formatStats(prefix) 1585 | print displayStats 1586 | if showHeaders: 1587 | rowNum += 1 1588 | 1589 | if BGMODE in ['nodes','all']: 1590 | 1591 | for node in gCluster.nodes: 1592 | 1593 | displayStats = node.formatData(prefix) 1594 | print displayStats 1595 | if showHeaders: 1596 | rowNum += 1 1597 | 1598 | if showHeaders: # if headers are needed then 1599 | if rowNum > triggerRow: 1600 | triggerRow = printHeader() 1601 | rowNum = 1 1602 | 1603 | pass 1604 | 1605 | 1606 | # In between sample refreshes allow the user to sort the node and volume data 1607 | if interactiveMode: 1608 | keypress = stdscr.getch() 1609 | 1610 | # check for user selecting q for quit 1611 | if keypress in [ord('q'),ord('Q')]: 1612 | break 1613 | 1614 | # DOWN arrow Pressed 1615 | elif keypress == 258: 1616 | # check if I'm at the bottom of the list already? 1617 | if (volumeCursor + pVolTop) < (len(gCluster.volumes) -1): 1618 | 1619 | # If at the bottom of the volume area, change the pad 1620 | # ofset 1621 | if volumeCursor == (vh -2): 1622 | pVolTop += 1 1623 | else: 1624 | # just move the highlighted row 1625 | volumeCursor +=1 1626 | 1627 | refreshVolumePad(volumePad,vh,volumeCursor,pVolTop) 1628 | volumePad.refresh(pVolTop,0,4,0,vh,80) 1629 | 1630 | # UP arrow Pressed 1631 | elif keypress == 259: 1632 | 1633 | if (volumeCursor + pVolTop) > 0: 1634 | if volumeCursor == 0: 1635 | pVolTop -=1 1636 | else: 1637 | volumeCursor -= 1 1638 | 1639 | refreshVolumePad(volumePad,vh,volumeCursor,pVolTop) 1640 | volumePad.refresh(pVolTop,0,4,0,vh,80) 1641 | 1642 | # '+' pressed 1643 | elif keypress == 43: 1644 | if (nodeCursor + pNodeTop) < (len(gCluster.nodes) -1): 1645 | if nodeCursor == dh : 1646 | pNodeTop += 1 1647 | else: 1648 | 1649 | nodeCursor +=1 1650 | 1651 | refreshNodePad(nodePad,dh,vh,nodeCursor,pNodeTop) 1652 | nodePad.refresh(pNodeTop,0,vh+5,0,vh+5+dh,80) 1653 | 1654 | # '-' pressed - CHANGES 1655 | elif keypress == 45: 1656 | if (nodeCursor + pNodeTop) > 0: 1657 | if nodeCursor == 0: 1658 | pNodeTop -= 1 1659 | else: 1660 | nodeCursor -= 1 1661 | 1662 | refreshNodePad(nodePad,dh,vh,nodeCursor,pNodeTop) 1663 | nodePad.refresh(pNodeTop,0,vh+5,0,vh+5+dh,80) 1664 | 1665 | 1666 | elif keypress in [ord('v'),ord('V')]: 1667 | sortVolName = not sortVolName 1668 | if sortVolName: 1669 | gCluster.volumes.sort(key=lambda volume: volume.name) 1670 | else: 1671 | gCluster.volumes.sort(key=lambda volume: volume.name,reverse=True) 1672 | 1673 | volumeCursor = 0 # reset highlight 1674 | pVolTop = 0 # reset the pad offset 1675 | refreshVolumePad(volumePad,vh,volumeCursor,pVolTop) 1676 | volumePad.refresh(pVolTop,0,4,0,vh,80) 1677 | 1678 | elif keypress in [ord('s'),ord('S')]: 1679 | sortVolSize = not sortVolSize 1680 | if sortVolSize: 1681 | gCluster.volumes.sort(key=lambda volume: volume.usableSize) 1682 | else: 1683 | gCluster.volumes.sort(key=lambda volume: volume.usableSize,reverse=True) 1684 | 1685 | volumeCursor = 0 # reset highlight 1686 | pVolTop = 0 1687 | refreshVolumePad(volumePad,vh,volumeCursor,pVolTop) 1688 | volumePad.refresh(pVolTop,0,4,0,vh,80) 1689 | 1690 | elif keypress in [ord('f'),ord('F')]: 1691 | sortVolFree = not sortVolFree 1692 | if sortVolFree: 1693 | gCluster.volumes.sort(key=lambda volume: volume.freeSpace) 1694 | else: 1695 | gCluster.volumes.sort(key=lambda volume: volume.freeSpace,reverse=True) 1696 | 1697 | volumeCursor = 0 # reset highlight etc 1698 | pVolTop = 0 1699 | refreshVolumePad(volumePad,vh,volumeCursor,pVolTop) 1700 | volumePad.refresh(pVolTop,0,4,0,vh,80) 1701 | 1702 | elif keypress in [ord('n'),ord('N')]: 1703 | sortNodeName = not sortNodeName 1704 | if sortNodeName: 1705 | gCluster.nodes.sort(key=lambda node: node.hostName) 1706 | else: 1707 | gCluster.nodes.sort(key=lambda node: node.hostName,reverse=True) 1708 | 1709 | pNodeTop = 0 1710 | nodeCursor = 0 1711 | 1712 | refreshNodePad(nodePad,dh,vh,nodeCursor,pNodeTop) 1713 | nodePad.refresh(0,0,vh+5,0,vh+5+dh,80) 1714 | 1715 | elif keypress in [ord('c'),ord('C')]: 1716 | sortNodeCPU = not sortNodeCPU 1717 | if sortNodeCPU: 1718 | gCluster.nodes.sort(key=lambda node: node.cpuBusyPct) 1719 | else: 1720 | gCluster.nodes.sort(key=lambda node: node.cpuBusyPct,reverse=True) 1721 | 1722 | pNodeTop = 0 1723 | nodeCursor = 0 1724 | 1725 | refreshNodePad(nodePad,dh,vh,nodeCursor,pNodeTop) 1726 | nodePad.refresh(0,0,vh+5,0,vh+5+dh,80) 1727 | 1728 | elif keypress in [ord('i'),ord('I')]: 1729 | sortNodeNetIn = not sortNodeNetIn 1730 | if sortNodeNetIn: 1731 | gCluster.nodes.sort(key=lambda node: node.netInRate) 1732 | else: 1733 | gCluster.nodes.sort(key=lambda node: node.netInRate,reverse=True) 1734 | 1735 | pNodeTop = 0 1736 | nodeCursor = 0 1737 | 1738 | refreshNodePad(nodePad,dh,vh,nodeCursor,pNodeTop) 1739 | nodePad.refresh(0,0,vh+5,0,vh+5+dh,80) 1740 | 1741 | elif keypress in [ord('o'),ord('O')]: 1742 | sortNodeNetOut = not sortNodeNetOut 1743 | if sortNodeNetOut: 1744 | gCluster.nodes.sort(key=lambda node: node.netOutRate) 1745 | else: 1746 | gCluster.nodes.sort(key=lambda node: node.netOutRate,reverse=True) 1747 | 1748 | pNodeTop = 0 1749 | nodeCursor = 0 1750 | 1751 | refreshNodePad(nodePad,dh,vh,nodeCursor,pNodeTop) 1752 | nodePad.refresh(0,0,vh+5,0,vh+5+dh,80) 1753 | 1754 | elif keypress in [ord('r'),ord('R')]: 1755 | sortNodeDiskR = not sortNodeDiskR 1756 | if sortNodeDiskR: 1757 | gCluster.nodes.sort(key=lambda node: node.blocksReadAvg) 1758 | else: 1759 | gCluster.nodes.sort(key=lambda node: node.blocksReadAvg,reverse=True) 1760 | 1761 | pNodeTop = 0 1762 | nodeCursor = 0 1763 | 1764 | refreshNodePad(nodePad,dh,vh,nodeCursor,pNodeTop) 1765 | nodePad.refresh(0,0,vh+5,0,vh+5+dh,80) 1766 | 1767 | elif keypress in [ord('w'),ord('W')]: 1768 | sortNodeDiskW = not sortNodeDiskW 1769 | if sortNodeDiskW: 1770 | gCluster.nodes.sort(key=lambda node: node.blocksWriteAvg) 1771 | else: 1772 | gCluster.nodes.sort(key=lambda node: node.blocksWriteAvg,reverse=True) 1773 | 1774 | pNodeTop = 0 1775 | nodeCursor = 0 1776 | 1777 | refreshNodePad(nodePad,dh,vh,nodeCursor,pNodeTop) 1778 | nodePad.refresh(0,0,vh+5,0,vh+5+dh,80) 1779 | 1780 | 1781 | elif keypress == curses.KEY_RESIZE: 1782 | # user has attempted to resize the window, which is not supported (yet!) 1783 | # so just tell them they're naughty and exit ;o) 1784 | errorType = "resize" 1785 | break 1786 | 1787 | elif keypress in [ord('d'),ord('D')]: 1788 | errorType="dump" 1789 | break 1790 | 1791 | sleep(0.1) # Pause for a 1/10 second 1792 | 1793 | except KeyboardInterrupt: # Catch CTRL-C from the user to leave the program 1794 | break 1795 | 1796 | except curses.error, e: # Catch UI problems 1797 | 1798 | errorType = "curses" 1799 | break 1800 | 1801 | except Exception, e: # DEBUG - Something bad happened, so dump the contents of the 1802 | errorType = "unknown" 1803 | dump = True 1804 | break 1805 | 1806 | if interactiveMode: 1807 | del nodePad 1808 | del infoWindow 1809 | del volumePad 1810 | resetScreen(stdscr) 1811 | 1812 | 1813 | # Clear up the forked processes 1814 | for p in gCluster.processList: 1815 | #print "killing " + str(p.pid) # DEBUG 1816 | p.terminate() 1817 | p.join() 1818 | 1819 | 1820 | if errorType == "resize": 1821 | print "ERR: Resizing the window is not currently supported" 1822 | 1823 | if errorType == "dump": 1824 | print "node area " + str(dh) 1825 | print "volume area " + str(vh) 1826 | print "voltop is " + str(pVolTop) 1827 | print "volume cursor is " + str(volumeCursor) 1828 | print "node top is " + str(pNodeTop) 1829 | print "node cursor is " + str(nodeCursor) 1830 | gCluster.dump() 1831 | 1832 | elif errorType == "curses": # DEBUG ONLY 1833 | print "ERR: Exception in screen handling (curses). Program needs a window of 80x24" 1834 | 1835 | print "ERR: Message - ",e 1836 | #print ', '.join([type(e).__name__, os.path.basename(top[0]), str(top[1])]) 1837 | 1838 | print "vol window size is " + str(vh) 1839 | print "data window size is " + str(dh) 1840 | 1841 | 1842 | elif errorType == "unknown": 1843 | print "ERR: Problem occurred - dump of cluster and volume objects follow" 1844 | print e 1845 | gCluster.dump() 1846 | 1847 | 1848 | return 1849 | 1850 | # --------------------------------------------------------------------------------------------------------------------------------- 1851 | 1852 | if __name__ == "__main__": 1853 | 1854 | usageInfo = "%prog [options] argument \n\n" + \ 1855 | "This program uses snmp to gather and present various operational metrics\n" + \ 1856 | "from gluster nodes to provide a single view of a cluster, that refreshes\n" + \ 1857 | "every 5 seconds." 1858 | 1859 | bgModeOptions = ['nodes', 'all', 'summary'] 1860 | dataFormatOptions = ['raw','readable'] 1861 | 1862 | parser = OptionParser(usage=usageInfo,version="%prog 1.0.0") 1863 | parser.add_option("-n","--no-heading",dest="showHeaders",action="store_false",default=True,help="suppress headings") 1864 | parser.add_option("-s","--servers",dest="serverList",default=[],type="string",help="Comma separated list of names/IP (default uses gluster's peers file)") 1865 | parser.add_option("-b","--bg-mode",dest="bgMode",default="nodes",type="string",help="Which data to display in 'batch' mode " + str(bgModeOptions) + ", (default is nodes)") 1866 | parser.add_option("-f","--format",dest="dataFormat",default="readable",type="string",help="Output type raw or readable(default)") 1867 | parser.add_option("-g","--server-group",dest="groupName",default="",type="string",help="Name of a server group define in the users XML config file)") 1868 | 1869 | (options, args) = parser.parse_args() 1870 | 1871 | # check for mutually exclusive options 1872 | if options.serverList and options.groupName: 1873 | print "-s and -g options are mutually exclusive, use either not both" 1874 | exit(4) 1875 | 1876 | # if user provides a server or group list, check the background mode is OK to use 1877 | if options.serverList or options.groupName: 1878 | if options.bgMode and options.bgMode in bgModeOptions: 1879 | BGMODE = options.bgMode 1880 | else: 1881 | print "invalid option supplied on -b option. Valid options are " + str(bgModeOptions) 1882 | exit(4) 1883 | 1884 | if options.dataFormat and options.dataFormat in dataFormatOptions: 1885 | 1886 | # Need to check if option is raw, if so then headers aren't needed, but an initial 1887 | # csv based header row is - no pagination 1888 | if options.dataFormat == "raw": 1889 | options.showHeaders = False 1890 | 1891 | FORMAT = options.dataFormat 1892 | 1893 | else: 1894 | print "Invalid output option specified. Valid options are - " + str(dataFormatOptions) 1895 | exit(4) 1896 | 1897 | whiteList = ['eth','wlan','em','ib'] # wlan for testing ONLY! 1898 | whiteList = r'|'.join([name + "*" for name in whiteList]) 1899 | baseInstall = '/var/lib/glusterd' 1900 | 1901 | SNMPCOMMUNITY = 'gluster' 1902 | 1903 | # Unicode solid block character 1904 | block=u'\u2588' 1905 | 1906 | # Size of maximum bar for a volume at 100% full 1907 | barWidth = 20 1908 | pctPerBlock = 100 / barWidth 1909 | 1910 | timeTemplate = '%H:%M:%S' 1911 | 1912 | # define the symbols used to describe node state 1913 | 1914 | 1915 | # Could use os.environ['TERM'] - linux = console, xterm is GUI 1916 | consoleIsTTY = os.environ['TERM'] == 'linux' 1917 | if consoleIsTTY: 1918 | titleHighlight=curses.A_REVERSE 1919 | rowHighlight = curses.A_UNDERLINE 1920 | nodeStatus = { 'connected' : u'\u00BB', # double arrow right 1921 | 'disconnected' : u'\u2219', # solid circle 1922 | 'unknown' : u'\u003F'} # Question Mark 1923 | else: 1924 | titleHighlight=curses.A_UNDERLINE 1925 | rowHighlight = curses.A_BOLD 1926 | nodeStatus = { 'connected' : u'\u25B2', # UP 1927 | 'disconnected' : u'\u25BC', # DOWN 1928 | 'unknown' : u'\u003F'} # Question Mark 1929 | 1930 | 1931 | 1932 | # Not all variations are listed...since not all variations are supported! 1933 | volTypeShort = { 'Distributed-Replicated' : 'D-R', 1934 | 'Striped' : ' S ', 1935 | 'Distributed-Striped' : 'D-S', 1936 | 'Replicated' : ' R ', 1937 | 'Distributed' : ' D '} 1938 | 1939 | # define a dict that uses a group name to hold a comma separated list of servers 1940 | variables = [] 1941 | serverGroups = {} 1942 | 1943 | # configFile defines groups of servers that can be used 1944 | configFile = os.path.expanduser('~/gtoprc.xml') 1945 | 1946 | # define the number of rows in the info window (UI only) 1947 | infoHeight = 3 1948 | 1949 | showHeaders = options.showHeaders 1950 | BLOCKSIZE = 512 1951 | 1952 | # Use these ratios to determine the screen window proportions based on current screen height 1953 | VOLUMEAREAPCT = 25 # 20% of screen is volume data 1954 | NODEAREAPCT = 75 # 66% is for node data by default 1955 | 1956 | # Maximums used to define the virtual size of the volume and node display areas 1957 | MAXVOLS = 64 1958 | MAXNODES = 64 1959 | 1960 | # Set refresh interval to align with SNMP agent refresh interval of 5 seconds 1961 | refreshRate = 5 1962 | 1963 | volDir = os.path.join(baseInstall,'vols') 1964 | peersDir = os.path.join(baseInstall,'peers') 1965 | 1966 | # create a cluster object - this becomes the root object, linking cluster to volumes and volumes to bricks 1967 | gCluster = Cluster() 1968 | 1969 | print "\ngtop starting" 1970 | 1971 | variables, serverGroup = processConfigFile(configFile) 1972 | 1973 | # Apply any overrides from the users config file 1974 | if variables: 1975 | print "Applying overrides from configuration file" 1976 | for assignment in variables: 1977 | print "\t" + assignment 1978 | exec assignment 1979 | 1980 | 1981 | 1982 | # Check if user has supplied an override for the servers to monitor 1983 | if options.serverList or options.groupName: 1984 | 1985 | screenY,screenX = screenSize() 1986 | interactiveMode = False 1987 | timeStamps = True 1988 | 1989 | # if a group name has been given, build the server list from the config file 1990 | if options.groupName: 1991 | serverList = getGroupServers(options.groupName) 1992 | 1993 | # if the server list is empty flag to the user, no match on group 1994 | if not serverList: 1995 | print "ERR: Config file does not have servers associated with group '" + options.groupName + "'" 1996 | 1997 | else: 1998 | serverList = options.serverList 1999 | 2000 | # If we have servers to process from the user, validate them (IP, DNS checks) 2001 | if serverList: 2002 | print "Checking supplied server list is usable.." 2003 | gCluster.validateServers(serverList) 2004 | 2005 | else: 2006 | 2007 | print "Checking for glusterfs peers file" 2008 | 2009 | # Populate cluster hosts from peers file 2010 | gCluster.getGlusterPeers() 2011 | 2012 | # If we have nodes - then program is running on a node so enable all the local gathering 2013 | if gCluster.nodes: 2014 | interactiveMode = True 2015 | screenY,screenX = screenSize() 2016 | if screenY <= 9: 2017 | print "ERR: console/xterm needs to be > 9 rows in size" 2018 | exit(8) 2019 | 2020 | # Build a volume list based on the hosts vol file(s) 2021 | gCluster.getGlusterVols() 2022 | gCluster.volumes.sort(key=lambda volume: volume.name) 2023 | 2024 | # Grab the glusterfs version from the running host 2025 | gCluster.getVersion() 2026 | else: 2027 | print "ERR: No gluster configuration present at " + peersDir 2028 | pass 2029 | 2030 | 2031 | 2032 | if gCluster.nodes: 2033 | 2034 | gCluster.nodes.sort(key=lambda node: node.hostName) # sort the list of hosts, by host name 2035 | 2036 | print "Checking SNMP is available on the selected hosts.." 2037 | 2038 | # Check SNMP is responding on each host before we try and use them 2039 | gCluster.SNMPcheck() 2040 | 2041 | # If there are still nodes after all the checks they're OK to use 2042 | if gCluster.nodes: 2043 | 2044 | 2045 | # Call the main processing loop 2046 | main(gCluster) 2047 | 2048 | 2049 | else: 2050 | # no valid servers to talk to or left after validations...better tell the user! 2051 | 2052 | print "ERR: Unable to determine the hosts to scan. For this program to work you have" 2053 | print "the following options" 2054 | print "* use -s server1,server2" 2055 | print "* use -g groupname (groups define in an XML config file in current directory)" 2056 | print "* run on a gluster node\n" 2057 | 2058 | 2059 | print "Program terminated." 2060 | 2061 | 2062 | 2063 | 2064 | --------------------------------------------------------------------------------