File: test_admin.py

package info (click to toggle)
pgbouncer 1.25.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,884 kB
  • sloc: ansic: 61,425; python: 5,703; sh: 4,527; makefile: 1,361; sed: 22
file content (434 lines) | stat: -rw-r--r-- 12,680 bytes parent folder | download
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import threading
import time

import psycopg
import pytest
from psycopg.rows import dict_row

from .utils import Bouncer, capture, run


def test_reload_error(bouncer):
    """
    Test that admin console correctly raises error during RELOAD
    when invalid value set for auth_type.
    """
    config = f"""
    [databases]
    p1 = host={bouncer.pg.host} port={bouncer.pg.port}

    [pgbouncer]
    listen_addr = {bouncer.host}
    listen_port = {bouncer.port}
    auth_type = trust
    admin_users = pgbouncer
    logfile = {bouncer.log_path}
    auth_file = {bouncer.auth_path}
    pool_mode = session
    server_lifetime = {{server_lifetime}}
    """
    good_config = config.format(server_lifetime=0)
    bad_config = config.format(server_lifetime="invalid_server_lifetime")
    with bouncer.run_with_config(good_config):
        with bouncer.ini_path.open("w") as f:
            f.write(bad_config)

        with pytest.raises(
            psycopg.errors.ConfigFileError,
            match=r"RELOAD failed, see logs for additional details",
        ):
            bouncer.admin("RELOAD")


def test_show(bouncer):
    show_items = [
        "clients",
        "config",
        "databases",
        # Calling SHOW FDS on MacOS leaks the returned file descriptors to the
        # python test runner. So we don't test this one directly. SHOW FDS is
        # still tested indirectly by the takeover tests.
        # "fds",
        "help",
        "lists",
        "peers",
        "peer_pools",
        "pools",
        "servers",
        "sockets",
        "active_sockets",
        "state",
        "stats",
        "stats_totals",
        "stats_averages",
        "users",
        "totals",
        "mem",
        "dns_hosts",
        "dns_zones",
    ]

    for item in show_items:
        bouncer.admin(f"SHOW {item}")


def test_socket_id(bouncer) -> None:
    """Test that PgSocket id is assigned as expected for sockets."""
    config = f"""
    [databases]
    p1 = host={bouncer.pg.host} port={bouncer.pg.port}

    [pgbouncer]
    listen_addr = {bouncer.host}
    listen_port = {bouncer.port}
    auth_type = trust
    admin_users = pgbouncer
    logfile = {bouncer.log_path}
    auth_file = {bouncer.auth_path}
    pool_mode = session
    server_lifetime = 0
    """

    with bouncer.run_with_config(config):
        with bouncer.cur(
            dbname="pgbouncer", user="pgbouncer", row_factory=dict_row
        ) as admin_cursor:
            admin_cursor.execute("SHOW SOCKETS")
            servers = admin_cursor.fetchall()
            initial_id = max([i["id"] for i in servers])

            for i in range(1, 4):
                conn_2 = bouncer.conn(dbname="p1")
                curr = conn_2.cursor()
                _ = curr.execute("SELECT 1")
                time.sleep(2)
                clients = admin_cursor.execute("SHOW SOCKETS").fetchall()
                assert len(clients) == 3
                assert set(
                    [
                        initial_id,
                        initial_id + i * 2 - 1,
                        initial_id + i * 2,
                    ]
                ) == set([client["id"] for client in clients])
                conn_2.close()
                time.sleep(2)


def test_server_id(bouncer) -> None:
    """Test that PgSocket id is assigned as expected for servers."""
    config = f"""
    [databases]
    p1 = host={bouncer.pg.host} port={bouncer.pg.port}

    [pgbouncer]
    listen_addr = {bouncer.host}
    listen_port = {bouncer.port}
    auth_type = trust
    admin_users = pgbouncer
    logfile = {bouncer.log_path}
    auth_file = {bouncer.auth_path}
    server_lifetime = 0
    """

    with bouncer.run_with_config(config):
        with bouncer.cur(
            dbname="pgbouncer", user="pgbouncer", row_factory=dict_row
        ) as admin_cursor:
            admin_cursor.execute("SHOW SOCKETS")
            servers = admin_cursor.fetchall()
            initial_id = max([i["id"] for i in servers])

            for i in range(1, 4):
                conn_2 = bouncer.conn(dbname="p1")
                curr = conn_2.cursor()
                _ = curr.execute("SELECT 1")
                time.sleep(2)
                clients = admin_cursor.execute("SHOW SERVERS").fetchall()
                assert [
                    initial_id + i * 2,
                ] == [client["id"] for client in clients]
                conn_2.close()
                time.sleep(2)


