forked from MaterializeInc/materialize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmzcompose.py
576 lines (494 loc) · 19.9 KB
/
mzcompose.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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# Copyright Materialize, Inc. and contributors. All rights reserved.
#
# Use of this software is governed by the Business Source License
# included in the LICENSE file at the root of this repository.
#
# As of the Change Date specified in that file, in accordance with
# the Business Source License, use of this software will be governed
# by the Apache License, Version 2.0.
import random
from collections.abc import Callable
from dataclasses import dataclass
from textwrap import dedent
from typing import Protocol
from materialize.checks.common import KAFKA_SCHEMA_WITH_SINGLE_STRING_FIELD
from materialize.mzcompose.composition import Composition
from materialize.mzcompose.services.clusterd import Clusterd
from materialize.mzcompose.services.kafka import Kafka
from materialize.mzcompose.services.materialized import Materialized
from materialize.mzcompose.services.postgres import Postgres
from materialize.mzcompose.services.redpanda import Redpanda
from materialize.mzcompose.services.schema_registry import SchemaRegistry
from materialize.mzcompose.services.testdrive import Testdrive
from materialize.mzcompose.services.zookeeper import Zookeeper
def schema() -> str:
return dedent(KAFKA_SCHEMA_WITH_SINGLE_STRING_FIELD)
SERVICES = [
Redpanda(),
Materialized(),
Testdrive(),
Clusterd(),
Postgres(),
Zookeeper(),
Kafka(),
SchemaRegistry(),
]
class Disruption(Protocol):
def run_test(self, c: Composition) -> None:
...
@dataclass
class KafkaTransactionLogGreaterThan1:
name: str
# override the `run_test`, as we need `Kafka` (not `Redpanda`), and need to change some other things
def run_test(self, c: Composition) -> None:
print(f"+++ Running disruption scenario {self.name}")
seed = random.randint(0, 256**4)
c.up("testdrive", persistent=True)
with c.override(
Kafka(
name="badkafka",
environment=[
"KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181",
# Setting the following values to 3 to trigger a failure
# sets the transaction.state.log.min.isr config
"KAFKA_TRANSACTION_STATE_LOG_MIN_ISR=3",
# sets the transaction.state.log.replication.factor config
"KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR=3",
],
),
SchemaRegistry(kafka_servers=[("badkafka", "9092")]),
Testdrive(
no_reset=True,
seed=seed,
entrypoint_extra=[
"--initial-backoff=1s",
"--backoff-factor=0",
"--kafka-addr=badkafka",
],
),
):
c.up("zookeeper", "badkafka", "schema-registry", "materialized")
self.populate(c)
self.assert_error(
c, "retriable transaction error", "running a single Kafka broker"
)
c.down(sanity_restart_mz=False)
def populate(self, c: Composition) -> None:
# Create a source and a sink
c.testdrive(
dedent(
"""
> CREATE CONNECTION kafka_conn
TO KAFKA (BROKER '${testdrive.kafka-addr}');
> CREATE CONNECTION IF NOT EXISTS csr_conn TO CONFLUENT SCHEMA REGISTRY (
URL '${testdrive.schema-registry-url}'
);
> CREATE TABLE sink_table (f1 INTEGER);
> INSERT INTO sink_table VALUES (1);
> INSERT INTO sink_table VALUES (2);
> CREATE SINK kafka_sink FROM sink_table
INTO KAFKA CONNECTION kafka_conn (TOPIC 'testdrive-kafka-sink-${testdrive.seed}')
FORMAT AVRO USING CONFLUENT SCHEMA REGISTRY CONNECTION csr_conn
ENVELOPE DEBEZIUM
$ kafka-verify-topic sink=materialize.public.kafka_sink
"""
),
)
def assert_error(self, c: Composition, error: str, hint: str) -> None:
c.testdrive(
dedent(
f"""
> SELECT bool_or(error ~* '{error}'), bool_or(details::json#>>'{{hints,0}}' ~* '{hint}')
FROM mz_internal.mz_sink_status_history
JOIN mz_sinks ON mz_sinks.id = sink_id
WHERE name = 'kafka_sink' and status = 'stalled'
true true
"""
)
)
@dataclass
class KafkaDisruption:
name: str
breakage: Callable
expected_error: str
fixage: Callable | None
def run_test(self, c: Composition) -> None:
print(f"+++ Running disruption scenario {self.name}")
seed = random.randint(0, 256**4)
c.down(destroy_volumes=True, sanity_restart_mz=False)
c.up("testdrive", persistent=True)
c.up("redpanda", "materialized", "clusterd")
with c.override(
Testdrive(
no_reset=True,
seed=seed,
entrypoint_extra=["--initial-backoff=1s", "--backoff-factor=0"],
)
):
self.populate(c)
self.breakage(c, seed)
self.assert_error(c, self.expected_error)
if self.fixage:
self.fixage(c, seed)
self.assert_recovery(c)
def populate(self, c: Composition) -> None:
# Create a source and a sink
c.testdrive(
dedent(
"""
# We specify the progress topic explicitly so we can delete it in a test later,
# and confirm that the sink stalls. (Deleting the output topic is not enough if
# we're not actively publishing new messages to the sink.)
> CREATE CONNECTION kafka_conn
TO KAFKA (
BROKER '${testdrive.kafka-addr}',
PROGRESS TOPIC 'testdrive-progress-topic-${testdrive.seed}'
);
> CREATE CONNECTION IF NOT EXISTS csr_conn TO CONFLUENT SCHEMA REGISTRY (
URL '${testdrive.schema-registry-url}'
);
$ kafka-create-topic topic=source-topic
$ kafka-ingest topic=source-topic format=bytes
ABC
> CREATE SOURCE source1
FROM KAFKA CONNECTION kafka_conn (TOPIC 'testdrive-source-topic-${testdrive.seed}')
FORMAT BYTES
ENVELOPE NONE
# WITH ( REMOTE 'clusterd:2100' ) https://github.com/MaterializeInc/materialize/issues/16582
# Ensure the source makes _real_ progress before we disrupt it. This also
# ensures the sink makes progress, which is required to hit certain stalls.
# As of implementing correctness property #2, this is required.
> SELECT count(*) from source1
1
> CREATE SINK sink1 FROM source1
INTO KAFKA CONNECTION kafka_conn (TOPIC 'testdrive-sink-topic-${testdrive.seed}')
FORMAT AVRO USING CONFLUENT SCHEMA REGISTRY CONNECTION csr_conn
ENVELOPE DEBEZIUM
# WITH ( REMOTE 'clusterd:2100' ) https://github.com/MaterializeInc/materialize/issues/16582
$ kafka-verify-topic sink=materialize.public.sink1
"""
)
)
def assert_error(self, c: Composition, error: str) -> None:
c.testdrive(
dedent(
f"""
> SELECT status, error ~* '{error}'
FROM mz_internal.mz_source_statuses
WHERE name = 'source1'
stalled true
"""
)
)
def assert_recovery(self, c: Composition) -> None:
c.testdrive(
dedent(
"""
$ kafka-ingest topic=source-topic format=bytes
ABC
> SELECT COUNT(*) FROM source1;
2
> SELECT status, error
FROM mz_internal.mz_source_statuses
WHERE name = 'source1'
running <null>
"""
)
)
@dataclass
class KafkaSinkDisruption:
name: str
breakage: Callable
expected_error: str
fixage: Callable | None
def run_test(self, c: Composition) -> None:
print(f"+++ Running Kafka sink disruption scenario {self.name}")
seed = random.randint(0, 256**4)
c.down(destroy_volumes=True, sanity_restart_mz=False)
c.up("testdrive", persistent=True)
c.up("redpanda", "materialized", "clusterd")
with c.override(
Testdrive(
no_reset=True,
seed=seed,
entrypoint_extra=["--initial-backoff=1s", "--backoff-factor=0"],
)
):
self.populate(c)
self.breakage(c, seed)
self.assert_error(c, self.expected_error)
if self.fixage:
self.fixage(c, seed)
self.assert_recovery(c)
def populate(self, c: Composition) -> None:
# Create a source and a sink
c.testdrive(
schema()
+ dedent(
"""
# We specify the progress topic explicitly so we can delete it in a test later,
# and confirm that the sink stalls. (Deleting the output topic is not enough if
# we're not actively publishing new messages to the sink.)
> CREATE CONNECTION kafka_conn
TO KAFKA (
BROKER '${testdrive.kafka-addr}',
PROGRESS TOPIC 'testdrive-progress-topic-${testdrive.seed}'
);
> CREATE CONNECTION IF NOT EXISTS csr_conn TO CONFLUENT SCHEMA REGISTRY (
URL '${testdrive.schema-registry-url}'
);
$ kafka-create-topic topic=source-topic
$ kafka-ingest topic=source-topic format=avro schema=${schema}
{"f1": "A"}
> CREATE SOURCE source1
FROM KAFKA CONNECTION kafka_conn (TOPIC 'testdrive-source-topic-${testdrive.seed}')
FORMAT AVRO USING CONFLUENT SCHEMA REGISTRY CONNECTION csr_conn
ENVELOPE NONE
# WITH ( REMOTE 'clusterd:2100' ) https://github.com/MaterializeInc/materialize/issues/16582
> CREATE SINK sink1 FROM source1
INTO KAFKA CONNECTION kafka_conn (TOPIC 'testdrive-sink-topic-${testdrive.seed}')
FORMAT AVRO USING CONFLUENT SCHEMA REGISTRY CONNECTION csr_conn
ENVELOPE DEBEZIUM
# WITH ( REMOTE 'clusterd:2100' ) https://github.com/MaterializeInc/materialize/issues/16582
$ kafka-verify-data format=avro sink=materialize.public.sink1 sort-messages=true
{"before": null, "after": {"row":{"f1": "A"}}}
"""
)
)
def assert_error(self, c: Composition, error: str) -> None:
c.testdrive(
dedent(
f"""
# Sinks generally halt after receiving an error, which means that they may alternate
# between `stalled` and `starting`. Instead of relying on the current status, we
# check that there is a stalled status with the expected error.
> SELECT bool_or(error ~* '{error}'), bool_or(details->'namespaced'->>'kafka' ~* '{error}')
FROM mz_internal.mz_sink_status_history
JOIN mz_sinks ON mz_sinks.id = sink_id
WHERE name = 'sink1' and status = 'stalled'
true true
"""
)
)
def assert_recovery(self, c: Composition) -> None:
c.testdrive(
dedent(
"""
> SELECT status, error
FROM mz_internal.mz_sink_statuses
WHERE name = 'sink1'
running <null>
"""
)
)
@dataclass
class PgDisruption:
name: str
breakage: Callable
expected_error: str
fixage: Callable | None
def run_test(self, c: Composition) -> None:
print(f"+++ Running disruption scenario {self.name}")
seed = random.randint(0, 256**4)
c.down(destroy_volumes=True, sanity_restart_mz=False)
c.up("testdrive", persistent=True)
c.up("postgres", "materialized", "clusterd")
with c.override(
Testdrive(
no_reset=True,
seed=seed,
entrypoint_extra=["--initial-backoff=1s", "--backoff-factor=0"],
)
):
self.populate(c)
self.breakage(c, seed)
self.assert_error(c, self.expected_error)
if self.fixage:
self.fixage(c, seed)
self.assert_recovery(c)
def populate(self, c: Composition) -> None:
# Create a source and a sink
c.testdrive(
dedent(
"""
> CREATE SECRET pgpass AS 'postgres'
> CREATE CONNECTION pg TO POSTGRES (
HOST postgres,
DATABASE postgres,
USER postgres,
PASSWORD SECRET pgpass
)
$ postgres-execute connection=postgres://postgres:postgres@postgres
ALTER USER postgres WITH replication;
DROP SCHEMA IF EXISTS public CASCADE;
CREATE SCHEMA public;
DROP PUBLICATION IF EXISTS mz_source;
CREATE PUBLICATION mz_source FOR ALL TABLES;
CREATE TABLE source1 (f1 INTEGER PRIMARY KEY, f2 integer[]);
INSERT INTO source1 VALUES (1, NULL);
ALTER TABLE source1 REPLICA IDENTITY FULL;
INSERT INTO source1 VALUES (2, NULL);
> CREATE SOURCE "pg_source"
FROM POSTGRES CONNECTION pg (PUBLICATION 'mz_source')
FOR TABLES ("source1");
"""
)
)
def assert_error(self, c: Composition, error: str) -> None:
c.testdrive(
dedent(
f"""
# Postgres sources may halt after receiving an error, which means that they may alternate
# between `stalled` and `starting`. Instead of relying on the current status, we
# check that the latest stall has the error we expect.
> SELECT status, error ~* '{error}'
FROM mz_internal.mz_source_status_history
JOIN mz_sources ON mz_sources.id = source_id
WHERE name = 'source1' and status = 'stalled'
ORDER BY occurred_at DESC LIMIT 1
stalled true
"""
)
)
def assert_recovery(self, c: Composition) -> None:
c.testdrive(
dedent(
"""
$ postgres-execute connection=postgres://postgres:postgres@postgres
INSERT INTO source1 VALUES (3);
> SELECT status, error
FROM mz_internal.mz_source_statuses
WHERE name = 'source1'
running <null>
> SELECT f1 FROM source1;
1
2
3
"""
)
)
disruptions: list[Disruption] = [
KafkaSinkDisruption(
name="delete-sink-topic-delete-progress-fix",
breakage=lambda c, seed: delete_sink_topic(c, seed),
expected_error="sink progress data exists, but sink data topic is missing",
# If we delete the progress topic, we will re-create the sink as if it is new.
fixage=lambda c, seed: c.exec(
"redpanda", "rpk", "topic", "delete", f"testdrive-progress-topic-{seed}"
),
),
KafkaSinkDisruption(
name="delete-sink-topic-recreate-topic-fix",
breakage=lambda c, seed: delete_sink_topic(c, seed),
expected_error="sink progress data exists, but sink data topic is missing",
# If we recreate the sink topic, the sink will work but will likely be inconsistent.
fixage=lambda c, seed: c.exec(
"redpanda", "rpk", "topic", "create", f"testdrive-sink-topic-{seed}"
),
),
KafkaDisruption(
name="delete-source-topic",
breakage=lambda c, seed: c.exec(
"redpanda", "rpk", "topic", "delete", f"testdrive-source-topic-{seed}"
),
expected_error="UnknownTopicOrPartition|topic",
fixage=None
# Re-creating the topic does not restart the source
# fixage=lambda c,seed: redpanda_topics(c, "create", seed),
),
KafkaDisruption(
name="pause-redpanda",
breakage=lambda c, _: c.pause("redpanda"),
expected_error="OperationTimedOut|BrokerTransportFailure|transaction",
fixage=lambda c, _: c.unpause("redpanda"),
),
KafkaDisruption(
name="kill-redpanda",
breakage=lambda c, _: c.kill("redpanda"),
expected_error="BrokerTransportFailure|Resolve|Broker transport failure|Timed out",
fixage=lambda c, _: c.up("redpanda"),
),
# https://github.com/MaterializeInc/materialize/issues/16582
# KafkaDisruption(
# name="kill-redpanda-clusterd",
# breakage=lambda c, _: c.kill("redpanda", "clusterd"),
# expected_error="???",
# fixage=lambda c, _: c.up("redpanda", "clusterd"),
# ),
PgDisruption(
name="kill-postgres",
breakage=lambda c, _: c.kill("postgres"),
expected_error="error connecting to server|connection closed|deadline has elapsed",
fixage=lambda c, _: c.up("postgres"),
),
PgDisruption(
name="drop-publication-postgres",
breakage=lambda c, _: c.testdrive(
dedent(
"""
$ postgres-execute connection=postgres://postgres:postgres@postgres
DROP PUBLICATION mz_source;
INSERT INTO source1 VALUES (3, NULL);
"""
)
),
expected_error="publication .+ does not exist",
# Can't recover when publication state is deleted.
fixage=None,
),
PgDisruption(
name="alter-postgres",
breakage=lambda c, _: alter_pg_table(c),
expected_error="source table source1 with oid .+ has been altered",
fixage=None,
),
PgDisruption(
name="unsupported-postgres",
breakage=lambda c, _: unsupported_pg_table(c),
expected_error="invalid input syntax for type array",
fixage=None,
),
# One-off disruption with a badly configured kafka sink
KafkaTransactionLogGreaterThan1(
name="bad-kafka-sink",
),
]
def workflow_default(c: Composition) -> None:
"""Test the detection and reporting of source/sink errors by
introducing a Disruption and then checking the mz_internal.mz_*_statuses tables
"""
for disruption in disruptions:
disruption.run_test(c)
def delete_sink_topic(c: Composition, seed: int) -> None:
c.exec("redpanda", "rpk", "topic", "delete", f"testdrive-sink-topic-{seed}")
# Write new data to source otherwise nothing will encounter the missing topic
c.testdrive(
schema()
+ dedent(
"""
$ kafka-ingest topic=source-topic format=avro schema=${schema}
{"f1": "B"}
> SELECT COUNT(*) FROM source1;
2
"""
)
)
def alter_pg_table(c: Composition) -> None:
c.testdrive(
dedent(
"""
$ postgres-execute connection=postgres://postgres:postgres@postgres
ALTER TABLE source1 DROP COLUMN f1;
INSERT INTO source1 VALUES (NULL)
"""
)
)
def unsupported_pg_table(c: Composition) -> None:
c.testdrive(
dedent(
"""
$ postgres-execute connection=postgres://postgres:postgres@postgres
INSERT INTO source1 VALUES (3, '[2:3]={2,2}')
"""
)
)