├── .gitignore ├── LICENSE ├── README.md ├── gl.py └── orzdba.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Python template 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | env/ 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *,cover 49 | .hypothesis/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | local_settings.py 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # dotenv 85 | .env 86 | 87 | # virtualenv 88 | .venv 89 | venv/ 90 | ENV/ 91 | 92 | # Spyder project settings 93 | .spyderproject 94 | 95 | # Rope project settings 96 | .ropeproject 97 | 98 | .idea 99 | 100 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | orzdba 2 | ====== 3 | 4 | 参照网上的orzdba脚本用python实现的mysql 工具 5 | -------------------------------------------------------------------------------- /gl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | #--------------------------------------------------------------------------- 4 | # 5 | # Author: lubo 6 | # E-mail: 454331202@qq.com 7 | # LastModified: 2014-05-23 11:18:31 8 | # Filename: gl.py 9 | # Desc: 10 | # 11 | #--------------------------------------------------------------------------- 12 | 13 | headline1 = '' 14 | headline2 = '' 15 | mysql_headline1 = '' 16 | mysql_headline2 = '' 17 | ncpu = 0 #Number of processors 18 | # Options Flag 19 | optflag = 0 #whether input opt 20 | timeFlag = 0 # -t : print current time 21 | interval = 1 # -i : time(second) interval 22 | my_load = 0 # -l : print load info 23 | my_cpu = 0 # -c : print cpu info 24 | my_swap = 0 # -s : print swap info 25 | my_disk = None # -d : print disk info 26 | my_net = None # -n : print net info 27 | mysql = 0 # -mysql: print mysql status 28 | mysql_conn ='' # mysql conn info 29 | com = 0; # -com : print mysql status 30 | innodb_hit = 0 # -hit : Print Innodb Hit% 31 | innodb_rows = 0 # -innodb_rows : Print Innodb Rows Status 32 | innodb_pages= 0 # -innodb_pages: Innodb Buffer Pool Pages Status 33 | innodb_data = 0 # -innodb_data : Innodb Data Status 34 | innodb_log = 0 # -innodb_log : Innodb Log Status 35 | innodb_status=0 # -innodb_status: Show Engine Innodb Status 36 | threads = 0 # -T : Print Threads Status 37 | bytes = 0 # -B : Print Bytes Status 38 | my_port = '3306' # default prot 3306 39 | my_socket =None # sockfile 40 | my_pwd =None # root user password 41 | dbrt = 0 # -rt 42 | lock_file='' 43 | tcprstat_logfile='' 44 | tcprstat_dir='/tmp/' 45 | orz_logfile=None 46 | old_console='' 47 | logfile_by_day=0 # one day one logfile 48 | # Variables For : 49 | #-----> Get SysInfo (from /proc/stat): CPU 50 | sys_cpu1 = (0,0,0,0,0,0,0,0) 51 | total_1 = 0 52 | # 53 | #<----- Get SysInfo (from /proc/stat): CPU 54 | #-----> Get SysInfo (from /proc/vmstat): SWAP 55 | swap1 ={'pswpin':0,'pswpout':0} 56 | swap_not_first = 0 57 | #<----- Get SysInfo (from /proc/vmstat): SWAP 58 | #-----> Get SysInfo (from /proc/net/dev): NET 59 | net1 ={'recv':0,'send':0} 60 | net_not_first = 0 61 | #<----- Get SysInfo (from /proc/net/dev): NET 62 | #-----> Get SysInfo (from /proc/diskstats): IO 63 | sys_io1 = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) 64 | io_not_first = 0; # no print first value 65 | #ncpu = `grep processor /proc/cpuinfo | wc -l`; #/* Number of processors */ 66 | # grep "HZ" -R /usr/include/* 67 | # /usr/include/asm-x86_64/param.h:#define HZ 100 68 | HZ = 100 69 | #<----- Get SysInfo (from /proc/diskstats): IO 70 | 71 | #-----> Get Mysql Status 72 | mystat1={"Com_select":0, 73 | "Com_delete":0 , 74 | "Com_update":0, 75 | "Com_insert":0, 76 | "Innodb_buffer_pool_read_requests":0, 77 | "Innodb_rows_inserted":0, 78 | "Innodb_rows_updated":0, 79 | "Innodb_rows_deleted":0, 80 | "Innodb_rows_read":0, 81 | "Threads_created":0, 82 | "Bytes_received":0, 83 | "Bytes_sent":0, 84 | "Innodb_buffer_pool_pages_flushed":0, 85 | "Innodb_data_read":0, 86 | "Innodb_data_reads":0, 87 | "Innodb_data_writes":0, 88 | "Innodb_data_written":0, 89 | "Innodb_os_log_fsyncs":0, 90 | "Innodb_os_log_written":0} 91 | mysql_no_first = 0 92 | #<----- Get Mysql Status 93 | HAS_COLOR=1 94 | count=None #times 95 | python_version='' 96 | -------------------------------------------------------------------------------- /orzdba.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | # --------------------------------------------------------------------------- 4 | # 5 | # Author: lubo 6 | # E-mail: 454331202@qq.com 7 | # LastModified: 2014-05-26 15:49:21 8 | # Filename: orzdba.py 9 | # Desc: 10 | # 11 | # --------------------------------------------------------------------------- 12 | from __future__ import division 13 | from __future__ import print_function 14 | import sys 15 | 16 | if sys.version_info < (2, 7): 17 | sys.exit('error: Python 2.7 or later required') 18 | import time 19 | import datetime 20 | import os 21 | import operator 22 | import subprocess 23 | import socket 24 | import fcntl 25 | import struct 26 | import getopt 27 | import argparse 28 | import signal 29 | import gl 30 | import multiprocessing 31 | import atexit 32 | import math 33 | 34 | ATTRIBUTES = dict( 35 | list(zip([ 36 | 'bold', 37 | 'dark', 38 | '', 39 | 'underline', 40 | 'blink', 41 | '', 42 | 'reverse', 43 | 'concealed' 44 | ], 45 | list(range(1, 9)) 46 | )) 47 | ) 48 | del ATTRIBUTES[''] 49 | HIGHLIGHTS = dict( 50 | list(zip([ 51 | 'on_grey', 52 | 'on_red', 53 | 'on_green', 54 | 'on_yellow', 55 | 'on_blue', 56 | 'on_magenta', 57 | 'on_cyan', 58 | 'on_white' 59 | ], 60 | list(range(40, 48)) 61 | )) 62 | ) 63 | 64 | COLORS = dict( 65 | list(zip([ 66 | 'grey', 67 | 'red', 68 | 'green', 69 | 'yellow', 70 | 'blue', 71 | 'magenta', 72 | 'cyan', 73 | 'white', 74 | ], 75 | list(range(30, 38)) 76 | )) 77 | ) 78 | 79 | RESET = '\033[0m' 80 | 81 | 82 | # --------------------------------------------------------------------------- 83 | # Function: 84 | # ChangeLog: 85 | # --------------------------------------------------------------------------- 86 | def colored(text, color=None, on_color=None, attrs=None): 87 | """Colorize text. 88 | 89 | Available text colors: 90 | red, green, yellow, blue, magenta, cyan, white. 91 | 92 | Available text highlights: 93 | on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. 94 | 95 | Available attributes: 96 | bold, dark, underline, blink, reverse, concealed. 97 | 98 | Example: 99 | colored('Hello, World!', 'red', 'on_grey', ['blue', 'blink']) 100 | colored('Hello, World!', 'green') 101 | """ 102 | if gl.HAS_COLOR: 103 | if os.getenv('ANSI_COLORS_DISABLED') is None: 104 | fmt_str = '\033[%dm%s' 105 | if color is not None: 106 | text = fmt_str % (COLORS[color], text) 107 | 108 | if on_color is not None: 109 | text = fmt_str % (HIGHLIGHTS[on_color], text) 110 | 111 | if attrs is not None: 112 | for attr in attrs: 113 | text = fmt_str % (ATTRIBUTES[attr], text) 114 | text += RESET 115 | return text 116 | 117 | 118 | def cprint(text, color=None, on_color=None, attrs=None, **kwargs): 119 | """Print colorize text. 120 | 121 | It accepts arguments of print function. 122 | """ 123 | 124 | print((colored(text, color, on_color, attrs)), **kwargs) 125 | 126 | 127 | def hostname(): 128 | """ 129 | 获取主机名称 130 | :return: 131 | """ 132 | sys = os.name 133 | if sys == 'nt': 134 | hostname = os.getenv('computername') 135 | return hostname 136 | elif sys == 'posix': 137 | hostname = socket.gethostname() 138 | return hostname 139 | else: 140 | return 'Unkwon hostname' 141 | 142 | 143 | def Get_local_ip(): 144 | """ 145 | Returns the actual ip of the local machine. 146 | This code figures out what source address would be used if some traffic 147 | were to be sent out to some well known address on the Internet. In this 148 | case, a Google DNS server is used, but the specific address does not 149 | matter much. No traffic is actually sent. 150 | """ 151 | try: 152 | csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 153 | csock.connect(('8.8.8.8', 80)) 154 | (addr, port) = csock.getsockname() 155 | csock.close() 156 | return addr 157 | except socket.error: 158 | return "127.0.0.1" 159 | 160 | 161 | def get_ip_address(): 162 | """ 163 | 164 | :return: 165 | """ 166 | localIP = Get_local_ip() 167 | return localIP 168 | 169 | 170 | def catch_zap(signalNun, currentStackFrame): 171 | # cprint ("\nExit Now...\n\n",'red') 172 | sys.exit(0) 173 | 174 | 175 | def convertBytes(bytes, lst=None): 176 | """ 177 | 178 | :param bytes: 179 | :param lst: 180 | :return: 181 | """ 182 | if lst is None: 183 | lst = ['Bytes', 'K', 'M', 'G', 'TB', 'PB', 'EB'] 184 | i = int(math.floor( # 舍弃小数点,取小 185 | math.log(bytes, 1024) # 求对数(对数:若 a**b = N 则 b 叫做以 a 为底 N 的对数) 186 | )) 187 | 188 | if i >= len(lst): 189 | i = len(lst) - 1 190 | return ('%.0f' + lst[i]) % (bytes / math.pow(1024, i)) 191 | 192 | 193 | @atexit.register 194 | def ClearFile(): 195 | if gl.dbrt: 196 | if os.path.isfile(gl.lock_file): 197 | try: 198 | os.remove(gl.lock_file) 199 | except OSError: 200 | os.system("rm -f %s" % gl.lock_file) 201 | if os.path.isfile(gl.tcprstat_logfile): 202 | try: 203 | os.remove(gl.tcprstat_logfile) 204 | except OSError: 205 | os.system("rm -f %s" % gl.tcprstat_logfile) 206 | if gl.orz_logfile is not None: 207 | sys.stdout.close 208 | sys.stdout = gl.old_console 209 | gl.HAS_COLOR = 1 210 | cprint('--------write log end--------------------------', 'green', end='') 211 | cprint("\nExit Now...\n\n", 'red') 212 | 213 | 214 | # --------------------------------------------------------------------------- 215 | # Function: 216 | # ChangeLog: 217 | # --------------------------------------------------------------------------- 218 | def get_options(): 219 | # define args 220 | parser = argparse.ArgumentParser( 221 | description='Created By lubo 454331202@qq.com') 222 | parser.add_argument('-i', '--interval', action='store', 223 | help='Time(second) Interval.', type=int, default=1) 224 | parser.add_argument('-t', '--time', action='store_true', 225 | help='Print The Current Time.') 226 | parser.add_argument('-sys', action='store_true', 227 | help='print SysInfo (include -l,-c,-s).') 228 | parser.add_argument('-l', '--load', action='store_true', 229 | help='Print Load Info.') 230 | parser.add_argument('-c', '--cpu', action='store_true', 231 | help='Print Cpu Info.') 232 | parser.add_argument('-d', '--disk', action='store', 233 | help='Print Disk Info.') 234 | parser.add_argument('-n', '--net', action='store', 235 | help='Print Net Info.Time.') 236 | parser.add_argument('-s', '--swap', action='store_true', 237 | help='Print The Swap Info.') 238 | parser.add_argument('-com', action='store_true', 239 | help='print mysql status.') 240 | parser.add_argument('-innodb_rows', action='store_true', 241 | help='Print Innodb Rows Status.') 242 | parser.add_argument('-innodb_pages', action='store_true', 243 | help=' Print Innodb Buffer Pool Pages Status.') 244 | parser.add_argument('-innodb_data', action='store_true', 245 | help='Print Innodb Data Status.') 246 | parser.add_argument('-innodb_log', action='store_true', 247 | help='Print Innodb Log Status.') 248 | parser.add_argument('-innodb_status', action='store_true', 249 | help='Print Innodb Status from Command: "Show Engine Innodb Status".') 250 | parser.add_argument('-innodb', action='store_true', 251 | help='Print Innodb Info.') 252 | parser.add_argument('-T', '--threads', action='store_true', 253 | help='Print Threads Status.') 254 | parser.add_argument('-B', '--bytes', action='store_true', 255 | help='Print Bytes Status.') 256 | parser.add_argument('-rt', action='store_true', help='Print MySQL DB RT.') 257 | parser.add_argument('-hit', action='store_true', help='Print Innodb Hit%%') 258 | parser.add_argument('-mysql', action='store_true', 259 | help='print SysInfo (Print MySQLInfo (include -t,-com,-hit,-T,-B).') 260 | parser.add_argument('-P', '--port', action='store', 261 | help='Port number to use for mysql connection(default 3306).') 262 | parser.add_argument('-S', '--socket', action='store', 263 | help='Socket file to use for mysql connection.') 264 | parser.add_argument('-p', '--pwd', action='store', 265 | help='root user password.') 266 | parser.add_argument('-C', '--count', action='store', 267 | help='Times.', type=int) 268 | parser.add_argument('-L', '--logfile', action='store', 269 | help='ath of logfile.') 270 | parser.add_argument('-logfile_by_day', 271 | action='store_true', help='one day a logfile.') 272 | parser.add_argument('-lazy', action='store_true', 273 | help='Print Info (include -t,-l,-c,-s,-m,-hit).') 274 | parser.add_argument('--nocolor', action='store_true', 275 | help='Print NO color.') 276 | 277 | # parser.print_help() 278 | opts = parser.parse_args() 279 | # parser.print_usage() 280 | if opts.lazy: 281 | opts.time = opts.load = opts.cpu = opts.swap = opts.com = gl.mysql = 1 282 | 283 | if ( 284 | opts.threads or opts.bytes or opts.rt or opts.com or opts.hit or opts.innodb_rows or opts.innodb_pages or opts.innodb_data or opts.innodb_log or opts.innodb_status): 285 | gl.mysql = 1 286 | 287 | if opts.sys: 288 | opts.time = opts.load = opts.cpu = opts.swap = opts.time = 1 289 | 290 | if opts.innodb: 291 | opts.time = opts.innodb_pages = opts.innodb_data = opts.innodb_log = opts.innodb_status = gl.mysql = 1 292 | 293 | if opts.mysql: 294 | gl.mysql = opts.time = opts.com = opts.hit = opts.threads = opts.bytes = 1 295 | if opts.nocolor or opts.logfile is not None: 296 | gl.HAS_COLOR = 0 297 | else: 298 | gl.HAS_COLOR = 1 299 | if opts.logfile is not None: 300 | gl.orz_logfile = opts.logfile 301 | if opts.logfile_by_day: 302 | gl.logfile_by_day = opts.logfile_by_day 303 | 304 | # set Headline 305 | if opts.time: 306 | gl.headline1 = colored('--------', 'blue', attrs=['bold']) 307 | gl.headline2 = colored(' time |', 'blue', attrs=[ 308 | 'bold', 'underline']) 309 | gl.timeFlag = 1 310 | gl.optflag = 1 311 | if opts.load: 312 | gl.headline1 += colored(' -----load-avg----', 'blue', attrs=['bold']) 313 | gl.headline2 += colored(' 1m 5m 15m |', 314 | 'blue', attrs=['bold', 'underline']) 315 | gl.my_load = 1 316 | gl.optflag = 1 317 | if opts.cpu: 318 | gl.headline1 += colored(' ---cpu-usage--- ', 'blue', attrs=['bold']) 319 | gl.headline2 += colored('usr sys idl iow|', 320 | 'blue', attrs=['bold', 'underline']) 321 | gl.my_cpu = 1 322 | gl.optflag = 1 323 | if opts.swap: 324 | gl.headline1 += colored('---swap--- ', 'blue', attrs=['bold']) 325 | gl.headline2 += colored(' si so|', 'blue', 326 | attrs=['bold', 'underline']) 327 | gl.my_swap = 1 328 | gl.optflag = 1 329 | if opts.net: 330 | gl.headline1 += colored(' -----net(B)----- ', 'blue', attrs=['bold']) 331 | gl.headline2 += colored(' recv send |', 332 | 'blue', attrs=['bold', 'underline']) 333 | gl.optsflag = 1 334 | if opts.disk: 335 | gl.headline1 += colored( 336 | '-------------------------io-usage----------------------- ', 'blue', attrs=['bold']) 337 | gl.headline2 += colored(' r/s w/s rkB/s wkB/s queue await svctm \%util|', 'blue', 338 | attrs=['bold', 'underline']) 339 | gl.optsflag = 1 340 | 341 | if opts.com: 342 | gl.mysql_headline1 += colored('-----------QPS--TPS----------- ', 343 | 'green', 'on_blue', attrs=['bold']) 344 | gl.mysql_headline2 += colored(' ins upd del sel iud|', 345 | 'green', attrs=['bold', 'underline']) 346 | gl.com = gl.optflag = 1 347 | if opts.hit: 348 | gl.mysql_headline1 += colored('------Hit%----- ', 349 | 'green', 'on_blue', attrs=['bold']) 350 | gl.mysql_headline2 += colored(' lor hit|', 351 | 'green', attrs=['bold', 'underline']) 352 | gl.innodb_hit = gl.optflag = 1 353 | if opts.innodb_rows: 354 | gl.mysql_headline1 += colored('---innodb rows status--- ', 355 | 'green', 'on_blue', attrs=['bold']) 356 | gl.mysql_headline2 += colored(' ins upd del read|', 357 | 'green', attrs=['bold', 'underline']) 358 | gl.innodb_rows = gl.optflag = 1 359 | if opts.innodb_pages: 360 | gl.mysql_headline1 += colored('---innodb bp pages status-- ', 361 | 'green', 'on_blue', attrs=['bold']) 362 | gl.mysql_headline2 += colored(' data free dirty flush|', 363 | 'green', attrs=['bold', 'underline']) 364 | gl.innodb_pages = gl.optflag = 1 365 | if opts.innodb_data: 366 | gl.mysql_headline1 += colored('-----innodb data status---- ', 367 | 'green', 'on_blue', attrs=['bold']) 368 | gl.mysql_headline2 += colored(' reads writes read written|', 369 | 'green', attrs=['bold', 'underline']) 370 | gl.innodb_data = gl.optflag = 1 371 | if opts.innodb_log: 372 | gl.mysql_headline1 += colored('--innodb log-- ', 373 | 'green', 'on_blue', attrs=['bold']) 374 | gl.mysql_headline2 += colored('fsyncs written|', 375 | 'green', attrs=['bold', 'underline']) 376 | gl.innodb_log = gl.optflag = 1 377 | if opts.innodb_status: 378 | gl.mysql_headline1 += colored(' his --log(byte)-- read ---query--- ', 379 | 'green', 'on_blue', attrs=['bold']) 380 | gl.mysql_headline2 += colored(' list uflush uckpt view inside que|', 381 | 'green', attrs=['bold', 'underline']) 382 | gl.innodb_status = gl.optflag = 1 383 | if opts.threads: 384 | gl.mysql_headline1 += colored('------threads------ ', 385 | 'green', 'on_blue', attrs=['bold']) 386 | gl.mysql_headline2 += colored(' run con cre cac|', 387 | 'green', attrs=['bold', 'underline']) 388 | gl.threads = gl.optflag = 1 389 | if opts.bytes: 390 | gl.mysql_headline1 += colored('-----bytes---- ', 391 | 'green', 'on_blue', attrs=['bold']) 392 | gl.mysql_headline2 += colored(' recv send|', 393 | 'green', attrs=['bold', 'underline']) 394 | gl.bytes = gl.optflag = 1 395 | if opts.rt: 396 | gl.mysql_headline1 += colored('--------tcprstat(us)-------- ', 397 | 'green', 'on_blue', attrs=['bold']) 398 | gl.mysql_headline2 += colored(' count avg 95-avg 99-avg|', 399 | 'green', attrs=['bold', 'underline']) 400 | gl.dbrt = gl.optflag = 1 401 | if opts.port is not None: 402 | gl.my_port = opts.port 403 | if opts.socket is not None: 404 | gl.my_socket = opts.socket 405 | if opts.net is not None: 406 | gl.my_net = opts.net 407 | if opts.disk is not None: 408 | gl.my_disk = opts.disk 409 | if opts.count is not None: 410 | gl.count = opts.count 411 | if opts.pwd is not None: 412 | gl.my_pwd = opts.pwd 413 | 414 | gl.interval = opts.interval 415 | if gl.optflag == 0: 416 | parser.print_help() 417 | return opts 418 | 419 | 420 | # --------------------------------------------------------------------------- 421 | # 6. 422 | # Function: 423 | # ChangeLog: 424 | # --------------------------------------------------------------------------- 425 | def Print_title(): 426 | cprint("\n") 427 | cprint('.=================================================.', 'green') 428 | cprint('| Welcome to use the orzdba tool ! |', 'green') 429 | cprint('| Yep...Chinese English~ |', 'green') 430 | cprint('| Created by lubo qq:454331202~ |', 'green') 431 | cprint(colored("'=============== Date: ", 'green') + colored(time.strftime("%Y-%m-%d", time.localtime()), 432 | 'red') + colored(" ================'" + "\n", 'green')) 433 | cprint( 434 | colored('HOST: ', 'red') + colored(hostname(), 'yellow') + colored(" IP: ", 'red') + colored(get_ip_address(), 435 | 'yellow')) 436 | 437 | # Get MYSQL DB Name and Variables 438 | if gl.mysql: 439 | (dbname, vars1, vars2) = get_mysql_vars() 440 | cprint(colored('Ver : ', 'red') + 441 | colored(dbversion + ' ' + dbversion_comment, 'yellow')) 442 | cprint(colored('DB : ', 'red') + colored(dbname, 'yellow')) 443 | cprint(colored('Var : ', 'red'), end='') 444 | i = 0 445 | for var in vars1: 446 | x = var.rstrip() 447 | (vname, vvalue) = x.split("\t") 448 | if i % 3 == 0 and i != 0: 449 | cprint(colored(' ' + vname, 'magenta') + 450 | colored('[', 'white'), end='') 451 | else: 452 | cprint(colored(vname, 'magenta') + 453 | colored('[', 'white'), end='') 454 | 455 | if operator.eq(vname, 'max_binlog_cache_size') or operator.eq(vname, 'max_binlog_size'): 456 | cprint(colored(convertBytes(float(vvalue)) + ']', 'white'), end='') 457 | else: 458 | cprint(colored(vvalue + ']', 'white'), end='') 459 | i += 1 460 | if i % 3 == 0: 461 | cprint('') 462 | cprint('\n') 463 | i = 0 464 | for var in vars2: 465 | x = var.rstrip() 466 | vvars = x.split("\t") 467 | if len(vvars) == 2: 468 | (vname, vvalue) = vvars 469 | 470 | if i % 3 == 0: 471 | cprint(colored(' ' + vname, 'magenta') + 472 | colored('[', 'white'), end='') 473 | else: 474 | cprint(colored(vname, 'magenta') + 475 | colored('[', 'white'), end='') 476 | 477 | if operator.eq(vname, 'innodb_log_file_size') or operator.eq(vname, 478 | 'innodb_log_buffer_size') or operator.eq(vname, 479 | 'innodb_buffer_pool_size'): 480 | 481 | # if float(vvalue) / 1024 / 1024 / 1024 >= 1: 482 | # cprint("{:.0f}".format(int(vvalue) / 1024 / 1024 / 1024), 'white', end='') 483 | # cprint('G]', 'white', end='') 484 | # else: 485 | # if float(vvalue) / 1024 / 1024 >= 1: 486 | # cprint("{:.0f}".format(int(vvalue) / 1024 / 1024), 'white', end='') 487 | # cprint('M]', 'white', end='') 488 | # else: 489 | # cprint(colored(vvalue + ']', 'white'), end='') 490 | 491 | cprint(colored(convertBytes(float(vvalue)) + ']', 'white'), end='') 492 | 493 | else: 494 | cprint(colored(vvalue + ']', 'white'), end='') 495 | i += 1 496 | if i % 3 == 0: 497 | cprint('') 498 | cprint('\n') 499 | 500 | 501 | def get_mysql_vars(): 502 | """ 503 | 504 | :return: 505 | """ 506 | # get dbname 507 | # global dbname,dbversion 508 | p = subprocess.Popen( 509 | gl.mysql_conn + ' -e "show databases" |grep -iwvE "information_schema|mysql|test" | tr "\n" "|"', shell=True, 510 | stdout=subprocess.PIPE) 511 | out = p.communicate()[0] 512 | if gl.python_version.major == 3: 513 | dbname = str(out).rstrip('|') 514 | elif gl.python_version.major == 2: 515 | dbname = out.rstrip('|') 516 | # get variables 517 | s1 = 'show variables where Variable_name in ("sync_binlog","max_connections","max_user_connections",' \ 518 | '"max_connect_errors","table_open_cache","table_definition_cache","thread_cache_size","binlog_format",' \ 519 | '"open_files_limit") ' 520 | # "max_binlog_size","max_binlog_cache_size" 521 | p = subprocess.Popen(gl.mysql_conn + " -e '" + s1 + 522 | "'", shell=True, stdout=subprocess.PIPE) 523 | out = p.communicate()[0].rstrip() 524 | # cprint(str(gl.python_version.major)) 525 | if gl.python_version.major == 2: 526 | vars1 = out.split('\n') 527 | elif gl.python_version.major == 3: 528 | vars1 = str(out).split('\n') 529 | s1 = 'show variables where Variable_name in ("innodb_flush_log_at_trx_commit","innodb_flush_method",' \ 530 | '"innodb_buffer_pool_size","innodb_max_dirty_pages_pct","innodb_log_buffer_size","innodb_log_file_size",' \ 531 | '"innodb_log_files_in_group","innodb_thread_concurrency","innodb_file_per_table",' \ 532 | '"innodb_adaptive_hash_index","innodb_open_files","innodb_io_capacity","innodb_read_io_threads",' \ 533 | '"innodb_write_io_threads","innodb_adaptive_flushing","innodb_lock_wait_timeout","innodb_log_files_in_group") ' 534 | p = subprocess.Popen(gl.mysql_conn + " -e '" + s1 + 535 | "'", shell=True, stdout=subprocess.PIPE) 536 | out = p.communicate()[0].rstrip() 537 | if gl.python_version.major == 2: 538 | vars2 = out.split('\n') 539 | elif gl.python_version.major == 3: 540 | vars2 = str(out).split('\n') 541 | # cprint (vars2) 542 | return (dbname, vars1, vars2) 543 | 544 | 545 | def get_mysql_version(): 546 | """ 547 | 548 | :return: 549 | """ 550 | global dbversion, dbversion_comment 551 | ss = 'show variables where Variable_name in ("version","version_comment") ' 552 | p = subprocess.Popen( 553 | gl.mysql_conn + " -e '" + ss + "'", shell=True, stdout=subprocess.PIPE) 554 | out = p.communicate()[0].rstrip() 555 | if gl.python_version.major == 2: 556 | vars1 = out.split('\n') 557 | elif gl.python_version.major == 3: 558 | vars1 = str(out).split('\n') 559 | 560 | for var in vars1: 561 | x = var.rstrip() 562 | (vname, vvalue) = x.split("\t") 563 | if operator.eq(vname, 'version'): 564 | dbversion = vvalue 565 | if operator.eq(vname, 'version_comment'): 566 | dbversion_comment = vvalue 567 | 568 | # --------------------------------------------------------------------------- 569 | # 8. 570 | # Function: 571 | # ChangeLog: 572 | # --------------------------------------------------------------------------- 573 | 574 | 575 | def load_stat(): 576 | loadavg = {} 577 | f = open("/proc/loadavg") 578 | con = f.read().split() 579 | f.close() 580 | loadavg['lavg_1'] = con[0] 581 | loadavg['lavg_5'] = con[1] 582 | loadavg['lavg_15'] = con[2] 583 | loadavg['nr'] = con[3] 584 | loadavg['last_pid'] = con[4] 585 | return loadavg 586 | 587 | 588 | # --------------------------------------------------------------------------- 589 | # 9. 590 | # Function: 591 | # ChangeLog: 592 | # --------------------------------------------------------------------------- 593 | def readCpuInfo(): 594 | # line format :(http://blog.csdn.net/nineday/archive/2007/12/11/1928847.aspx) 595 | # cpu 1-user 2-nice 3-system 4-idle 5-iowait 6-irq 7-softirq 596 | cpuinfo = {} 597 | f = open('/proc/stat') 598 | lines = f.readlines() 599 | f.close() 600 | 601 | for line in lines: 602 | line = line.lstrip() 603 | sys_cpu2 = line.split() 604 | if len(sys_cpu2) < 5: 605 | continue 606 | if sys_cpu2[0].startswith('cpu'): 607 | break 608 | 609 | total_2 = 0 610 | for i in range(1, len(sys_cpu2)): 611 | total_2 = total_2 + int(sys_cpu2[i]) 612 | 613 | user_diff = int(sys_cpu2[1]) + int(sys_cpu2[2]) - \ 614 | int(gl.sys_cpu1[1]) - int(gl.sys_cpu1[2]) 615 | system_diff = int(sys_cpu2[3]) + int(sys_cpu2[6]) + int(sys_cpu2[7]) - int(gl.sys_cpu1[3]) - int( 616 | gl.sys_cpu1[6]) - int(gl.sys_cpu1[7]) 617 | idle_diff = int(sys_cpu2[4]) - int(gl.sys_cpu1[4]) 618 | iowait_diff = int(sys_cpu2[5]) - int(gl.sys_cpu1[5]) 619 | total_diff = total_2 - gl.total_1 620 | user_diff_1 = int((user_diff / total_diff) * 100 + 0.5) 621 | system_diff_1 = int((system_diff / total_diff) * 100 + 0.5) 622 | idle_diff_1 = int((idle_diff / total_diff) * 100 + 0.5) 623 | iowait_diff_1 = int((iowait_diff / total_diff) * 100 + 0.5) 624 | cpuinfo['userdiff_t'] = user_diff_1 625 | cpuinfo['systemdiff_t'] = system_diff_1 626 | cpuinfo['idlediff_t'] = idle_diff_1 627 | cpuinfo['iowaitdiff_t'] = iowait_diff_1 628 | cpuinfo['userdiff'] = user_diff 629 | cpuinfo['systemdiff'] = system_diff 630 | cpuinfo['idlediff'] = idle_diff 631 | cpuinfo['iowaitdiff'] = iowait_diff 632 | gl.sys_cpu1 = sys_cpu2 633 | gl.total_1 = total_2 634 | return cpuinfo 635 | 636 | 637 | # --------------------------------------------------------------------------- 638 | # 10. 639 | # Function: 640 | # ChangeLog: 641 | # --------------------------------------------------------------------------- 642 | def get_swap(): 643 | # Get SysInfo (from /proc/vmstat): SWAP 644 | # Detail Info : http://www.linuxinsight.com/proc_vmstat.html 645 | # pswpin/s:每秒系统换入的交换页面(swap page)数量 646 | # pswpout/s:每秒系统换出的交换页面(swap page)数量 647 | swap2 = {'pswpin': 0, 'pswpout': 0} 648 | pswapinfo = {} 649 | p = subprocess.Popen('cat /proc/vmstat |grep -E "pswpin|pswpout"', 650 | shell=True, stdout=subprocess.PIPE, bufsize=0) 651 | out = p.communicate() 652 | lines = out[0] 653 | if lines: 654 | x = lines.replace(b'\n', b' ') 655 | x = x.split() 656 | swap2['pswpin'] = x[1] 657 | swap2['pswpout'] = x[3] 658 | if gl.swap_not_first: 659 | pswpindiff = int(swap2['pswpin']) - int(gl.swap1['pswpin']) 660 | pswpoutdiff = int(swap2['pswpout']) - int(gl.swap1['pswpout']) 661 | else: 662 | pswpindiff = 0 663 | pswpoutdiff = 0 664 | pswapinfo['pswpin'] = pswpindiff 665 | pswapinfo['pswpout'] = pswpoutdiff 666 | gl.swap1 = swap2 667 | gl.swap_not_first += 1 668 | return pswapinfo 669 | 670 | 671 | # --------------------------------------------------------------------------- 672 | # 11. 673 | # Function: 674 | # ChangeLog: 675 | # --------------------------------------------------------------------------- 676 | def readNetInfo(dev): 677 | net2 = {} 678 | netdiff = {} 679 | fd = open("/proc/net/dev", "r") 680 | for line in fd.readlines(): 681 | if line.find(dev) > 0: 682 | field = line.split() 683 | net2['recv'] = field[1] 684 | net2['send'] = field[9] 685 | fd.close() 686 | # p=subprocess.Popen('cat /proc/net/dev |grep "\\b'+dev+'\\b"',shell=True,stdout=subprocess.PIPE) 687 | # while p.poll()==None: 688 | # lines = p.stdout.readlines() 689 | # for line in lines: 690 | # line=line.replace(':',' ') 691 | # items=line.split() 692 | # net2['recv']=items[1] 693 | # net2['send']=items[9] 694 | if net2: 695 | if gl.net_not_first: 696 | recv_diff = (float(net2['recv']) - 697 | float(gl.net1['recv'])) / gl.interval 698 | send_diff = (float(net2['send']) - 699 | float(gl.net1['send'])) / gl.interval 700 | else: 701 | recv_diff = 0 702 | send_diff = 0 703 | netdiff['recv'] = recv_diff 704 | netdiff['send'] = send_diff 705 | gl.net1 = net2 706 | gl.net_not_first += 1 707 | else: 708 | netdiff = None 709 | return netdiff 710 | 711 | 712 | # --------------------------------------------------------------------------- 713 | # 12. 714 | # Function: 715 | # ChangeLog: 716 | # --------------------------------------------------------------------------- 717 | def readDiskInfo(dev, deltams): 718 | # Detail IO Info : 719 | # (1) http://www.mjmwired.net/kernel/Documentation/iostats.txt 720 | # (2) http://www.linuxinsight.com/iostat_utility.html 721 | # (3) source code --> http://www.linuxinsight.com/files/iostat-2.2.tar.gz 722 | # iostat --> line format : 723 | # 0 1 2 3 4 5 6 7 8 9 10 11 724 | # Device: rrqm/s wrqm/s r/s w/s rkB/s wkB/s avgrq-sz avgqu-sz await svctm %util 725 | # sda 0.05 12.44 0.42 7.60 5.67 80.15 21.42 0.04 4.63 0.55 0.44 726 | 727 | sys_io2 = None 728 | sys_iodiff = {} 729 | p = subprocess.Popen('cat /proc/diskstats |grep "\\b' + dev + '\\b"', shell=True, stdout=subprocess.PIPE, 730 | stderr=subprocess.PIPE, bufsize=0) 731 | out = p.communicate()[0] 732 | sys_io2 = out.split() 733 | # print len(sys_io2) 734 | if sys_io2 is None or len(sys_io2) == 0: 735 | return None 736 | # /* Read I/O operations */ 737 | rd_ios = float(sys_io2[3]) - float(gl.sys_io1[3]) 738 | rd_merges = float(sys_io2[4]) - float(gl.sys_io1[4]) # /* Reads merged */ 739 | rd_sectors = float(sys_io2[5]) - float(gl.sys_io1[5]) # /* Sectors read */ 740 | # /* Time in queue + service for read */ 741 | rd_ticks = float(sys_io2[6]) - float(gl.sys_io1[6]) 742 | # /* Write I/O operations */ 743 | wr_ios = float(sys_io2[7]) - float(gl.sys_io1[7]) 744 | wr_merges = float(sys_io2[8]) - float(gl.sys_io1[8]) # /* Writes merged */ 745 | # /* Sectors written */ 746 | wr_sectors = float(sys_io2[9]) - float(gl.sys_io1[9]) 747 | # /* Time in queue + service for write */ 748 | wr_ticks = float(sys_io2[10]) - float(gl.sys_io1[10]) 749 | # /* Time of requests in queue */ 750 | ticks = float(sys_io2[12]) - float(gl.sys_io1[12]) 751 | # /* Average queue length */ 752 | aveq = float(sys_io2[13]) - float(gl.sys_io1[13]) 753 | 754 | n_ios = 0 # /* Number of requests */ 755 | n_ticks = 0 # /* Total service time */ 756 | n_kbytes = 0 # /* Total kbytes transferred */ 757 | busy = 0 # /* Utilization at disk (percent) */ 758 | svc_t = 0 # /* Average disk service time */ 759 | wait = 0 # /* Average wait */ 760 | size = 0 # /* Average request size */ 761 | queue = 0 # /* Average queue */ 762 | 763 | n_ios = rd_ios + wr_ios 764 | n_ticks = rd_ticks + wr_ticks 765 | n_kbytes = (rd_sectors + wr_sectors) / 2.0 766 | queue = aveq / deltams 767 | if n_ios == 0: 768 | size = 0 769 | wait = 0 770 | svc_t = 0 771 | else: 772 | size = n_kbytes / n_ios 773 | wait = n_ticks / n_ios 774 | svc_t = ticks / n_ios 775 | 776 | busy = 100.0 * ticks / deltams # /* percentage! */ 777 | if busy > 100: 778 | busy = 100 # 779 | rkbs = (1000.0 * rd_sectors / deltams / 2) 780 | wkbs = (1000.0 * wr_sectors / deltams / 2) 781 | # r/s w/s 782 | rd_ios_s = (1000.0 * rd_ios / deltams) 783 | wr_ios_s = (1000.0 * wr_ios / deltams) 784 | # $rkbs,$wkbs,$queue,$wait,$svc_t,$busy 785 | sys_iodiff['rkbs'] = rkbs 786 | sys_iodiff['wkbs'] = wkbs 787 | sys_iodiff['queue'] = queue 788 | sys_iodiff['wait'] = wait 789 | sys_iodiff['svc_t'] = svc_t 790 | sys_iodiff['busy'] = busy 791 | sys_iodiff['rd_ios_s'] = rd_ios_s 792 | sys_iodiff['wr_ios_s'] = wr_ios_s 793 | gl.sys_io1 = sys_io2 794 | return sys_iodiff 795 | 796 | 797 | # --------------------------------------------------------------------------- 798 | # 13. 799 | # Function: Get Innodb Status from Command: 'Show Engine Innodb Status' 800 | # ChangeLog: 801 | # --------------------------------------------------------------------------- 802 | def get_innodb_status(): 803 | innodb_status = {} 804 | s1 = 'show engine innodb status' 805 | p = subprocess.Popen(gl.mysql_conn + " -e '" + s1 + 806 | "'", shell=True, stdout=subprocess.PIPE) 807 | out = p.communicate()[0].rstrip() 808 | vars = out.split('\\n') 809 | # print vars 810 | # http://code.google.com/p/mysql-cacti-templates/source/browse/trunk/scripts/ss_get_mysql_stats.php 811 | # print len(vars) 812 | for var in vars: 813 | if var.find('History list length') > -1: 814 | items = var.split() 815 | innodb_status['history_list'] = items[3] 816 | elif var.find('Log sequence number') > -1: 817 | items = var.split() 818 | innodb_status['log_bytes_written'] = items[3] 819 | elif var.find('Log flushed up to') > -1: 820 | items = var.split() 821 | innodb_status['log_bytes_flushed'] = items[4] 822 | elif var.find('Last checkpoint at') > -1: 823 | items = var.split() 824 | innodb_status['last_checkpoint'] = items[3] 825 | elif var.find('queries inside InnoDB') > -1: 826 | items = var.split() 827 | innodb_status['queries_inside'] = items[0] 828 | innodb_status['queries_queued'] = items[4] 829 | elif var.find('read views open inside InnoDB') > -1: 830 | items = var.split() 831 | innodb_status['read_views'] = items[0] 832 | # elif var.find('')>-1: 833 | # items=var.split() 834 | # print items 835 | # innodb_status['']=items[3] 836 | innodb_status['unflushed_log'] = int( 837 | innodb_status['log_bytes_written']) - int(innodb_status['log_bytes_flushed']) 838 | innodb_status['uncheckpointed_bytes'] = int(innodb_status['log_bytes_written']) - int( 839 | innodb_status['last_checkpoint']) 840 | return innodb_status 841 | 842 | 843 | # --------------------------------------------------------------------------- 844 | # 14. 845 | # Function: 846 | # ChangeLog: 847 | # --------------------------------------------------------------------------- 848 | def get_mysqlstat(): 849 | mystat2 = {} 850 | if gl.mysql: 851 | s1 = 'show global status where Variable_name in ("Com_select","Com_insert","Com_update","Com_delete","Innodb_buffer_pool_read_requests","Innodb_buffer_pool_reads","Innodb_rows_inserted","Innodb_rows_updated","Innodb_rows_deleted","Innodb_rows_read","Threads_running","Threads_connected","Threads_cached","Threads_created","Bytes_received","Bytes_sent","Innodb_buffer_pool_pages_data","Innodb_buffer_pool_pages_free","Innodb_buffer_pool_pages_dirty","Innodb_buffer_pool_pages_flushed","Innodb_data_reads","Innodb_data_writes","Innodb_data_read","Innodb_data_written","Innodb_os_log_fsyncs","Innodb_os_log_written")' 852 | p = subprocess.Popen(gl.mysql_conn + " -e '" + 853 | s1 + "'", shell=True, stdout=subprocess.PIPE) 854 | out = p.communicate()[0].rstrip() 855 | # print out 856 | if gl.python_version.major == 2: 857 | vars = out.split('\n') 858 | for var in vars: 859 | (vname, vvalue) = var.split('\t') 860 | mystat2[vname] = vvalue 861 | elif gl.python_version.major == 3: 862 | vars = str(out).split('\n') 863 | for var in vars: 864 | (vname, vvalue) = var.split('\t') 865 | mystat2[vname] = vvalue 866 | # print gl.mysql_no_first 867 | if gl.mysql_no_first: 868 | insert_diff = (int(mystat2["Com_insert"]) - 869 | int(gl.mystat1["Com_insert"])) / gl.interval 870 | update_diff = (int(mystat2["Com_update"]) - 871 | int(gl.mystat1["Com_update"])) / gl.interval 872 | delete_diff = (int(mystat2["Com_delete"]) - 873 | int(gl.mystat1["Com_delete"])) / gl.interval 874 | select_diff = (int(mystat2["Com_select"]) - 875 | int(gl.mystat1["Com_select"])) / gl.interval 876 | read_request = (int(mystat2["Innodb_buffer_pool_read_requests"]) - int( 877 | gl.mystat1["Innodb_buffer_pool_read_requests"])) / gl.interval 878 | read = ( 879 | int(mystat2["Innodb_buffer_pool_reads"]) - int( 880 | gl.mystat1["Innodb_buffer_pool_reads"])) / gl.interval 881 | innodb_rows_inserted_diff = (int(mystat2["Innodb_rows_inserted"]) - int( 882 | gl.mystat1["Innodb_rows_inserted"])) / gl.interval 883 | innodb_rows_updated_diff = (int(mystat2["Innodb_rows_updated"]) - int( 884 | gl.mystat1["Innodb_rows_updated"])) / gl.interval 885 | innodb_rows_deleted_diff = (int(mystat2["Innodb_rows_deleted"]) - int( 886 | gl.mystat1["Innodb_rows_deleted"])) / gl.interval 887 | innodb_rows_read_diff = (int(mystat2["Innodb_rows_read"]) - int( 888 | gl.mystat1["Innodb_rows_read"])) / gl.interval 889 | innodb_bp_pages_flushed_diff = (int(mystat2["Innodb_buffer_pool_pages_flushed"]) - int( 890 | gl.mystat1["Innodb_buffer_pool_pages_flushed"])) / gl.interval 891 | innodb_data_reads_diff = (int(mystat2["Innodb_data_reads"]) - int( 892 | gl.mystat1["Innodb_data_reads"])) / gl.interval 893 | innodb_data_writes_diff = (int(mystat2["Innodb_data_writes"]) - int( 894 | gl.mystat1["Innodb_data_writes"])) / gl.interval 895 | innodb_data_read_diff = (int(mystat2["Innodb_data_read"]) - int( 896 | gl.mystat1["Innodb_data_read"])) / gl.interval 897 | innodb_data_written_diff = (int(mystat2["Innodb_data_written"]) - int( 898 | gl.mystat1["Innodb_data_written"])) / gl.interval 899 | innodb_os_log_fsyncs_diff = (int(mystat2["Innodb_os_log_fsyncs"]) - int( 900 | gl.mystat1["Innodb_os_log_fsyncs"])) / gl.interval 901 | innodb_os_log_written_diff = (int(mystat2["Innodb_os_log_written"]) - int( 902 | gl.mystat1["Innodb_os_log_written"])) / gl.interval 903 | threads_created_diff = (int( 904 | mystat2["Threads_created"]) - int(gl.mystat1["Threads_created"])) / gl.interval 905 | bytes_received_diff = ( 906 | int(mystat2["Bytes_received"]) - int(gl.mystat1["Bytes_received"])) / gl.interval 907 | bytes_sent_diff = ( 908 | int(mystat2["Bytes_sent"]) - int(gl.mystat1["Bytes_sent"])) / gl.interval 909 | if gl.com: 910 | # Com_insert # Com_update # Com_delete 911 | cprint("{:>5.0f}{:6.0f}{:>6.0f}".format( 912 | insert_diff, update_diff, delete_diff), 'white', end='') 913 | # Com_select 914 | cprint("{:7.0f}".format(select_diff), 'yellow', end='') 915 | # Total TPS 916 | cprint("{:>6.0f}".format(insert_diff + 917 | update_diff + delete_diff), 'yellow', end='') 918 | cprint('|', 'green', attrs=['bold'], end='') 919 | if gl.innodb_hit: 920 | # Innodb_buffer_pool_read_requests 921 | cprint("{:>7.0f}".format(read_request), 'white', end='') 922 | # Hit% : (Innodb_buffer_pool_read_requests - Innodb_buffer_pool_reads) / Innodb_buffer_pool_read_requests * 100% 923 | if read_request > 0: 924 | hit = (read_request - read) / read_request * 100 925 | if hit > 99: 926 | cprint("{:>8.2f}".format(hit), 'green', end='') 927 | else: 928 | cprint("{:>8.2f}".format(hit), 'red', end='') 929 | else: 930 | cprint("{:>8.2f}".format(100.00), 'green', end='') 931 | cprint('|', 'green', attrs=['bold'], end='') 932 | if gl.innodb_rows: 933 | # Innodb_rows_inserted,Innodb_rows_updated,Innodb_rows_deleted,Innodb_rows_read 934 | cprint("{:>5.0f}{:>6.0f}{:>6.0f}{:>7.0f}".format(innodb_rows_inserted_diff, innodb_rows_updated_diff, 935 | innodb_rows_deleted_diff, innodb_rows_read_diff), 936 | 'white', end='') 937 | cprint('|', 'green', attrs=['bold'], end='') 938 | if gl.innodb_pages: 939 | # Innodb_buffer_pool_pages_data/free/dirty/flushed 940 | cprint("{:>7.0f}{:>7.0f}".format(int(mystat2["Innodb_buffer_pool_pages_data"]), 941 | int(mystat2["Innodb_buffer_pool_pages_free"])), 'white', end='') 942 | cprint("{:>7.0f}{:>6.0f}".format(int(mystat2["Innodb_buffer_pool_pages_dirty"]), 943 | innodb_bp_pages_flushed_diff), 'yellow', end='') 944 | cprint('|', 'green', attrs=['bold'], end='') 945 | if gl.innodb_data: 946 | # Innodb_data_reads/writes/read/written 947 | cprint("{:>6.0f}{:>7.0f}".format(innodb_data_reads_diff, 948 | innodb_data_writes_diff), 'white', end='') 949 | if innodb_data_read_diff / 1024 / 1024 > 1: 950 | if innodb_data_read_diff / 1024 / 1024 > 9: 951 | cprint("{:>6.1f}".format( 952 | innodb_data_read_diff / 1024 / 1024) + 'm', 'red', end='') 953 | else: 954 | cprint("{:>6.1f}".format( 955 | innodb_data_read_diff / 1024 / 1024) + 'm', 'white', end='') 956 | elif innodb_data_read_diff / 1024 > 1: 957 | cprint("{:>6.0f}".format( 958 | innodb_data_read_diff / 1024) + 'k', 'white', end='') 959 | else: 960 | cprint("{:>6.0f}".format( 961 | innodb_data_read_diff), 'white', end='') 962 | if innodb_data_written_diff / 1024 / 1024 > 1: 963 | if innodb_data_written_diff / 1024 / 1024 > 9: 964 | cprint("{:>8.1f}".format( 965 | innodb_data_written_diff / 1024 / 1024) + 'm', 'red', end='') 966 | else: 967 | cprint("{:>8.1f}".format( 968 | innodb_data_written_diff / 1024 / 1024) + 'm', 'white', end='') 969 | elif innodb_data_written_diff / 1024 > 1: 970 | cprint("{:>8.0f}".format( 971 | innodb_data_written_diff / 1024) + 'k', 'white', end='') 972 | else: 973 | cprint("{:>8.0f}".format( 974 | innodb_data_read_diff), 'white', end='') 975 | cprint('|', 'green', attrs=['bold'], end='') 976 | if gl.innodb_log: 977 | # Innodb_os_log_fsyncs/written 978 | cprint("{:>6.0f}".format( 979 | innodb_os_log_fsyncs_diff), 'white', end='') 980 | if innodb_os_log_written_diff / 1024 / 1024 > 1: 981 | cprint("{:>8.1f}".format( 982 | innodb_os_log_written_diff / 1024 / 1024) + 'm', 'red', end='') 983 | elif innodb_os_log_written_diff / 1024 > 1: 984 | cprint("{:>8.0f}".format( 985 | innodb_os_log_written_diff / 1024) + 'k', 'yellow', end='') 986 | else: 987 | cprint("{:>8.0f}".format( 988 | innodb_os_log_written_diff), 'yellow', end='') 989 | cprint('|', 'green', attrs=['bold'], end='') 990 | if gl.innodb_status: 991 | innodb_status = get_innodb_status() 992 | cprint("{:>5.0f}".format( 993 | int(innodb_status['history_list'])), 'white', end='') 994 | if int(innodb_status['unflushed_log']) / 1024 / 1024 > 1: 995 | cprint("{:>6.1f}".format( 996 | int(innodb_status['unflushed_log']) / 1024 / 1024) + 'm', 'yellow', end='') 997 | elif int(innodb_status['unflushed_log']) / 1024 > 1: 998 | cprint("{:>6.1f}".format( 999 | int(innodb_status['unflushed_log']) / 1024) + 'k', 'yellow', end='') 1000 | else: 1001 | cprint("{:>6.1f}".format( 1002 | int(innodb_status['unflushed_log'])) + 'b', 'yellow', end='') 1003 | if int(innodb_status['uncheckpointed_bytes']) / 1024 / 1024 > 1: 1004 | cprint("{:>6.1f}".format(int(innodb_status['uncheckpointed_bytes']) / 1024 / 1024) + 'm', 'yellow', 1005 | end='') 1006 | elif int(innodb_status['uncheckpointed_bytes']) / 1024 > 1: 1007 | cprint("{:>6.1f}".format( 1008 | int(innodb_status['uncheckpointed_bytes']) / 1024) + 'k', 'yellow', end='') 1009 | else: 1010 | cprint("{:>6.1f}".format( 1011 | int(innodb_status['uncheckpointed_bytes'])) + 'b', 'yellow', end='') 1012 | cprint("{:>6.0f}{:>7.0f}{:>5.0f}".format(int(innodb_status['read_views']), 1013 | int(innodb_status['queries_inside']), 1014 | int(innodb_status['queries_queued'])), 'white', end='') 1015 | cprint('|', 'green', attrs=['bold'], end='') 1016 | if gl.threads: 1017 | cprint("{:>4.0f}{:>5.0f}{:>5.0f}{:>5.0f}".format(int(mystat2["Threads_running"]), 1018 | int(mystat2["Threads_connected"]), 1019 | threads_created_diff, int(mystat2["Threads_cached"])), 1020 | 'white', end='') 1021 | cprint('|', 'green', attrs=['bold'], end='') 1022 | if gl.bytes: 1023 | if bytes_received_diff / 1024 / 1024 > 1: 1024 | cprint("{:>6.1f}".format(bytes_received_diff / 1025 | 1024 / 1024) + 'm', 'white', end='') 1026 | elif bytes_received_diff / 1024 > 1: 1027 | cprint("{:6.0f}".format( 1028 | bytes_received_diff / 1024) + 'k', 'white', end='') 1029 | else: 1030 | cprint("{:>6.0f}".format(bytes_received_diff) + 1031 | 'b', 'white', end='') 1032 | if bytes_sent_diff / 1024 / 1024 > 1: 1033 | cprint("{:>6.1f}".format(bytes_sent_diff / 1034 | 1024 / 1024) + 'm', 'white', end='') 1035 | elif bytes_sent_diff / 1024 > 1: 1036 | cprint("{:6.0f}".format( 1037 | bytes_sent_diff / 1024) + 'k', 'white', end='') 1038 | else: 1039 | cprint("{:>6.0f}".format(bytes_sent_diff) + 1040 | 'b', 'white', end='') 1041 | cprint('|', 'green', attrs=['bold'], end='') 1042 | else: 1043 | if gl.com: 1044 | cprint("{:>5d}{:>6d}{:>6d}".format(0, 0, 0), 'white', end='') 1045 | cprint("{:>7d}{:>6d}".format(0, 0), 'yellow', end='') 1046 | cprint('|', 'green', attrs=['bold'], end='') 1047 | if gl.innodb_hit: 1048 | cprint("{:>7d}".format(0), 'white', end='') 1049 | cprint("{:>8.2f}".format(100.00), 'green', end='') 1050 | cprint('|', 'green', attrs=['bold'], end='') 1051 | if gl.innodb_rows: 1052 | cprint("{:>5.0f}{:>6.0f}{:>6.0f}{:7.0f}".format( 1053 | 0, 0, 0, 0), 'white', end='') 1054 | cprint('|', 'green', attrs=['bold'], end='') 1055 | if gl.innodb_pages: 1056 | cprint("{:>7.0f}{:>7.0f}".format(0, 0), 'white', end='') 1057 | cprint("{:>7.0f}{:>6.0f}".format(0, 0), 'yellow', end='') 1058 | cprint('|', 'green', attrs=['bold'], end='') 1059 | if gl.innodb_data: 1060 | cprint("{:>6.0f}{:>7.0f}{:>6.0f}{:>8.0f}".format( 1061 | 0, 0, 0, 0), 'white', end='') 1062 | cprint('|', 'green', attrs=['bold'], end='') 1063 | if gl.innodb_log: 1064 | cprint("{:>6.0f}".format(0), 'white', end='') 1065 | cprint("{:>8.0f}".format(0), 'yellow', end='') 1066 | cprint('|', 'green', attrs=['bold'], end='') 1067 | if gl.innodb_status: 1068 | cprint("{:>5d}".format(0), 'white', end='') 1069 | cprint("{:>6.1f}".format(0) + 'b', 'yellow', end='') 1070 | cprint("{:>6.1f}".format(0) + 'b', 'yellow', end='') 1071 | cprint("{:>6d}{:>7d}{:>5d}".format(0, 0, 0), 'white', end='') 1072 | cprint('|', 'green', attrs=['bold'], end='') 1073 | if gl.threads: 1074 | cprint("{:>4.0f}{:>5.0f}{:>5.0f}{:>5.0f}".format( 1075 | 0, 0, 0, 0), 'white', end='') 1076 | cprint('|', 'green', attrs=['bold'], end='') 1077 | if gl.bytes: 1078 | cprint("{:>7.0f}{:>7.0f}".format(0, 0), 'white', end='') 1079 | cprint('|', 'green', attrs=['bold'], end='') 1080 | # Keep Last Status 1081 | gl.mystat1 = mystat2 1082 | gl.mysql_no_first += 1 1083 | 1084 | 1085 | def get_sysinfo(): 1086 | gl.ncpu = multiprocessing.cpu_count() 1087 | if gl.my_load: 1088 | loadavg = load_stat() 1089 | if operator.gt(float(loadavg['lavg_1']), gl.ncpu): 1090 | cprint("{:5.2f}".format(float(loadavg['lavg_1'])), 'red', end='') 1091 | else: 1092 | cprint("{:5.2f}".format(float(loadavg['lavg_1'])), 'white', end='') 1093 | if operator.gt(float(loadavg['lavg_5']), gl.ncpu): 1094 | cprint("{:6.2f}".format(float(loadavg['lavg_5'])), 'red', end='') 1095 | else: 1096 | cprint("{:6.2f}".format(float(loadavg['lavg_5'])), 'white', end='') 1097 | if operator.gt(float(loadavg['lavg_15']), gl.ncpu): 1098 | cprint("{:6.2f}".format(float(loadavg['lavg_15'])), 'red', end='') 1099 | else: 1100 | cprint("{:6.2f}".format( 1101 | float(loadavg['lavg_15'])), 'white', end='') 1102 | 1103 | cprint('|', 'blue', attrs=['bold'], end='') 1104 | if gl.my_cpu or gl.my_disk is not None: 1105 | cpuinfo = readCpuInfo() 1106 | if gl.my_cpu: 1107 | if operator.gt(cpuinfo['userdiff_t'], 10): 1108 | cprint("{:3d}".format(cpuinfo['userdiff_t']), 'red', end='') 1109 | else: 1110 | cprint("{:3d}".format(cpuinfo['userdiff_t']), 'green', end='') 1111 | if operator.gt(cpuinfo['systemdiff_t'], 10): 1112 | cprint("{:4d}".format(cpuinfo['systemdiff_t']), 'red', end='') 1113 | else: 1114 | cprint("{:4d}".format( 1115 | cpuinfo['systemdiff_t']), 'white', end='') 1116 | cprint("{:4d}".format(cpuinfo['idlediff_t']), 'white', end='') 1117 | if operator.gt(cpuinfo['iowaitdiff_t'], 10): 1118 | cprint("{:4d}".format(cpuinfo['iowaitdiff_t']), 'red', end='') 1119 | else: 1120 | cprint("{:4d}".format( 1121 | cpuinfo['iowaitdiff_t']), 'green', end='') 1122 | cprint('|', 'blue', attrs=['bold'], end='') 1123 | if gl.my_swap: 1124 | swapinfo = get_swap() 1125 | if swapinfo['pswpin'] > 0: 1126 | cprint("{:5d}".format( 1127 | int(swapinfo['pswpin'] / gl.interval)), 'red', end='') 1128 | else: 1129 | cprint("{:5d}".format(0), 'white', end='') 1130 | if swapinfo['pswpout'] > 0: 1131 | cprint("{:5d}".format( 1132 | int(swapinfo['pswpout'] / gl.interval)), 'red', end='') 1133 | else: 1134 | cprint("{:5d}".format(0), 'white', end='') 1135 | cprint('|', 'blue', attrs=['bold'], end='') 1136 | if gl.my_net is not None: 1137 | netinfo = readNetInfo(gl.my_net) 1138 | if netinfo is None: 1139 | cprint('\nERROR! Please set the right net info!\n', 'red') 1140 | sys.exit(0) 1141 | else: 1142 | # netinfo['recv']=1073741824 1143 | # 1048576 1144 | # 1073741824 1145 | # netinfo['send']=1073741824 1146 | # 1048576 1147 | # 1073741824 1148 | if netinfo['recv'] / 1024 / 1024 > 1: 1149 | cprint("{:>7.1f}".format( 1150 | netinfo['recv'] / 1024 / 1024) + 'm', 'red', end='') 1151 | elif netinfo['recv'] / 1024 > 1: 1152 | cprint("{:>7d}".format( 1153 | int(netinfo['recv'] / 1024)) + 'k', 'red', end='') 1154 | else: 1155 | cprint("{:>7d}".format( 1156 | int(netinfo['recv'])) + 'b', 'white', end='') 1157 | if netinfo['send'] / 1024 / 1024 > 1: 1158 | cprint("{:>7.1f}".format( 1159 | (netinfo['send'] / 1024 / 1024)) + 'm', 'red', end='') 1160 | elif netinfo['send'] / 1024 > 1: 1161 | cprint("{:>7d}".format( 1162 | int(netinfo['send'] / 1024)) + 'k', 'red', end='') 1163 | # cprint ('|','blue',end='') 1164 | else: 1165 | cprint("{:>7d}".format( 1166 | int(netinfo['send'])) + 'b', 'white', end='') 1167 | cprint('|', 'blue', attrs=['bold'], end='') 1168 | if gl.my_disk is not None: 1169 | deltams = 1000 * ( 1170 | cpuinfo['userdiff'] + cpuinfo['systemdiff'] + cpuinfo['idlediff'] + cpuinfo['iowaitdiff']) / gl.ncpu / gl.HZ 1171 | ios_diff = readDiskInfo(gl.my_disk, deltams) 1172 | if ios_diff is None: 1173 | cprint('\nERROR! Please set the right disk info!\n', 'red') 1174 | # cprint ('sys_io1:','white',end='') 1175 | # cprint (gl.sys_io1,'red') 1176 | sys.exit(0) 1177 | else: 1178 | # print ios_diff 1179 | cprint("{:>6.1f}{:>7.1f}".format( 1180 | ios_diff['rd_ios_s'], ios_diff['wr_ios_s']), 'white', end='') 1181 | if ios_diff['rkbs'] > 1024: 1182 | cprint("{:>8.1f}".format(ios_diff['rkbs']), 'red', end='') 1183 | else: 1184 | cprint("{:>8.1f}".format(ios_diff['rkbs']), 'white', end='') 1185 | if ios_diff['wkbs'] > 1024: 1186 | cprint("{:>8.1f}".format(ios_diff['wkbs']), 'red', end='') 1187 | else: 1188 | cprint("{:>8.1f}".format(ios_diff['wkbs']), 'white', end='') 1189 | cprint("{:>8.1f}".format(ios_diff['queue']), 'white', end='') 1190 | if ios_diff['wait'] > 5: 1191 | cprint("{:>6.1f}".format(ios_diff['wait']), 'red', end='') 1192 | else: 1193 | cprint("{:>6.1f}".format(ios_diff['wait']), 'green', end='') 1194 | if ios_diff['svc_t'] > 5: 1195 | cprint("{:>6.1f}".format(ios_diff['svc_t']), 'red', end='') 1196 | else: 1197 | cprint("{:>6.1f}".format(ios_diff['svc_t']), 'white', end='') 1198 | if ios_diff['busy'] > 80: 1199 | cprint("{:>8.1f}".format(ios_diff['busy']), 'red', end='') 1200 | else: 1201 | cprint("{:>8.1f}".format(ios_diff['busy']), 'green', end='') 1202 | cprint('|', 'blue', attrs=['bold'], end='') 1203 | 1204 | 1205 | # --------------------------------------------------------------------------- 1206 | # 16. 1207 | # Function: 1208 | # ChangeLog: 1209 | # --------------------------------------------------------------------------- 1210 | def get_dbrt(): 1211 | my_pid = os.getpid() 1212 | tcprstat_lck = 'orzdba_tcprstat.' + str(my_pid) 1213 | gl.lock_file = gl.tcprstat_dir + tcprstat_lck 1214 | try: 1215 | os.open(gl.lock_file, os.O_CREAT | os.O_EXCL | os.O_RDWR) 1216 | except OSError: 1217 | # lock文件已经创建 1218 | s = 'tail -n 1 ' + gl.tcprstat_logfile 1219 | p = subprocess.Popen(s, shell=True, stdout=subprocess.PIPE, bufsize=0) 1220 | out = p.communicate()[0] 1221 | if out: 1222 | (timestamp, count, max, min, avg, med, stddev, max_95, 1223 | avg_95, std_95, max_99, avg_99, std_99) = out.split() 1224 | cprint("{:>7.0f}".format(int(count)), 'green', end='') 1225 | if int(avg) > 10000: 1226 | cprint("{:>7.0f}".format(int(avg)), 'red', end='') 1227 | else: 1228 | cprint("{:>7.0f}".format(int(avg)), 'green', end='') 1229 | if int(avg_95) > 10000: 1230 | cprint("{:>7.0f}".format(int(avg_95)), 'red', end='') 1231 | else: 1232 | cprint("{:>7.0f}".format(int(avg_95)), 'green', end='') 1233 | if int(avg_99) > 10000: 1234 | cprint("{:>7.0f}".format(int(avg_99)), 'red', end='') 1235 | else: 1236 | cprint("{:>7.0f}".format(int(avg_99)), 'green', end='') 1237 | else: 1238 | # cprint('out:'+str(len(out))) 1239 | cprint("{:>7.0f}{:>7.0f}{:>7.0f}{:>7.0f}".format( 1240 | 0, 0, 0, 0), 'green', end='') 1241 | cprint('|', 'green', attrs=['bold'], end='') 1242 | else: 1243 | # 第一次运行 1244 | pid = os.fork() 1245 | if pid == 0: 1246 | chpid = os.getpid() 1247 | # gl.tcprstat_logfile=gl.tcprstat_dir+'orzdba_tcprstat.'+str(chpid)+'.log' 1248 | my_tcprstat = '/usr/bin/tcprstat --no-header -t 1 -n 0 -p ' + \ 1249 | gl.my_port + ' -l ' + get_ip_address() 1250 | my_tcprstat += ' >' + gl.tcprstat_dir + \ 1251 | 'orzdba_tcprstat.' + str(chpid) + '.log' 1252 | # print my_tcprstat 1253 | os.execlp("/bin/sh", "sh", "-c", my_tcprstat) 1254 | sys.exit(0) 1255 | gl.tcprstat_logfile = gl.tcprstat_dir + \ 1256 | 'orzdba_tcprstat.' + str(pid) + '.log' 1257 | cprint("{:>7.0f}{:>7.0f}{:>7.0f}{:>7.0f}".format( 1258 | 0, 0, 0, 0), 'green', end='') 1259 | cprint('|', 'green', attrs=['bold'], end='') 1260 | 1261 | 1262 | # --------------------------------------------------------------------------- 1263 | # 17. 1264 | # Function: 主程序入口 1265 | # ChangeLog: 1266 | # --------------------------------------------------------------------------- 1267 | def main(): 1268 | # variables 1269 | mycount = 0 1270 | signal.signal(signal.SIGINT, catch_zap) 1271 | gl.python_version = sys.version_info 1272 | if gl.python_version < (2, 7): 1273 | sys.exit('error: Python 2.7 or later required') 1274 | # clean screen 1275 | os.system('cls' if os.name == 'nt' else 'clear') 1276 | # cprint (str(gl.python_version)) 1277 | opts = get_options() 1278 | if gl.optflag == 0: 1279 | sys.exit(0) 1280 | gl.mysql_conn = 'mysql -s --skip-column-names -uroot -P' + gl.my_port 1281 | if gl.my_socket is not None: 1282 | gl.mysql_conn += ' -S' + gl.my_socket 1283 | # print gl.mysql_conn 1284 | if gl.my_pwd is not None: 1285 | shell_command = "env" 1286 | os.putenv("MYSQL_PWD", gl.my_pwd) 1287 | # subprocess.call(shell_command, shell=True) 1288 | get_mysql_version() 1289 | if gl.orz_logfile is not None: 1290 | gl.HAS_COLOR = 1 1291 | cprint('--------write log begin--------------------------', 'green', end='') 1292 | cprint('') 1293 | gl.old_console = sys.stdout 1294 | if gl.logfile_by_day: 1295 | # logfile=gl.orz_logfile+'.'+time.strftime('%Y%m%d%H%M',time.localtime(time.time())) 1296 | logfile = gl.orz_logfile + '.' + \ 1297 | time.strftime('%Y%m%d', time.localtime(time.time())) 1298 | else: 1299 | logfile = gl.orz_logfile 1300 | cprint('logfile:' + logfile, 'green', end='') 1301 | cprint('') 1302 | gl.HAS_COLOR = 0 1303 | sys.stdout = open(logfile, 'w+') 1304 | Print_title() 1305 | 1306 | while (1): 1307 | # -C:Times to exists 1308 | if (gl.count is not None and mycount + 1 > gl.count): 1309 | break 1310 | if (gl.orz_logfile is not None and gl.logfile_by_day): 1311 | newlogfile = gl.orz_logfile + '.' + \ 1312 | time.strftime('%Y%m%d', time.localtime(time.time())) 1313 | if os.path.exists(newlogfile) == False: 1314 | logfile = newlogfile 1315 | cprint(logfile) 1316 | sys.stdout.close 1317 | sys.stdout = open(logfile, 'w+') 1318 | Print_title() 1319 | if gl.count is not None: 1320 | gl.count = gl.count - mycount 1321 | mycount = 0 1322 | # Print Headline 1323 | if (mycount % 15 == 0): 1324 | if gl.mysql: 1325 | cprint(gl.headline1, end='') 1326 | cprint(gl.mysql_headline1) 1327 | cprint(gl.headline2, end='') 1328 | cprint(gl.mysql_headline2) 1329 | else: 1330 | cprint(gl.headline1) 1331 | cprint(gl.headline2) 1332 | mycount += 1 1333 | # (1) Print Current Time 1334 | if (gl.timeFlag == 1): 1335 | cprint( 1336 | colored(time.strftime("%H:%M:%S", time.localtime()), 1337 | 'yellow') + colored('|', 'blue', attrs=['bold']), 1338 | end='') 1339 | # (2) Print SysInfo 1340 | get_sysinfo() 1341 | # (3) Print MySQL Status 1342 | get_mysqlstat() 1343 | # (4) TCPRSTAT 1344 | if gl.dbrt: 1345 | get_dbrt() 1346 | cprint('') 1347 | # sleep interval 1348 | time.sleep(gl.interval) 1349 | 1350 | 1351 | if __name__ == '__main__': 1352 | main() 1353 | --------------------------------------------------------------------------------