-
Notifications
You must be signed in to change notification settings - Fork 26
/
query_progress.py
executable file
·269 lines (235 loc) · 7.7 KB
/
query_progress.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#!/usr/bin/env python3
"""
This script shows the actual state and progress of the running query.
Usage:
query_progress.py [--host XXX] [--port NNN] [--dbname XXX] [--username XXX] [--password] [--verbose] [--pid NNN]
query_progress.py [--basedir XXX] [--verbose] [--pid NNN] --serverid XXX
Formatted by black (https://pypi.org/project/black/)
Copyright (c) 2021-2024, Hironobu Suzuki @ interdb.jp
"""
import psycopg2
import argparse
import getpass
import sys
import os
import hashlib
import re
import math
from pgpi import Database, Repository, QueryProgress, Log
if __name__ == "__main__":
def usage():
_msg = "Usage:\n"
_msg += "\tquit\t\t: Quit this program\n"
_msg += "\tv, verbose\t: Switch Verbose mode <--> Normal mode\n"
_msg += "\th, help\t\t: Show help message\n"
print(_msg)
def clear_console():
if os.name == "nt":
os.system("cls")
else:
os.system("clear")
LOG_LEVEL = Log.info
explain_stmt = re.compile(r"^explain")
# Parse arguments.
parser = argparse.ArgumentParser(
description="This script shows the actual state and progress of the running query.",
add_help=False,
)
parser.add_argument(
"--host",
"-h",
help='Database server host or socker directory (default: "localhost")',
default="localhost",
)
parser.add_argument(
"--port", "-p", help='Database server port (default: "5432")', default="5432"
)
parser.add_argument(
"--dbname", help='Database (default: "postgres")', default="postgres"
)
parser.add_argument(
"--username",
"-U",
help='Database user name (default: "postgres")',
default="postgres",
)
parser.add_argument("--password", "-W", action="store_true", help="input password")
parser.add_argument(
"--serverid",
help="Identifier of the database server you connect, which is described in hosts.conf",
default=None,
)
parser.add_argument(
"--basedir",
help="Directory of the repository you use (default: '.')",
default=".",
)
parser.add_argument(
"--pid",
help="Pid of the Postgres process that you want to show the query progress",
default="0",
)
parser.add_argument("--verbose", action="store_true", help="Show all")
parser._add_action(
argparse._HelpAction(
option_strings=["--help", "-H"], help="Show this help message and exit"
)
)
args = parser.parse_args()
"""
Make connection parameter.
"""
base_dir = str(args.basedir)
if args.serverid is not None:
server_id = str(args.serverid)
db = Database(base_dir, LOG_LEVEL)
conn = db.get_connection_param(str(args.serverid))
del db
else:
server_id = None
conn = (
"host="
+ str(args.host)
+ " port="
+ str(args.port)
+ " dbname="
+ str(args.dbname)
+ " user="
+ str(args.username)
)
if args.password == True:
_password = getpass.getpass()
conn += " password=" + _password
"""
Connect to database server.
"""
try:
connection = psycopg2.connect(conn)
except psycopg2.OperationalError as e:
print("Could not connect to {}".format(args.host))
sys.exit(1)
connection.autocommit = True
clear_console()
"""
Welcome message.
"""
print("Connected to {}".format(args.host))
print('\n\tEnter "quit" or Contrl-C to quit this script')
print('\tEnter "help" to show usage.\n')
pid = args.pid
previous_pid = pid
verbose = args.verbose
qp = QueryProgress(base_dir, LOG_LEVEL)
"""
Main loop.
"""
while True:
# Wait for input.
msg = "Enter pid (default: " + str(pid) + ') or "quit":'
try:
pid = input(msg)
except KeyboardInterrupt:
connection.close()
print("\n")
sys.exit(1)
if pid == "quit":
break
elif pid == "":
pid = previous_pid
elif str.lower(pid) == "h" or str.lower(pid) == "help":
usage()
pid = previous_pid
continue
elif str.lower(pid) == "v" or str.lower(pid) == "verbose":
verbose ^= True
print(
"Switch to {} mode".format(
(lambda v: "Verbose" if verbose else "Normal")(verbose)
)
)
pid = previous_pid
continue
elif pid.isdigit() == False:
pid = previous_pid
continue
clear_console()
# Execute pg_query_plan().
sql = "SELECT pid, database, worker_type, nested_level, queryid, query, planid, plan, plan_json"
sql += " FROM pg_query_plan(" + pid + ")"
cur = connection.cursor()
try:
cur.execute(sql)
except Exception as err:
cur.close()
print("Error! Check the pid:{} you set.".format(pid))
continue
if cur.rowcount == 0:
cur.close()
print("retuned 0 row")
previous_pid = pid
continue
# Prepare data to calcurate the progress of the queries.
_X = []
for row in cur:
_worker_type = row[2]
_queryid = int(row[4])
_query = row[5]
_planid = int(row[6])
_plan_json = row[8]
if Log.debug1 <= LOG_LEVEL:
print("Debug1: queryid={} planid={}".format(_queryid, _planid))
_X.append(
[
_worker_type,
_queryid,
_planid,
_plan_json,
int(
hashlib.md5(str(_query).encode()).hexdigest(), 16
), # For version 13.
]
)
# Show the progress of the queries if the queries are NOT EXPLAIN.
if re.match(explain_stmt, str.lower(_query)) is None:
_ret = qp.query_progress(_X, server_id)
print("==> Query Progress:")
for _p in _ret:
print("\tqueryid = {}".format(str(_p[0])))
_percent = _p[1] * 100
_percent = math.floor(_percent * 10 ** 2) / (10 ** 2)
_pb = qp.make_progress_bar(_percent)
print("\t{:>8.2f}[%] {}".format(float(_percent), str(_pb)))
else:
print("Notice: EXPLAIN ANALYZE statement is out of scope.")
# Display query info.
cur.scroll(0, mode="absolute")
i = 1
for row in cur:
_pid = row[0]
_database = row[1]
_worker_type = row[2]
_nested_level = row[3]
_queryid = int(row[4])
_query = row[5]
_planid = int(row[6])
_plan = row[7]
_plan_json = row[8]
print("[{}]----------------------------------------------------".format(i))
print("pid :{}".format(_pid))
if verbose:
print("database :{}".format(_database))
print("worker_type :{}".format(_worker_type))
print("nested_level :{}".format(_nested_level))
print("queryid :{}".format(_queryid))
print("query :\n {}".format(_query))
if verbose:
print("planid :{}".format(_planid))
print("query_plan :\n{}".format(_plan))
i += 1
cur.close()
previous_pid = pid
"""
Finish processing.
"""
connection.close()
del qp