def test_client_id(bouncer) -> None:
    """Test that PgSocket id is assigned as expected for clients."""
    config = f"""
    [databases]
    p1 = host={bouncer.pg.host} port={bouncer.pg.port}

    [pgbouncer]
    listen_addr = {bouncer.host}
    listen_port = {bouncer.port}
    auth_type = trust
    admin_users = pgbouncer
    logfile = {bouncer.log_path}
    auth_file = {bouncer.auth_path}
    server_lifetime = 0
    """

    with bouncer.run_with_config(config):
        initial_id = bouncer.admin("SHOW CLIENTS", row_factory=dict_row)[0]["id"]

        for i in range(1, 4):
            clients = bouncer.admin("SHOW CLIENTS", row_factory=dict_row)
            assert [
                initial_id + i,
            ] == [client["id"] for client in clients]


def test_client_states(bouncer):
    conn_1 = bouncer.conn(dbname="p3x", user="clientstate")

    clients = bouncer.admin("SHOW CLIENTS", row_factory=dict_row)
    client_id = [
        client
        for client in clients
        if client["database"] == "p3x" and client["user"] == "clientstate"
    ][0]["state"]
    assert client_id == "idle"

    cur_1 = conn_1.cursor()

    bouncer.admin("PAUSE p3x")

    # Give a moment for the query to hit the pause
    time.sleep(1)

    # We'll run a query in a separate thread to simulate blocking/waiting
    def run_blocked_query():
        # This query will attempt to run but the DB is paused
        cur_1.execute("SELECT pg_sleep(5)")
        # If the DB is never resumed, this call will block until test times out
        # Once the DB is resumed, it should succeed
        cur_1.fetchone()

    thread = threading.Thread(target=run_blocked_query)
    thread.start()

    # Give the thread a moment to attempt the query
    time.sleep(1)

    clients = bouncer.admin("SHOW CLIENTS", row_factory=dict_row)
    client_id = [
        client
        for client in clients
        if client["database"] == "p3x" and client["user"] == "clientstate"
    ][0]["state"]
    assert client_id == "waiting"

    bouncer.admin("RESUME p3x")

    # Wait for the thread to finish the blocked query
    thread.join(timeout=10)
    # Confirm the query eventually completes
    assert not thread.is_alive(), "Expected the blocked query thread to finish"

    cur_1.execute("BEGIN; SELECT pg_sleep(5);")

    clients = bouncer.admin("SHOW CLIENTS", row_factory=dict_row)
    client_id = [
        client
        for client in clients
        if client["database"] == "p3x" and client["user"] == "clientstate"
    ][0]["state"]
    assert client_id == "active"

    # Rollback/commit to end the long-running transaction
    cur_1.execute("ROLLBACK")

    # Cleanup
    cur_1.close()
    conn_1.close()


def test_kill_db(bouncer: "Bouncer"):
    # Connect to client as user A
    conn_1 = bouncer.conn(dbname="p0", user="maxedout")

    # Connect to client as user B
    conn_2 = bouncer.conn(dbname="p0", user="maxedout")

    # Validate count
    clients = bouncer.admin("SHOW CLIENTS", row_factory=dict_row)
    assert len(clients) == 3

    # Issue kill command
    bouncer.admin("KILL p0")

    # Validate count
    clients = bouncer.admin("SHOW CLIENTS")
    assert len(clients) == 1

    conn_1.close()
    conn_2.close()


def test_kill_db_nonexisting(bouncer: "Bouncer"):
    # Connect to client as user A
    conn_1 = bouncer.conn(dbname="p0", user="maxedout")

    # Validate count
    clients = bouncer.admin("SHOW CLIENTS", row_factory=dict_row)
    assert len(clients) == 2

    # Issue kill command
    with pytest.raises(
        psycopg.errors.ProtocolViolation,
        match=r"no such database: dne",
    ):
        clients = bouncer.admin("KILL dne")

    # Validate count
    clients = bouncer.admin("SHOW CLIENTS")
    assert len(clients) == 2

    conn_1.close()


def test_kill_all(bouncer: "Bouncer"):
    # Connect to client as user A to first database
    conn_1 = bouncer.conn(dbname="p0", user="maxedout")

    # Connect to client as user B to second database
    conn_2 = bouncer.conn(dbname="p1", user="maxedout")

    # Validate count
    clients = bouncer.admin("SHOW CLIENTS", row_factory=dict_row)
    assert len(clients) == 3

    # Issue kill command
    bouncer.admin("KILL")

    # Validate count
    clients = bouncer.admin("SHOW CLIENTS")
    assert len(clients) == 1

    conn_1.close()
    conn_2.close()


