-
-
Notifications
You must be signed in to change notification settings - Fork 4k
/
run.py
506 lines (429 loc) · 15.5 KB
/
run.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
from __future__ import annotations
import logging
import os
import signal
from multiprocessing import cpu_count
import click
from sentry.bgtasks.api import managed_bgtasks
from sentry.runner.decorators import configuration, log_options
from sentry.utils.kafka import run_processor_with_signals
DEFAULT_BLOCK_SIZE = int(32 * 1e6)
def _address_validate(
ctx: click.Context, param: click.Parameter, value: str | None
) -> tuple[str | None, int | None]:
if value is None:
return (None, None)
if ":" in value:
host, port_s = value.split(":", 1)
port: int | None = int(port_s)
else:
host = value
port = None
return host, port
class QueueSetType(click.ParamType):
name = "text"
def convert(self, value, param, ctx):
if value is None:
return None
# Providing a compatibility with splitting
# the `events` queue until multiple queues
# without the need to explicitly add them.
queues = set()
for queue in value.split(","):
if queue == "events":
queues.add("events.preprocess_event")
queues.add("events.process_event")
queues.add("events.save_event")
from sentry.runner.initializer import show_big_error
show_big_error(
[
"DEPRECATED",
"`events` queue no longer exists.",
"Switch to using:",
"- events.preprocess_event",
"- events.process_event",
"- events.save_event",
]
)
else:
queues.add(queue)
return frozenset(queues)
QueueSet = QueueSetType()
def kafka_options(
consumer_group: str,
allow_force_cluster: bool = True,
include_batching_options: bool = False,
default_max_batch_size: int | None = None,
default_max_batch_time_ms: int | None = 1000,
):
"""
Basic set of Kafka options for a consumer.
"""
def inner(f):
f = click.option(
"--consumer-group",
"group_id",
default=consumer_group,
help="Kafka consumer group for the consumer.",
)(f)
f = click.option(
"--auto-offset-reset",
"auto_offset_reset",
default="latest",
type=click.Choice(["earliest", "latest", "error"]),
help="Position in the commit log topic to begin reading from when no prior offset has been recorded.",
)(f)
if include_batching_options:
f = click.option(
"--max-batch-size",
"max_batch_size",
default=default_max_batch_size,
type=int,
help="Maximum number of messages to batch before flushing.",
)(f)
f = click.option(
"--max-batch-time-ms",
"max_batch_time",
default=default_max_batch_time_ms,
type=int,
help="Maximum time (in seconds) to wait before flushing a batch.",
)(f)
if allow_force_cluster:
f = click.option(
"--force-topic",
"force_topic",
default=None,
type=str,
help="Override the Kafka topic the consumer will read from.",
)(f)
f = click.option(
"--force-cluster",
"force_cluster",
default=None,
type=str,
help="Kafka cluster ID of the overridden topic. Configure clusters via KAFKA_CLUSTERS in server settings.",
)(f)
return f
return inner
def strict_offset_reset_option():
return click.option(
"--strict-offset-reset/--no-strict-offset-reset",
default=True,
help=(
"--strict-offset-reset, the default, means that the kafka consumer "
"still errors in case the offset is out of range.\n\n"
"--no-strict-offset-reset will use the auto offset reset even in that case. "
"This is useful in development, but not desirable in production since expired "
"offsets mean data-loss.\n\n"
"Most consumers that do not have this option at all default to 'Not Strict'."
),
)
@click.group()
def run():
"Run a service."
@run.command()
@click.option(
"--bind",
"-b",
default=None,
help="Bind address.",
metavar="ADDRESS",
callback=_address_validate,
)
@click.option(
"--workers", "-w", default=0, help="The number of worker processes for handling requests."
)
@click.option("--upgrade", default=False, is_flag=True, help="Upgrade before starting.")
@click.option(
"--with-lock", default=False, is_flag=True, help="Use a lock if performing an upgrade."
)
@click.option(
"--noinput", default=False, is_flag=True, help="Do not prompt the user for input of any kind."
)
@log_options()
@configuration
def web(bind, workers, upgrade, with_lock, noinput):
"Run web service."
if upgrade:
click.echo("Performing upgrade before service startup...")
from sentry.runner import call_command
try:
call_command(
"sentry.runner.commands.upgrade.upgrade",
verbosity=0,
noinput=noinput,
lock=with_lock,
)
except click.ClickException:
if with_lock:
click.echo("!! Upgrade currently running from another process, skipping.", err=True)
else:
raise
with managed_bgtasks(role="web"):
from sentry.services.http import SentryHTTPServer
SentryHTTPServer(host=bind[0], port=bind[1], workers=workers).run()
def run_worker(**options):
"""
This is the inner function to actually start worker.
"""
from django.conf import settings
if settings.CELERY_ALWAYS_EAGER:
raise click.ClickException(
"Disable CELERY_ALWAYS_EAGER in your settings file to spawn workers."
)
# These options are no longer used, but keeping around
# for backwards compatibility
for o in "without_gossip", "without_mingle", "without_heartbeat":
options.pop(o, None)
from sentry.celery import app
# NOTE: without_mingle breaks everything,
# we can't get rid of this. Intentionally kept
# here as a warning. Jobs will not process.
without_mingle = os.getenv("SENTRY_WORKER_FORCE_WITHOUT_MINGLE", "false").lower() == "true"
with managed_bgtasks(role="worker"):
worker = app.Worker(
without_mingle=without_mingle,
without_gossip=True,
without_heartbeat=True,
pool_cls="processes",
**options,
)
worker.start()
raise SystemExit(worker.exitcode)
@run.command()
@click.option(
"--hostname",
"-n",
help=(
"Set custom hostname, e.g. 'w1.%h'. Expands: %h" "(hostname), %n (name) and %d, (domain)."
),
)
@click.option(
"--queues",
"-Q",
type=QueueSet,
help=(
"List of queues to enable for this worker, separated by "
"comma. By default all configured queues are enabled. "
"Example: -Q video,image"
),
)
@click.option("--exclude-queues", "-X", type=QueueSet)
@click.option(
"--concurrency",
"-c",
default=cpu_count(),
help=(
"Number of child processes processing the queue. The "
"default is the number of CPUs available on your "
"system."
),
)
@click.option(
"--logfile", "-f", help=("Path to log file. If no logfile is specified, stderr is used.")
)
@click.option("--quiet", "-q", is_flag=True, default=False)
@click.option("--no-color", is_flag=True, default=False)
@click.option("--autoreload", is_flag=True, default=False, help="Enable autoreloading.")
@click.option("--without-gossip", is_flag=True, default=False)
@click.option("--without-mingle", is_flag=True, default=False)
@click.option("--without-heartbeat", is_flag=True, default=False)
@click.option("--max-tasks-per-child", default=10000)
@click.option("--ignore-unknown-queues", is_flag=True, default=False)
@log_options()
@configuration
def worker(ignore_unknown_queues, **options):
"""Run background worker instance and autoreload if necessary."""
from sentry.celery import app
known_queues = frozenset(c_queue.name for c_queue in app.conf.CELERY_QUEUES)
if options["queues"] is not None:
if not options["queues"].issubset(known_queues):
unknown_queues = options["queues"] - known_queues
message = "Following queues are not found: %s" % ",".join(sorted(unknown_queues))
if ignore_unknown_queues:
options["queues"] -= unknown_queues
click.echo(message)
else:
raise click.ClickException(message)
if options["exclude_queues"] is not None:
if not options["exclude_queues"].issubset(known_queues):
unknown_queues = options["exclude_queues"] - known_queues
message = "Following queues cannot be excluded as they don't exist: %s" % ",".join(
sorted(unknown_queues)
)
if ignore_unknown_queues:
options["exclude_queues"] -= unknown_queues
click.echo(message)
else:
raise click.ClickException(message)
if options["autoreload"]:
from django.utils import autoreload
autoreload.run_with_reloader(run_worker, **options)
else:
run_worker(**options)
@run.command()
@click.option(
"--pidfile",
help=(
"Optional file used to store the process pid. The "
"program will not start if this file already exists and "
"the pid is still alive."
),
)
@click.option(
"--logfile", "-f", help=("Path to log file. If no logfile is specified, stderr is used.")
)
@click.option("--quiet", "-q", is_flag=True, default=False)
@click.option("--no-color", is_flag=True, default=False)
@click.option("--autoreload", is_flag=True, default=False, help="Enable autoreloading.")
@click.option("--without-gossip", is_flag=True, default=False)
@click.option("--without-mingle", is_flag=True, default=False)
@click.option("--without-heartbeat", is_flag=True, default=False)
@log_options()
@configuration
def cron(**options):
"Run periodic task dispatcher."
from django.conf import settings
if settings.CELERY_ALWAYS_EAGER:
raise click.ClickException(
"Disable CELERY_ALWAYS_EAGER in your settings file to spawn workers."
)
from sentry.celery import app
with managed_bgtasks(role="cron"):
app.Beat(
# without_gossip=True,
# without_mingle=True,
# without_heartbeat=True,
**options
).run()
@run.command("consumer")
@log_options()
@click.argument(
"consumer_name",
)
@click.argument("consumer_args", nargs=-1)
@click.option(
"--topic",
type=str,
help="Which physical topic to use for this consumer. This can be a topic name that is not specified in settings. The logical topic is still hardcoded in sentry.consumers.",
)
@click.option(
"--cluster", type=str, help="Which cluster definition from settings to use for this consumer."
)
@click.option(
"--consumer-group",
"group_id",
required=True,
help="Kafka consumer group for the consumer.",
)
@click.option(
"--auto-offset-reset",
"auto_offset_reset",
default="latest",
type=click.Choice(["earliest", "latest", "error"]),
help="Position in the commit log topic to begin reading from when no prior offset has been recorded.",
)
@click.option("--join-timeout", type=float, help="Join timeout in seconds.", default=None)
@click.option(
"--max-poll-interval-ms",
type=int,
default=30000,
)
@click.option(
"--group-instance-id",
type=str,
default=None,
)
@click.option(
"--synchronize-commit-log-topic",
help="Topic that the Snuba writer is publishing its committed offsets to.",
)
@click.option(
"--synchronize-commit-group",
help="Consumer group that the Snuba writer is committing its offset as.",
)
@click.option(
"--healthcheck-file-path",
help="A file to touch roughly every second to indicate that the consumer is still alive. See https://getsentry.github.io/arroyo/strategies/healthcheck.html for more information.",
)
@click.option(
"--enable-dlq",
help="Enable dlq to route invalid messages to. See https://getsentry.github.io/arroyo/dlqs.html#arroyo.dlq.DlqPolicy for more information.",
is_flag=True,
default=False,
)
@click.option(
"--log-level",
type=click.Choice(["debug", "info", "warning", "error", "critical"], case_sensitive=False),
help="log level to pass to the arroyo consumer",
)
@strict_offset_reset_option()
@configuration
def basic_consumer(consumer_name, consumer_args, topic, **options):
"""
Launch a "new-style" consumer based on its "consumer name".
Example:
sentry run consumer ingest-profiles --consumer-group ingest-profiles
runs the ingest-profiles consumer with the consumer group ingest-profiles.
Consumers are defined in 'sentry.consumers'. Each consumer can take
additional CLI options. Those can be passed after '--':
sentry run consumer ingest-occurrences --consumer-group occurrence-consumer -- --processes 1
Consumer-specific arguments can be viewed with:
sentry run consumer ingest-occurrences --consumer-group occurrence-consumer -- --help
"""
from sentry.consumers import get_stream_processor
from sentry.metrics.middleware import add_global_tags
from sentry.utils.arroyo import initialize_arroyo_main
log_level = options.pop("log_level", None)
if log_level is not None:
logging.getLogger("arroyo").setLevel(log_level.upper())
add_global_tags(kafka_topic=topic, consumer_group=options["group_id"])
initialize_arroyo_main()
processor = get_stream_processor(consumer_name, consumer_args, topic=topic, **options)
run_processor_with_signals(processor, consumer_name)
@run.command("dev-consumer")
@click.argument("consumer_names", nargs=-1)
@log_options()
@configuration
def dev_consumer(consumer_names):
"""
Launch multiple "new-style" consumers in the same thread.
This does the same thing as 'sentry run consumer', but is not configurable,
hardcodes consumer groups and is highly imperformant.
"""
from sentry.consumers import get_stream_processor
from sentry.utils.arroyo import initialize_arroyo_main
initialize_arroyo_main()
processors = [
get_stream_processor(
consumer_name,
[],
topic=None,
cluster=None,
group_id="sentry-consumer",
auto_offset_reset="latest",
strict_offset_reset=False,
join_timeout=None,
max_poll_interval_ms=None,
synchronize_commit_group=None,
synchronize_commit_log_topic=None,
enable_dlq=False,
healthcheck_file_path=None,
enforce_schema=True,
)
for consumer_name in consumer_names
]
def handler(signum, frame):
for processor in processors:
processor.signal_shutdown()
signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)
while True:
for processor in processors:
processor._run_once()
@run.command("backpressure-monitor")
@log_options()
@configuration
def backpressure_monitor():
from sentry.processing.backpressure.monitor import start_service_monitoring
start_service_monitoring()