├── .gitignore ├── LICENSE ├── MANIFEST.in ├── NOTICE ├── README.md ├── cassandra-toolbox ├── CHANGELOG.md ├── __init__.py ├── cassandra-stat └── cassandra-tracing ├── requirements.txt └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | #Ipython Notebook 62 | .ipynb_checkpoints 63 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include requirements.* 2 | include README* 3 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2016 Knewton, Inc. All Rights Reserved. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | 15 | *********************************************************************** 16 | 17 | Requests package Notice (docs.python-requests.org/) 18 | 19 | Copyright 2016 Kenneth Reitz 20 | 21 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 22 | 23 | http://www.apache.org/licenses/LICENSE-2.0 24 | 25 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 26 | 27 | *********************************************************************** 28 | 29 | Datastax python cassandra driver package Notice (datastax.github.io/python-driver) 30 | 31 | Copyright 2013-2016 DataStax 32 | 33 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 34 | 35 | http://www.apache.org/licenses/LICENSE-2.0 36 | 37 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 38 | 39 | ********************************************************************** 40 | 41 | License information for these dependencies can be found in LICENSE.txt. 42 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | cassandra-toolbox 2 | ========================= 3 | 4 | A suite of tools for Cassandra - A highly scalable distributed NoSQL datastore. 5 | 6 | These are a set of monitoring and analysis tools that were initially developed at Knewton in order to introspect behavior and performance of the Cassandra clusters at knewton. These scripts are designed to run locally or remotely against a cassandra cluster. Just install this into your virtual environment and go for it. 7 | 8 | **Be aware that these scripts may cause some load on the target server which can impact your performance. Nothing comes without a price.** 9 | 10 | Installation 11 | ============ 12 | 13 | It is preferable to create a virtual environment to install these tools into 14 | 15 | ```bash 16 | pip install virtualenv 17 | virtualenv /path/to/your/virtualenv 18 | source /path/to/your/virtualenv/bin/activate 19 | ``` 20 | 21 | To install the project you can clone this repo and install it directly into your virtual environment, this would get you the latest code 22 | 23 | ```bash 24 | git clone git@github.com:Knewton/cassandra-toolbox.git 25 | cd cassandra-toolbox 26 | ./setup.py install 27 | ``` 28 | 29 | You can also directly install our package from pip 30 | 31 | ```bash 32 | pip install cassandra-toolbox 33 | ``` 34 | 35 | 36 | Usage 37 | ===== 38 | 39 | This package consists of several scripts that get installed as executables into the environment that the package is in. Each script does something different and is described independently below. 40 | 41 | cassandra-stat 42 | ---------------- 43 | 44 | The cassandra-stat tool shows a real-time feed of how many operations have gone through Cassandra as reported by the JMX interface that is exposed. Many people pump this information through Graphite or another data collector which is a good idea so you can visualize and store the data. However these systems usually poll every minute and can lag behind events. This allows you to see to the second what is occuring on the system in a manner similar to iostat. 45 | 46 | This script interfaces with the jolokia jmx-http bridge which must be attached to your Cassandra instances that you plan to run cassandra-stat against. This is very easy however and not intrustive to Cassandra. 47 | 48 | Installing Jolokia is painless. You first [download the JVM agent from their website](https://jolokia.org/download.html). Then you modify your ``cassandra-env.sh`` file to include the following line: 49 | 50 | ```bash 51 | JVM_OPTS="$JVM_OPTS -javaagent:.jar" 52 | ``` 53 | 54 | A restart of the Cassandra instance is required after this modification. 55 | 56 | To use cassandra-stat you only need to execute the following local to the Cassandra instance you wish to monitor. You must have activated the virtual environment that cassandra-toolbox is installed into if you have installed the pacakge into a virtual environment. The output will look similar to the following: 57 | 58 | ```bash 59 | $cassandra-stat 60 | Reads Ranges Writes Reads (99%) ms Ranges (99%) ms Writes (99%) ms Compactions Flushes Row Cache Misses Time ns 61 | 1 0 111 91.462 68.81 17.4 0 0 0 20:15:36 total 62 | 2 4 113 91.4 68.30 17.98 0 0 0 20:15:37 total 63 | 0 0 117 91.4 68.30 17.17 0 0 0 20:15:38 total 64 | 0 0 72 91.4 68.30 17.34 0 0 0 20:15:39 total 65 | 0 2 69 91.4 68.30 17.3 0 0 0 20:15:40 total 66 | ``` 67 | 68 | The fields that are output are as follows: 69 | 70 | * Reads: Number of reads since the last line was reported 71 | * Ranges: Number of range queries since the last line was reported 72 | * Writes: Number of writes (updates/insertions/deletions) since the last line was reported 73 | * Reads (99%): 99th percentile latency in reads given in milliseconds 74 | * Ranges (99%): 99th percentile latency in range queries given in milliseconds 75 | * Writes (99%): 99th percentile latency in writes (updates/insertions/deletions) given in milliseconds 76 | * Compactions: Number of pending compactions 77 | * Flushes : Number of memtable flushes that are in progress 78 | * Row Cache Misses: Number of row cache misses that have occured since the last line was reported 79 | * time: Time in HH:MM:SS that the line was recorded at 80 | * ns: Namespace that the statistic is output for. This can be "total" which is a sum for all keyspaces, ```` which is a sum of all column families inside that keyspace, or ``.`` which is the most granular output 81 | 82 | If a namespace has no traffic, that is if there are 0 reads, range queries, or writes reported for that namespace then the namespace will not be output to the screen with the exception of "total" which will always be output. Note that some of the statistics are differences with the previous line so the absolute numbers can vary depending on the rate that is chosen (this is configurable, see below). Additionally the 99 percentile outputs are for a moving average that is generated internally by the Cassandra metric libraries so they are not representative of the 99th percentile at that instant. Any aggregate level metrics (total or keyspace level metrics) will show the highest 99th percentile latency. Aggregates for other metrics are summations of the constituent column families. By default system keyspaces are not included in these aggregations, but this is configurable. 83 | 84 | Configurations are set by command line flags, these can be accessed by running ``cassandra-stat --help``: 85 | 86 | * ``--header_rows int``: 87 | * An integer of how many rows should pass before a new header line is output. If this is 0 then only the first header will be printed, and if this is -1 then the top header row will not be printed. Default 10. 88 | * ``--rate int``: 89 | * How many seconds should pass between server polls. Default 1. 90 | * ``--show_system``: 91 | * Include system keyspaces and their related column families in the output. The aggregation in "total" will include system keyspace entires as well, which is not the default behavior. 92 | * ``--host string``: 93 | * The http://HOST:PORT that this script should connect to. Default http://localhost:8778. 94 | * ``--show_keyspaces``: 95 | * Set this flag in order to show keyspace level output. 96 | * ``--show_cfs``: 97 | * Set this flag to show `.` level output. 98 | * ``--no_total``: 99 | * Set this flag to suppress output of the aggregated total. This may have the effect of having no output when there is no traffic in the database. 100 | * ``--show_zeros``: 101 | * Show all namespaces that are set to be output regardless if there is no activity. 102 | * ``--namespaces string``: 103 | * Comma separated list of namespaces to process and show. To show an entire keyspace then use the keyspace name as an entry, and to show only a column family then add ``.`` to the list. For example ``--namespaces keyspace1,keyspace2.test1`` would show all column families from ``keyspace1`` and only the ``test1`` column family from ``keyspace2``. Note that there can be strange behaviors with this flag as other flags. Adding a system keyspace to this flag will have no effect unless the ``--show_system`` flag is also included. Adding namespaces to this flag will change what namespaces are included in the total for aggregations but these namespaces will not be printed out if the ``--show_keyspaces`` or ``--show_cfs`` flags are not included. For example ``--namespaces keyspace1,keyspace2.test1 --show_keyspaces`` would output an entry for ``total``, ``keyspace1``, and ``keyspace2`` where ``total`` will be the aggregate of all column families in ``keyspace1`` as well as the column family ``test1`` in ``keyspace2``, ``keyspace1`` will be the aggregate of all column families within it, and ``keyspace2`` will be the aggregate of only the column family ``test1``. If you are using this flag and ``--show_system`` then you must include which system keyspaces you wish to include, they will not be included by default if using the ``--namespaces`` flag. 104 | 105 | cassandra-tracing 106 | ----------------- 107 | This script facilitates analysis of Cassandra tracing data, which on its own is difficult to draw conclusions from. Tracing is very useful to look at individual CQL queries in the cqlsh shell, however to get a better idea of your system's behavior it is often useful to sample a percentage of queries, trace them, and save these traces for later. Cassandra makes this easy to do with nodetool. You can use the following to set the probability that any cql query (that is coordinated by the cassandra node local to this command) is traced to 0.1%. 108 | 109 | ```bash 110 | $nodetool settraceprobability 0.001 111 | ``` 112 | 113 | Note that a value of 1 means every query will be traced. A trace logs many lines for every query so be careful of setting this value very high. It is possible that tracing less than 5% of all queries can result in a write workload which is equal in number to the load which it is tracing. 114 | 115 | To use cassandra-tracing you only need to execute the following local to the Cassandra instance you wish to investigate the tracing logs of. You must have activated the virtual environment that cassandra-toolbox is installed into if you have installed the pacakge into a virtual environment. The output will look similar to the following: 116 | 117 | ```bash 118 | $ cassandra-tracing 119 | 100% Complete: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|100 120 | 121 | Total skipped due to null duration: 0 122 | Total skipped due to error: 0 123 | 124 | 175 sessions satisfying criteria. 125 | Showing 100 longest running results. 126 | Session Id Duration (microsecs) Max Tombstones Total Tombstones Flags Time Started Query 127 | bedd77a0-159e-11e6-af1d-5b2aec1d0944 19696 32 32 2016-05-09T04:30:23.259000 SELECT * FROM system.schema_columnfamilies 128 | be941af0-1801-11e6-9deb-25e4276011e4 20569 0 0 2016-05-12T05:24:05.280000 Executing single-partition query on ColumnFamilyA 129 | b4c924a0-1565-11e6-af1d-5b2aec1d0944 20905 32 32 2016-05-08T21:42:05.041000 SELECT * FROM system.schema_columnfamilies 130 | fdf6fda0-174a-11e6-ace9-39442dcd207a 21056 0 0 2016-05-11T07:35:53.724000 Executing single-partition query on ColumnFamilyB 131 | c5f24e80-1751-11e6-af1d-5b2aec1d0944 21397 0 0 2016-05-11T08:24:26.216000 Executing single-partition query on ColumnFamilyB 132 | f7670600-183b-11e6-af1d-5b2aec1d0944 21992 0 0 2016-05-12T12:20:51.425000 Executing single-partition query on ColumnFamilyC 133 | ``` 134 | 135 | The output displays the following information, sorted by duration: 136 | 137 | * Session ID 138 | * Duration in microseconds 139 | * Max number of tombstones encountered on a single session 140 | * Total tombstones encountered 141 | * Flags signifying special behavior, according to the legend: 142 | * R = read repair 143 | * T = timeout 144 | * I = index used 145 | * Starting timestamp of the session (hidden in slim mode) 146 | * CQL query or inferred query fragment (hidden in slim mode) 147 | 148 | The Session Id can be used to introspect specific queries (which are logged as a session) in cqlsh yourself, by querying for the session id in the events table of the system_tracing keyspace. 149 | 150 | ```bash 151 | $ cqlsh 152 | Connected to cassandra at 172.ip.ip.ip:9042. 153 | [cqlsh 5.0.1 | Cassandra 2.1.11 | CQL spec 3.2.1 | Native protocol v3] 154 | Use HELP for help. 155 | cqlsh> use system_traces; 156 | cqlsh:system_traces> select * from events WHERE session_id=bedd77a0-159e-11e6-af1d-5b2aec1d0944; 157 | session_id | event_id | activity | source | source_elapsed | thread 158 | --------------------------------------+--------------------------------------+--------------------------------------------------------------------------------------------------+--------------+----------------+--------------------- 159 | bedd77a0-159e-11e6-af1d-5b2aec1d0944 | bedd9eb0-159e-11e6-af1d-5b2aec1d0944 | Parsing SELECT * FROM system.schema_columnfamilies | 172.ip.ip.ip | 21 | SharedPool-Worker-2 160 | bedd77a0-159e-11e6-af1d-5b2aec1d0944 | beddecd0-159e-11e6-af1d-5b2aec1d0944 | Preparing statement | 172.ip.ip.ip | 31 | SharedPool-Worker-2 161 | bedd77a0-159e-11e6-af1d-5b2aec1d0944 | bede13e0-159e-11e6-af1d-5b2aec1d0944 | Computing ranges to query | 172.ip.ip.ip | 73 | SharedPool-Worker-2 162 | bedd77a0-159e-11e6-af1d-5b2aec1d0944 | bede3af0-159e-11e6-af1d-5b2aec1d0944 | Submitting range requests on 1 ranges with a concurrency of 1 (22.37143 rows per range expected) | 172.ip.ip.ip | 88 | SharedPool-Worker-2 163 | bedd77a0-159e-11e6-af1d-5b2aec1d0944 | bede6200-159e-11e6-af1d-5b2aec1d0944 | Submitted 1 concurrent range requests covering 1 ranges | 172.ip.ip.ip | 96 | SharedPool-Worker-2 164 | bedd77a0-159e-11e6-af1d-5b2aec1d0944 | beded730-159e-11e6-af1d-5b2aec1d0944 | Executing seq scan across 3 sstables for [min(-1), min(-1)] | 172.ip.ip.ip | 382 | SharedPool-Worker-4 165 | bedd77a0-159e-11e6-af1d-5b2aec1d0944 | bedefe40-159e-11e6-af1d-5b2aec1d0944 | Read 7 live and 0 tombstone cells | 172.ip.ip.ip | 2057 | SharedPool-Worker-4 166 | bedd77a0-159e-11e6-af1d-5b2aec1d0944 | bedf2550-159e-11e6-af1d-5b2aec1d0944 | Read 2 live and 0 tombstone cells | 172.ip.ip.ip | 2495 | SharedPool-Worker-4 167 | bedd77a0-159e-11e6-af1d-5b2aec1d0944 | bedf7370-159e-11e6-af1d-5b2aec1d0944 | Read 1 live and 0 tombstone cells | 172.ip.ip.ip | 3066 | SharedPool-Worker-4 168 | bedd77a0-159e-11e6-af1d-5b2aec1d0944 | bee00fb0-159e-11e6-af1d-5b2aec1d0944 | Read 17 live and 32 tombstone cells | 172.ip.ip.ip | 16892 | SharedPool-Worker-4 169 | bedd77a0-159e-11e6-af1d-5b2aec1d0944 | bee05dd0-159e-11e6-af1d-5b2aec1d0944 | Read 7 live and 0 tombstone cells | 172.ip.ip.ip | 18757 | SharedPool-Worker-4 170 | bedd77a0-159e-11e6-af1d-5b2aec1d0944 | bee084e0-159e-11e6-af1d-5b2aec1d0944 | Scanned 5 rows and matched 5 | 172.ip.ip.ip | 19172 | SharedPool-Worker-4 171 | ``` 172 | 173 | The results from ``cassandra-tracing`` can be limited by thresholds on both duration and tombstones, and by and a result cap. The result cap gathers the same number of results but caps the display. When limited results are displayed the results displayed are always the longest duration events. 174 | 175 | Regardless of limiting mechanisms, note that full table scans must be done on the ``sessions`` and ``events`` tables in the ``system_traces`` keyspace. 176 | 177 | Configurations are set by command line flags, these can be accessed by running `cassandra-tracing --help`: 178 | 179 | * node_ip: 180 | * Specify ip of the node being queried 181 | * --tombstoneThreshold int: 182 | * Show only sessions who read tombstones equal to or greater than this threshold. Default 0. 183 | * --time int: 184 | * Show only sessions that took longer than this threshold in microseconds. Default 10000 (10ms). 185 | * --resultCap int: 186 | * Maximum number of results to print out. To print all results, use 0. Default 100. 187 | * --slim: 188 | * Enable slim mode, where the query and time started are suppressed in the output. 189 | 190 | Supported Python Versions 191 | ========================= 192 | 193 | Python 2.7 and Python 3.4+ are supported. 194 | 195 | Licenses 196 | ======== 197 | 198 | The cassandra-toolbox pacakge is licensed under the Apache 2.0 license. 199 | 200 | Issues 201 | ====== 202 | 203 | Please report any bugs or requests that you have using the GitHub issue tracker! 204 | 205 | Authors 206 | ======= 207 | 208 | * Dr. Jeffrey Berger 209 | * Dr. Joshua Wickman 210 | * Carlos Monroy Nieblas 211 | -------------------------------------------------------------------------------- /cassandra-toolbox/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | 4 | ## 0.1.5 5 | 6 | ### cassandra-tracing 7 | 8 | #### New Features 9 | 10 | - Minimal support has been added for Scylla, which uses a different key structure for columns queried with the `dateOf` operator. This support has been tested with Scylla 1.3 only. 11 | 12 | #### Bug Fixes 13 | 14 | - Sessions which were skipped due to error were properly recorded, but encountered a bug when their details were printed. Error cases should now have their session ID and error message printed, as intended. 15 | 16 | 17 | ## 0.1.4 18 | 19 | - Uploaded to public PyPI 20 | -------------------------------------------------------------------------------- /cassandra-toolbox/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Knewton/cassandra-toolbox/0aacb248ad39d76d80136a6130484073d8c26c01/cassandra-toolbox/__init__.py -------------------------------------------------------------------------------- /cassandra-toolbox/cassandra-stat: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Cassandra Stat, an IO Stat like program to monitor Cassandra.""" 3 | from __future__ import print_function 4 | import requests 5 | import argparse 6 | import sys 7 | from datetime import datetime 8 | from copy import deepcopy 9 | import time 10 | 11 | 12 | def stderr_print(*args, **kwargs): 13 | """Print to stderr in a backwards compatible way from a common interface. 14 | 15 | Use this function as one does the standard print function, except it will 16 | send the output to stderr. 17 | """ 18 | print(*args, file=sys.stderr, **kwargs) 19 | 20 | 21 | class CassandraStat(object): 22 | """Continually poll a Cassandra instance for stats and output it to stdout. 23 | 24 | Once the cassandra stat object is instantiated it begins running until 25 | recieving a keyboard interrupt. 26 | """ 27 | 28 | def __init__( 29 | self, 30 | host, 31 | user, 32 | password, 33 | header_rows, 34 | rate, 35 | show_system, 36 | show_keyspace, 37 | show_cfs, 38 | show_total, 39 | show_zeros, 40 | namespaces 41 | ): 42 | """Create a CassandraStat instance and begin running immediately. 43 | 44 | **Args:** 45 | host (str): 46 | Host and port to connect to, format http://HOST:PORT 47 | header_rows (int): 48 | How many rows should pass before a new header line is output. 49 | If this is 0 then only the first header will be printed, and if 50 | this is -1 then the top header row will not be printed. 51 | Renamed printed_rows_between_headers internally in this class 52 | from the arg name which is displayed to the user as 53 | header_rows for brevity. 54 | rate (int): 55 | How many seconds should pass between server polls. 56 | show_system (bool): 57 | Include system keyspaces and their related column families in 58 | the output. The aggregation in "total" will include system 59 | keyspace entires as well. 60 | show_keyspace (bool): 61 | Show keyspace level output. 62 | show_cfs (bool): 63 | Show column family level output. 64 | show_total (bool): 65 | Show a row with overall total stats for the instance. 66 | show_zeros (bool): 67 | Show all namespaces that are set to be output regardless if 68 | there is no activity. 69 | namespaces (list): 70 | list of keyspace or keysapce.cf names to be shown 71 | """ 72 | self.host = host 73 | self.user = user 74 | self.password = password 75 | self.printed_rows_between_headers = header_rows 76 | self.rate = rate 77 | self.show_system = show_system 78 | self.show_keyspace = show_keyspace 79 | self.show_cfs = show_cfs 80 | self.show_zeros = show_zeros 81 | self.namespaces = namespaces 82 | self.show_total = show_total 83 | self.previous_data = {} 84 | self.current_data = {} 85 | # Note the display name must be unique amongst metrics or you will 86 | # encounter undocumented and unspecified behavior 87 | self.metrics = [ 88 | { 89 | "metric_name": "ReadLatency", 90 | "metric_key": "Count", 91 | "display_name": "Reads", 92 | "sum": True, 93 | "diff": True, 94 | "nonzero": True 95 | }, 96 | { 97 | "metric_name": "RangeLatency", 98 | "metric_key": "Count", 99 | "display_name": "Ranges", 100 | "sum": True, 101 | "diff": True, 102 | "nonzero": True 103 | }, 104 | { 105 | "metric_name": "WriteLatency", 106 | "metric_key": "Count", 107 | "display_name": "Writes", 108 | "sum": True, 109 | "diff": True, 110 | "nonzero": True 111 | }, 112 | { 113 | "metric_name": "ReadLatency", 114 | "metric_key": "99thPercentile", 115 | "display_name": "Reads (99%) ms" 116 | }, 117 | { 118 | "metric_name": "RangeLatency", 119 | "metric_key": "99thPercentile", 120 | "display_name": "Ranges (99%) ms" 121 | }, 122 | { 123 | "metric_name": "WriteLatency", 124 | "metric_key": "99thPercentile", 125 | "display_name": "Writes (99%) ms" 126 | }, 127 | { 128 | "metric_name": "PendingCompactions", 129 | "metric_key": "Value", 130 | "display_name": "Compactions", 131 | "sum": True 132 | }, 133 | { 134 | "metric_name": "PendingFlushes", 135 | "metric_key": "Count", 136 | "display_name": "Flushes", 137 | "sum": True 138 | }, 139 | { 140 | "metric_name": "RowCacheMiss", 141 | "metric_key": "Count", 142 | "display_name": "Row Cache Misses", 143 | # "space": 18, 144 | "sum": True, 145 | "diff": True 146 | } 147 | ] 148 | self.run() 149 | 150 | def run(self): 151 | """Run the cassandra-stat process until a keyboard interrupt. 152 | 153 | **Args:** 154 | None 155 | 156 | **Returns:** 157 | None 158 | """ 159 | batch_cnt = 0 160 | if self.printed_rows_between_headers >= 0: 161 | self.print_headers() 162 | while True: 163 | if self.previous_data: 164 | batch_cnt += 1 165 | time.sleep(self.rate) 166 | if batch_cnt == self.printed_rows_between_headers: 167 | batch_cnt = 1 168 | self.print_headers() 169 | self.print_data() 170 | self.previous_data = self.current_data 171 | 172 | def print_headers(self): 173 | """Print headers to stdout. 174 | 175 | **Args:** 176 | None 177 | 178 | **Returns:** 179 | None 180 | """ 181 | headerstr = "" 182 | for metric in self.metrics: 183 | space = metric.get("space", len(metric["display_name"]) + 2) 184 | headerstr += metric["display_name"].center(space) 185 | headerstr += "Time".center(12) 186 | headerstr += "ns" 187 | print(headerstr) 188 | 189 | def parse_jmx_key(self, key): 190 | """Parse a JMX key into a list of dicts. 191 | 192 | **Args:** 193 | key (str): JMX key of the format "uri:key1=value1,key2=value2" 194 | 195 | **Returns:** 196 | dict: Dictionary of JMX key: value pairs 197 | """ 198 | kvs = key.split(":")[1] 199 | return { 200 | kvstr.split("=")[0]: kvstr.split("=")[1] 201 | for kvstr in kvs.split(",") 202 | } 203 | 204 | def fetch_and_update( 205 | self, 206 | data, 207 | name, 208 | keyname, 209 | internalname, 210 | sum_values=True 211 | ): 212 | """Fetch a metric from JMX and include it in our data dictionary. 213 | 214 | The jolokia service has a get request made to it to read a metric that 215 | is passed in as name and keyname from the server. For example, the 216 | name may be WriteLatency and the keyname could be Count to retrieve 217 | the count of how many writes have occured. 218 | 219 | It will respond with a JSON of which the data is contained in the value 220 | field. Therein is a list of dicts where the key is a JMX key of the 221 | form "uri:key1=value1,key2=value2" and the value is itself a dict of 222 | keyname (such as Count) to the actual value of the metric. 223 | 224 | The JMX key is parsed out by a different function to extract the 225 | namespace that the metric is acting on. It uses the namespace, which 226 | is composed of . as the key in the internal 227 | data dictionary that is passed in. The internal data dict has the 228 | structure of 229 | { 230 | : { 231 | : value 232 | } 233 | } 234 | and the corresponding namespace and internalname is updated with the 235 | value that is recieved from JMX. If the sum flag is false then it 236 | will update the field in the data dict for the largest value, if it is 237 | sum then it will add the value to the namespace. 238 | 239 | **Args:** 240 | data (dict): 241 | A dict of all currently compiled metrics with the schema 242 | as described in the comment above. This is passed in so 243 | that the values can be added onto the data dict rather than 244 | having the calling function have to have logic to merge 245 | the previous data into the data that is being returned. 246 | name (str): 247 | JMX Metric name 248 | keyname (str): 249 | JMX Attribute key name 250 | internalname (str): 251 | Mertric name as displayed in the header which is unique and 252 | so used as the internal identifier of the metric. 253 | sum_values (boolean, default=True): 254 | Set to true if the value for this metric should be summed 255 | over a given namespace. If it set to false then only 256 | the largest value for a given namespace will be displayed. 257 | This is useful for things such as latency measurements as 258 | you would only want to see the highest latency not the sum 259 | of all latencies. By default this is summed as most reported 260 | metrics such as pending tasks and operations should be 261 | the sum of all such values in a given namespace. 262 | 263 | **Returns:** 264 | None, all the data that is of interest is added into the data 265 | dictionary that is passed in. As Python passes objects by 266 | reference the calling function will have the data dict updated 267 | to include the data requested without requiring the assignment of 268 | a returned value. 269 | 270 | **Exit Conditions:** 271 | If there is an error connecting to the jolokia agent of the form 272 | `requests.exceptions.ConnectionError` then an error message will 273 | be printed out and the process will exit with a return code of 1 274 | If the jolokia agent responds but with a 4xx/5xx status code or 275 | a 2xx/3xx status code with an error field that is nonempty then 276 | the process will exit with a return code of 1 and print an error. 277 | """ 278 | auth = requests.auth.HTTPBasicAuth(self.user, self.password) \ 279 | if self.user is not None and self.password is not None else None 280 | 281 | try: 282 | resp = requests.get( 283 | "{host}/jolokia/read/org.apache.cassandra.metrics:" 284 | "type=ColumnFamily,*,name={name}/{key}" 285 | .format(name=name, key=keyname, host=self.host), 286 | auth=auth 287 | ) 288 | except requests.exceptions.ConnectionError: 289 | print( 290 | "The application recieved a connection error, perhaps " 291 | "the ports are not open to the host specified or " 292 | "you do not have the jolokia agent installed and active. " 293 | "Please download the jolokia JVM agent jar file and insert " 294 | "JVM_OPTS=\"$JVM_OPTS -javaagent:PATH_TO_JOLOKIA_JAR.jar\" " 295 | "into your cassandra-env.sh file and restart cassandra." 296 | ) 297 | sys.exit(1) 298 | if resp.status_code >= 400 or resp.json().get("error"): 299 | stderr_print( 300 | "ERROR the jolokia agent returned an error trying to access " 301 | "the following metric : " 302 | "org.apache.cassandra.metrics:type=ColumnFamily,*," 303 | "name={name}/{key}".format(name=name, key=keyname) 304 | ) 305 | return 306 | else: 307 | jmx_data = resp.json()["value"] 308 | for key, jmx_obj in jmx_data.items(): 309 | fields = self.parse_jmx_key(key) 310 | 311 | # If there is no keyspace do not process the entry, this is some 312 | # internally aggregated value and we are doing custom aggregation 313 | if "keyspace" not in fields: 314 | continue 315 | 316 | # If the keyspace is a system keyspace skip processing unless 317 | # the show_system flag is true 318 | if( 319 | fields["keyspace"] in [ 320 | "system", 321 | "system_keyspaces", 322 | "system_auth" 323 | ] and not self.show_system 324 | ): 325 | continue 326 | 327 | full_namespace = "{ksp}.{cf}".format( 328 | ksp=fields["keyspace"], 329 | cf=fields["scope"] 330 | ) 331 | 332 | # If the user has passed in a set of namespaces that we should be 333 | # restricted to then check if this namespace is in this restricted 334 | # set. If not then we should not process it, if there are no 335 | # namespaces passed in by the user we should use all namespaces. 336 | if self.namespaces: 337 | include_namespace = False 338 | for passed_in_namespace in self.namespaces: 339 | if "." in passed_in_namespace: 340 | if passed_in_namespace == full_namespace: 341 | include_namespace = True 342 | break 343 | else: 344 | if passed_in_namespace == fields["keyspace"]: 345 | include_namespace = True 346 | break 347 | if not include_namespace: 348 | continue 349 | 350 | # If the show_cfs flag is true then our namespace is the full 351 | # keyspace.columnfamily namespace 352 | # If the show_keyspace flag is true then the namespace we are 353 | # using will be just the keyspace 354 | # If neither flag is set we will only store things in totals 355 | if self.show_cfs: 356 | ns = full_namespace 357 | elif self.show_keyspace: 358 | ns = fields["keyspace"] 359 | else: 360 | ns = None 361 | 362 | if ns: 363 | if ns not in data: 364 | data[ns] = {} 365 | if internalname not in data[ns]: 366 | data[ns][internalname] = jmx_obj[keyname] 367 | else: 368 | if sum_values: 369 | data[ns][internalname] += jmx_obj[keyname] 370 | elif data[ns][internalname] < jmx_obj[keyname]: 371 | data[ns][internalname] = jmx_obj[keyname] 372 | 373 | if self.show_total: 374 | if internalname not in data["total"]: 375 | data["total"][internalname] = jmx_obj[keyname] 376 | else: 377 | if sum: 378 | data["total"][internalname] += jmx_obj[keyname] 379 | elif data["total"][internalname] < jmx_obj[keyname]: 380 | data["total"][internalname] = jmx_obj[keyname] 381 | 382 | def get_data(self): 383 | """Get all data from jmx and construct a data dict. 384 | 385 | This constructs a data dict of the form 386 | { 387 | : { 388 | : value 389 | } 390 | } 391 | for all the metrics that are output by cassandra-stat through 392 | repeated calls to fetch_and_update. 393 | 394 | **Args:** 395 | None 396 | 397 | **Returns:** 398 | dict: the data dictionary, format is described above. 399 | """ 400 | retval = {} 401 | if self.show_total: 402 | retval["total"] = {} 403 | 404 | for metric in self.metrics: 405 | self.fetch_and_update( 406 | data=retval, 407 | name=metric["metric_name"], 408 | keyname=metric["metric_key"], 409 | internalname=metric["display_name"], 410 | sum_values=metric.get("sum", False) 411 | ) 412 | return retval 413 | 414 | def diffdata(self): 415 | """Find the difference in the Cassandra data from the last iteration. 416 | 417 | This uses the current_data and previous_data that has been saved from 418 | the current round of data gathering and the most recent previous round 419 | of data gathering. As these are class variables they are not passed 420 | into this function but they are accessed through self. The function 421 | will take a difference of some of these metrics, others it will take 422 | the latest value, and it will return a new data dict that has the 423 | values that should be output to the user. 424 | 425 | **Args:** 426 | None 427 | 428 | **Returns:** 429 | dict: data dict that contains the values to be output 430 | """ 431 | retval = deepcopy(self.current_data) 432 | for ns, current_metric_data in self.current_data.items(): 433 | # Iterate through all metrics that we are collecting 434 | for metric in self.metrics: 435 | # If the metric should have its difference taken then do so, 436 | # otherwise just report the most recent value 437 | if metric.get("diff"): 438 | retval[ns][metric["display_name"]] = ( 439 | current_metric_data.get(metric["display_name"], 0) - 440 | self.previous_data.get(ns, {}).get( 441 | metric["display_name"], 0 442 | ) 443 | ) 444 | else: 445 | retval[ns][metric["display_name"]] = ( 446 | current_metric_data.get(metric["display_name"], 0) 447 | ) 448 | return retval 449 | 450 | def print_dataline(self, data): 451 | """Print to stdout a single line of data. 452 | 453 | **Args:** 454 | data (dict): Data dict that is the output of the diffdata 455 | function, see get_data function for structure. 456 | 457 | **Returns:** 458 | None 459 | """ 460 | # Are there any metrics that are nonzero metrics, which means if any of 461 | # these metrics are nonzero then we should show the namespace. 462 | nonzero_fields = [x for x in self.metrics if x.get("nonzero")] 463 | 464 | number_of_printed_ns = 0 465 | for ns, metric_data in data.items(): 466 | # If there are nonzero fields then we should check that at least 467 | # one of the metrics is nonzero. We do this by creating a list of 468 | # all fields for this namespace which are nonzero designated fields 469 | # who have values that are not 0 or None. This can then be 470 | # tested in a conditional, if the list is empty then it will 471 | # evaluate to false. 472 | nonzero_value_fields = [ 473 | y for y in nonzero_fields if metric_data.get(y["display_name"]) 474 | ] 475 | 476 | # The conditional for displaying a line of data is broken into 477 | # two statements 478 | # 479 | # The first statement checks three things. If the field 480 | # show_zeroes is set then it will pass, if there are no metric 481 | # fields that are designated as nonzero metrics then it passes, 482 | # and if there are nonzero metrics if this namespace has any of 483 | # those metrics with nonzero/non-None values it will pass. 484 | # 485 | # The second is the test if this row is the "total" row which 486 | # records the total activity of the node. If the show_total field 487 | # is set to False this will fail and if the ns is not "total" it 488 | # will fail. 489 | if ( 490 | ( 491 | nonzero_value_fields or 492 | self.show_zeros or 493 | not nonzero_fields 494 | ) or 495 | ( 496 | ns == "total" and 497 | self.show_total 498 | ) 499 | ): 500 | datastr = "" 501 | for metric in self.metrics: 502 | space = metric.get( 503 | "space", len(metric["display_name"]) + 2 504 | ) 505 | datastr += str( 506 | metric_data.get(metric["display_name"], 0) 507 | ).center(space) 508 | datastr += datetime.now().strftime("%H:%M:%S").center(12) 509 | datastr += ns 510 | number_of_printed_ns += 1 511 | print(datastr) 512 | # If there are multiple namespaces are printed then we should 513 | # put a new line in between each block of namespaces 514 | if number_of_printed_ns > 1: 515 | print("\n") 516 | 517 | def print_data(self): 518 | """Fetch a new iteration of data and print data to stout. 519 | 520 | **Args:** 521 | None 522 | 523 | **Returns:** 524 | None 525 | """ 526 | self.current_data = self.get_data() 527 | if self.previous_data: 528 | self.print_dataline(self.diffdata()) 529 | 530 | 531 | def parse_args(): 532 | """Parse command line arguments. 533 | 534 | **Args:** 535 | None 536 | 537 | **Returns:** 538 | Namespace object that represents the parsed command line 539 | """ 540 | parser = argparse.ArgumentParser( 541 | description=( 542 | 'Cassandra-stat tool for live monitoring of Cassandra traffic.' 543 | ) 544 | ) 545 | parser.add_argument( 546 | '--host', 547 | dest='host', 548 | default="http://localhost:8778", 549 | help='Host and port to connect to, format http://HOST:PORT.' 550 | ) 551 | parser.add_argument( 552 | '--user', 553 | dest='user', 554 | default=None, 555 | help='The username for use in basic HTTP authentication.' 556 | ) 557 | parser.add_argument( 558 | '--password', 559 | dest='password', 560 | default=None, 561 | help='The password for use in basic HTTP authentication.' 562 | ) 563 | parser.add_argument( 564 | '--header_rows', 565 | dest='header_rows', 566 | default=10, 567 | type=int, 568 | help=( 569 | 'How many rows should pass before a new header line is output. ' 570 | 'If this is 0 then only the first header will be printed, and if ' 571 | 'this is -1 then the top header row will not be printed.' 572 | ) 573 | ) 574 | parser.add_argument( 575 | '--rate', 576 | dest='rate', 577 | default=1, 578 | type=int, 579 | help='How many seconds should pass between server polls.' 580 | ) 581 | parser.add_argument( 582 | '--show_system', 583 | dest='show_system', 584 | default=False, 585 | action="store_true", 586 | help=( 587 | 'Include system keyspaces and their related column families in ' 588 | 'the output. The aggregation in "total" will include system ' 589 | 'keyspace entires as well.' 590 | ) 591 | ) 592 | parser.add_argument( 593 | '--show_keyspace', 594 | dest='show_keyspace', 595 | default=False, 596 | action="store_true", 597 | help='Show keyspace level output.' 598 | ) 599 | parser.add_argument( 600 | '--show_cfs', 601 | dest='show_cfs', 602 | default=False, 603 | action="store_true", 604 | help='Show . level output.' 605 | ) 606 | parser.add_argument( 607 | '--show_zeros', 608 | dest='show_zeros', 609 | default=False, 610 | action="store_true", 611 | help=( 612 | 'Show all namespaces that are set to be output regardless if ' 613 | 'there is no activity.' 614 | ) 615 | ) 616 | parser.add_argument( 617 | '--no_total', 618 | dest='show_total', 619 | default=True, 620 | action="store_false", 621 | help=( 622 | 'Suppress output of total aggregation. This may have the effect ' 623 | 'of having no output when there is no traffic in the database.' 624 | ) 625 | ) 626 | parser.add_argument( 627 | '--namespaces', 628 | dest='namespaces', 629 | default="", 630 | help=( 631 | 'Comma separated list of namespaces to process and show. To show ' 632 | 'an entire keyspace then use the keyspace name as an entry, and ' 633 | 'to show only a column family then add . ' 634 | 'to the list. This flag can result in suprsing behavior if you ' 635 | 'are not careful so please see the README file for more.' 636 | ) 637 | ) 638 | return parser.parse_args() 639 | 640 | 641 | def main(): 642 | """Create an instance of CassandraStat and run until interrupt. 643 | 644 | **Args:** 645 | None 646 | 647 | **Returns:** 648 | None 649 | """ 650 | args = parse_args() 651 | namespaces = [] 652 | if args.namespaces: 653 | namespaces = args.namespaces.split(",") 654 | 655 | try: 656 | CassandraStat( 657 | host=args.host, 658 | user=args.user, 659 | password=args.password, 660 | header_rows=args.header_rows, 661 | rate=args.rate, 662 | show_system=args.show_system, 663 | show_keyspace=args.show_keyspace, 664 | show_cfs=args.show_cfs, 665 | show_total=args.show_total, 666 | show_zeros=args.show_zeros, 667 | namespaces=namespaces 668 | ) 669 | except KeyboardInterrupt: 670 | sys.exit(0) 671 | 672 | 673 | if __name__ == "__main__": 674 | main() 675 | -------------------------------------------------------------------------------- /cassandra-toolbox/cassandra-tracing: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Tool for cassandra tracing analysis.""" 3 | 4 | from __future__ import print_function 5 | from cassandra.cluster import Cluster 6 | from cassandra import OperationTimedOut 7 | import re 8 | import argparse 9 | import textwrap 10 | 11 | 12 | def parse_args(): 13 | """Parse command line arguments. 14 | 15 | Args: 16 | None 17 | 18 | Returns: 19 | namespace object: parsed arguments 20 | """ 21 | arg_parser = argparse.ArgumentParser( 22 | description=( 23 | textwrap.dedent( 24 | """\ 25 | This script facilitates analysis of Cassandra tracing data, 26 | which on its own is difficult to draw conclusions from. The 27 | output displays the following information, sorted by duration: 28 | - Session ID 29 | - Duration in microseconds 30 | - Max number of tombstones encountered on a single session 31 | - Total tombstones encountered 32 | - Flags signifying special behavior, according to the legend: 33 | - R = read repair 34 | - T = timeout 35 | - I = index used 36 | - Starting timestamp of the session (hidden in slim mode) 37 | - CQL query or inferred query fragment (hidden in slim mode) 38 | 39 | The results can be limited by thresholds on both duration and 40 | tombstones, and by and a result cap. The result cap gathers 41 | the same number of results but caps the display - when using 42 | this, the results displayed are always the longest duration 43 | events. 44 | 45 | Regardless of limiting mechanisms, note that full table scans 46 | must be done on the "sessions" and "events" tables in the 47 | "system_traces" keyspace. 48 | """ 49 | ) 50 | ), 51 | formatter_class=argparse.RawDescriptionHelpFormatter 52 | ) 53 | arg_parser.add_argument( 54 | '-H', '--host', dest="node_ip", default='127.0.0.1', 55 | help="Specify IP address of the node being queried, default 127.0.0.1." 56 | ) 57 | arg_parser.add_argument( 58 | '-p', '--port', dest="node_port", default=9042, 59 | type=int, help=( 60 | 'Specify the port to connect to on the host, default 9042.' 61 | ) 62 | ) 63 | arg_parser.add_argument( 64 | '-b', '--tombstoneThreshold', dest="tombstone_threshold", default=0, 65 | type=int, help=( 66 | 'Show only sessions who read tombstones equal to or greater than ' 67 | ' this threshold, default 0.' 68 | ) 69 | ) 70 | arg_parser.add_argument( 71 | '-t', '--time', dest="time_threshold", default=10000, type=int, 72 | help=( 73 | 'Show only sessions that took longer than this threshold in ' 74 | 'microseconds, default 10000.' 75 | ) 76 | ) 77 | arg_parser.add_argument( 78 | '-r', '--resultCap', dest='result_cap', default=100, type=int, 79 | help=( 80 | 'Maximum number of results to print out, default 100. To print ' 81 | 'all results, use 0.' 82 | ) 83 | ) 84 | arg_parser.add_argument( 85 | '-s', '--slim', dest='slim', default=False, action='store_true', 86 | help=( 87 | 'Enable slim mode, where the query and time started are ' 88 | 'suppressed in the output.' 89 | ) 90 | ) 91 | return arg_parser.parse_args() 92 | 93 | 94 | def print_update(current_cnt, total_cnt): 95 | """Print progress bar to stdout. 96 | 97 | Args: 98 | current_cnt (int): current number of scanned sessions 99 | total_cnt (int): total number of sessions to scan 100 | 101 | Returns: 102 | none 103 | """ 104 | percent = int(current_cnt * 100 / total_cnt) 105 | print( 106 | "\r{x}% Complete: {bar}|100".format( 107 | x=str(percent).zfill(3), 108 | bar=("X" * percent).ljust(100) 109 | ), 110 | end="" 111 | ) 112 | 113 | 114 | def process_sessions(dbsession, time_threshold, tombstone_threshold): 115 | """Process sessions collection of traces keyspace. 116 | 117 | Args: 118 | dbsession (Cassandra session object): system_traces connection 119 | time_threshold (int): minimum time in microsecs 120 | for a session to qualify for processing 121 | tombstone_threshold (int): minimum number of total 122 | tombstones scanned to qualify for processing 123 | 124 | Returns: 125 | list( 126 | { 127 | "duration": int (microseconds), 128 | "session_id": UUID 129 | "max_tombstones": int, 130 | "tot_tombstones": int, 131 | "time_started": datetime, 132 | "query": str 133 | } 134 | ) 135 | """ 136 | sessions = dbsession.execute('SELECT * FROM sessions') 137 | output = [] 138 | sessions_cnt = dbsession.execute('SELECT COUNT(*) FROM sessions') 139 | total_cnt = sessions_cnt[0].count 140 | current_cnt = 0 141 | skipped_null = [] # Elements: str 142 | skipped_err = [] # Elements: tuple 143 | for sess in sessions: 144 | current_cnt += 1 145 | print_update(current_cnt, total_cnt) 146 | if not sess.duration: 147 | skipped_null.append(str(sess.session_id)) 148 | continue 149 | elif sess.duration >= time_threshold: 150 | try: 151 | ( 152 | tot_tombstones, 153 | max_tombstones, 154 | time_started, 155 | query_frag, 156 | flags 157 | ) = get_event_info(dbsession, sess.session_id) 158 | except Exception as e: 159 | skipped_err.append( 160 | (str(sess.session_id), str(e)) 161 | ) 162 | continue 163 | if tot_tombstones >= tombstone_threshold: 164 | if sess.parameters and sess.parameters.get('query'): 165 | query = sess.parameters['query'] 166 | elif query_frag: 167 | query = query_frag 168 | else: 169 | query = sess.request 170 | output.append( 171 | { 172 | "duration": sess.duration, 173 | "session_id": sess.session_id, 174 | "max_tombstones": max_tombstones, 175 | "tot_tombstones": tot_tombstones, 176 | "query": query, 177 | "flags": flags, 178 | "time_started": time_started 179 | } 180 | ) 181 | print('\n\n') 182 | print('Total skipped due to null duration:\t{sn}' 183 | .format(sn=len(skipped_null))) 184 | print('\t' + '\n\t'.join(skipped_null)) 185 | print('Total skipped due to error:\t{se}' 186 | .format(se=len(skipped_err))) 187 | if skipped_err: 188 | print('\t' + '\n\t'.join([ 189 | '{sess}\t{err}'.format(sess=x[0], err=x[1]) for x in skipped_err 190 | ])) 191 | print('\n\n') 192 | return sorted(output, key=lambda k: k['duration']) 193 | 194 | 195 | def get_event_info(dbsession, session_id): 196 | """Get additional info about the event corresponding toa given session_id. 197 | 198 | The query fragment in the return tuple is the best-guess that this program 199 | is making by parsing the events as to what the query was operating on in 200 | case the parameters field does not itself contain the query, as happens 201 | with thrift clients. 202 | 203 | The flags in the return tuple are a concatenation of single-letter 204 | representations of query properties, including: 205 | - read repair (R) 206 | - timeout (T) 207 | - index used (I) 208 | 209 | Args: 210 | dbsession (Cassandra session object): system_traces connection 211 | session_id (UUID): session_id to count the 212 | tombstones of 213 | 214 | Returns: 215 | tuple( 216 | total tombstone count(int), 217 | max tombstone count(int), 218 | time started (ISO str), 219 | query fragment (str), 220 | flags (str) 221 | ) 222 | """ 223 | events = dbsession.execute( 224 | 'SELECT dateOf(event_id), activity FROM events ' 225 | 'WHERE session_id={sid}'.format( 226 | sid=session_id 227 | ) 228 | ) 229 | max_tombstone_cnt = 0 230 | tot_tombstone_cnt = 0 231 | time_started = '' 232 | query = '' 233 | flags = set() 234 | for event in events: 235 | m = re.search("([0-9]+) tombstone", event.activity) 236 | if m and int(m.group(1)) > 0: 237 | tot_tombstone_cnt += int(m.group(1)) 238 | if max_tombstone_cnt < int(m.group(1)): 239 | max_tombstone_cnt = int(m.group(1)) 240 | if not query: 241 | if "Parsing" in event.activity: 242 | query = event.activity[7:] 243 | elif "idx" in event.activity: 244 | m = re.search(".*(Scanning.*\.$)", event.activity) 245 | query = m.group(1) 246 | flags.add('I') 247 | elif "memtable" in event.activity: 248 | query = event.activity 249 | elif "query" in event.activity: 250 | query = event.activity 251 | if "read-repair" in event.activity.lower(): 252 | flags.add('R') 253 | elif "idx" in event.activity.lower(): 254 | flags.add('I') 255 | elif "timeout" in event.activity.lower(): 256 | flags.add('T') 257 | 258 | if not time_started: 259 | try: 260 | # Cassandra 261 | time_started = event.dateOf_event_id.isoformat() 262 | except AttributeError: 263 | # Scylla 264 | time_started = event.system_dateof_event_id.isoformat() 265 | return (tot_tombstone_cnt, max_tombstone_cnt, time_started, query.strip(), 266 | ''.join(flags)) 267 | 268 | 269 | def print_output(output, result_cap, show_less=False): 270 | """Print the results of the analysis to stdout. 271 | 272 | Args: 273 | output(list): List of dictionaries, see process_sessions 274 | documentation for schema 275 | result_cap(int): Limit on number of results to show (preferring 276 | longest duration events) 277 | show_less(boolean, optional): Show less information to be friendly 278 | for small screens (i.e. "slim mode") 279 | 280 | Returns: 281 | None 282 | """ 283 | print("{x} sessions satisfying criteria.".format(x=len(output))) 284 | if result_cap < len(output): 285 | print("Showing {x} longest running results.".format(x=result_cap)) 286 | print( 287 | "{sessid}{duration}{maxtomb}{tottomb}{flag}{ts}{query}".format( 288 | sessid="Session Id".center(40), 289 | duration="Duration (microsecs)".center(22), 290 | maxtomb="Max Tombstones".center(20), 291 | tottomb="Total Tombstones".center(20), 292 | flag="Flags".center(10), 293 | ts="" if show_less else "Time Started".center(30), 294 | query="" if show_less else "Query" 295 | ) 296 | ) 297 | if result_cap: 298 | output = output[-result_cap:] 299 | for entry in output: 300 | print( 301 | "{sessid}{duration}{maxtomb}{tottomb}{flag}{ts}{query}".format( 302 | sessid=str(entry["session_id"]).center(40), 303 | duration=str(entry["duration"]).center(22), 304 | maxtomb=str(entry["max_tombstones"]).center(20), 305 | tottomb=str(entry["tot_tombstones"]).center(20), 306 | flag=entry["flags"].center(10), 307 | ts="" if show_less else str(entry["time_started"]).center(30), 308 | query="" if show_less else entry["query"] 309 | ) 310 | ) 311 | print("EOM") 312 | 313 | 314 | def main(): 315 | """Run tracing processor, used only if file is executed as a script. 316 | 317 | Args: 318 | None 319 | 320 | Returns: 321 | None 322 | """ 323 | args = parse_args() 324 | cluster = Cluster([args.node_ip], args.node_port) 325 | dbsession = cluster.connect('system_traces') 326 | output = process_sessions( 327 | dbsession, 328 | args.time_threshold, 329 | args.tombstone_threshold 330 | ) 331 | print_output(output, args.result_cap, args.slim) 332 | 333 | if __name__ == '__main__': 334 | try: 335 | main() 336 | except OperationTimedOut: 337 | print( 338 | 'Timeout in gossip communication, ensure cluster is in steady ' 339 | 'state (no nodes leaving or joining) before retrying' 340 | ) 341 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests>=2.9 2 | cassandra-driver>=3.3 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Setup file for cassandra-toolbox. 3 | 4 | Execute `setup.py install` to install the latest cassandra-toolbox scripts 5 | into your environment. You can also execute `setup.py sdist` or 6 | `setup.py bdist` to generate source and binary distributions. 7 | """ 8 | import glob 9 | from setuptools import find_packages, setup 10 | import warnings 11 | 12 | 13 | def get_readme(): 14 | """Get the README from the current directory. 15 | 16 | **Args:** 17 | None 18 | 19 | **Returns:** 20 | str: String is empty if no README file exists. 21 | """ 22 | all_readmes = sorted(glob.glob("README*")) 23 | if len(all_readmes) > 1: 24 | warnings.warn( 25 | "There seems to be more than one README in this directory." 26 | "Choosing the first in lexicographic order." 27 | ) 28 | if len(all_readmes) > 0: 29 | return open(all_readmes[0], 'r').read() 30 | 31 | warnings.warn("There doesn't seem to be a README in this directory.") 32 | return "" 33 | 34 | 35 | def parse_requirements(filename): 36 | """Parse a requirements file . 37 | 38 | Parser ignores comments and -r inclusions of other files. 39 | 40 | **Args:** 41 | filename (str): Path of the requirements file to be parsed 42 | 43 | **Returns:** 44 | list: List of PKG=VERSION strings 45 | """ 46 | reqs = [] 47 | with open(filename, 'r') as f: 48 | for line in f: 49 | hash_idx = line.find('#') 50 | if hash_idx >= 0: 51 | line = line[:hash_idx] 52 | line = line.strip() 53 | reqs.append(line) 54 | return reqs 55 | 56 | 57 | setup( 58 | name="cassandra-toolbox", 59 | version='0.1.5', 60 | author="Knewton Database Team", 61 | author_email="database@knewton.com", 62 | license="Apache2", 63 | url="https://github.com/Knewton/cassandra-toolbox", 64 | packages=find_packages(), 65 | install_requires=parse_requirements('requirements.txt'), 66 | include_package_data=True, 67 | scripts=[ 68 | 'cassandra-toolbox/cassandra-stat', 69 | 'cassandra-toolbox/cassandra-tracing' 70 | ], 71 | description=( 72 | "A suite of tools for Cassandra - A highly scalable distributed " 73 | "NoSQL datastore." 74 | ), 75 | long_description="\n" + get_readme() 76 | ) 77 | --------------------------------------------------------------------------------