def test_kill_client_nonexisting(bouncer):
    # Connect to client as user A
    conn_1 = bouncer.conn(dbname="p0", user="maxedout")

    # Validate count
    clients = bouncer.admin("SHOW CLIENTS", row_factory=dict_row)
    assert len(clients) == 2

    # Issue kill client command
    with pytest.raises(
        psycopg.errors.ProtocolViolation,
        match=r"client not found",
    ):
        clients = bouncer.admin(f"KILL_CLIENT 1000")

    # Validate count
    clients = bouncer.admin("SHOW CLIENTS")
    assert len(clients) == 2

    conn_1.close()


def test_kill_client_invalid(bouncer):
    # Connect to client as user A
    conn_1 = bouncer.conn(dbname="p0", user="maxedout")

    # Validate count
    clients = bouncer.admin("SHOW CLIENTS")
    assert len(clients) == 2

    # Issue kill client command
    with pytest.raises(
        psycopg.errors.ProtocolViolation,
        match=r"invalid client pointer supplied",
    ):
        clients = bouncer.admin("KILL_CLIENT non_existant_client_id")

    # Validate count
    clients = bouncer.admin("SHOW CLIENTS")
    assert len(clients) == 2

    conn_1.close()


def test_kill_client(bouncer):
    # Connect to client as user A
    conn_1 = bouncer.conn(dbname="p0", user="maxedout")

    # Validate count
    clients = bouncer.admin("SHOW CLIENTS", row_factory=dict_row)
    assert len(clients) == 2

    # Get clients id
    client_id = [client for client in clients if client["database"] == "p0"][0]["id"]

    # Issue kill client command
    clients = bouncer.admin(f"KILL_CLIENT {client_id}")

    # Validate count
    clients = bouncer.admin("SHOW CLIENTS")
    assert len(clients) == 1

    conn_1.close()


def test_show_version(bouncer):
    admin_version = bouncer.admin_value(f"SHOW VERSION")
    subprocess_result = capture(
        [*bouncer.base_command(), "--version"],
    )
    subprocess_version = subprocess_result.split("\n")[0]
    assert admin_version == subprocess_version


def test_help(bouncer):
    run([*bouncer.base_command(), "--help"])


def test_show_stats(bouncer):
    # Use session pooling database to see differenecs between transactions and
    # server assignments
    bouncer.default_db = "p3"
    bouncer.test()
    bouncer.test()
    bouncer.test()
    bouncer.test()
    with bouncer.cur() as cur:
        with cur.connection.transaction():
            cur.execute("SELECT 1")
            cur.execute("SELECT 1")
            cur.execute("SELECT 1")
        with cur.connection.transaction():
            cur.execute("SELECT 1")
            cur.execute("SELECT 1")
            cur.execute("SELECT 1")

    stats = bouncer.admin("SHOW STATS", row_factory=dict_row)
    p3_stats = next(s for s in stats if s["database"] == "p3")
    assert p3_stats is not None
    # 5 connection attempts (and thus assignments)
    assert p3_stats["total_server_assignment_count"] == 5
    # 4 autocommit queries + 2 transactions
    assert p3_stats["total_xact_count"] == 6
    # 11 SELECT 1 + 2 times COMMIT and ROLLBACK
    assert p3_stats["total_query_count"] == 15

    stats = bouncer.admin("SHOW STATS_TOTALS", row_factory=dict_row)
    p3_stats = next(s for s in stats if s["database"] == "p3")
    assert p3_stats is not None
    # 5 connection attempts (and thus assignments)
    assert p3_stats["server_assignment_count"] == 5
    # 4 autocommit queries + 2 transactions
    assert p3_stats["xact_count"] == 6
    # 11 SELECT 1 + 2 times COMMIT and ROLLBACK
    assert p3_stats["query_count"] == 15

    totals = bouncer.admin("SHOW TOTALS")
    # 5 connection attempts (and thus assignments)
    assert ("total_server_assignment_count", 5) in totals
    # 4 autocommit queries + 2 transactions + 4 admin commands
    assert ("total_xact_count", 10) in totals
    # 11 SELECT 1 + 2 times COMMIT and ROLLBACK + 4 admin commands
    assert ("total_query_count", 19) in totals