Skip to content

prefect.cli.worker

start async

Start a worker process to poll a work pool for flow runs.

Source code in prefect/cli/worker.py
 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
@worker_app.command()
async def start(
    worker_name: str = typer.Option(
        None,
        "-n",
        "--name",
        help=(
            "The name to give to the started worker. If not provided, a unique name"
            " will be generated."
        ),
    ),
    work_pool_name: str = typer.Option(
        ...,
        "-p",
        "--pool",
        help="The work pool the started worker should poll.",
        prompt=True,
    ),
    work_queues: List[str] = typer.Option(
        None,
        "-q",
        "--work-queue",
        help=(
            "One or more work queue names for the worker to pull from. If not provided,"
            " the worker will pull from all work queues in the work pool."
        ),
    ),
    worker_type: Optional[str] = typer.Option(
        None,
        "-t",
        "--type",
        help=(
            "The type of worker to start. If not provided, the worker type will be"
            " inferred from the work pool."
        ),
    ),
    prefetch_seconds: int = SettingsOption(
        PREFECT_WORKER_PREFETCH_SECONDS,
        help="Number of seconds to look into the future for scheduled flow runs.",
    ),
    run_once: bool = typer.Option(
        False, help="Only run worker polling once. By default, the worker runs forever."
    ),
    limit: int = typer.Option(
        None,
        "-l",
        "--limit",
        help="Maximum number of flow runs to start simultaneously.",
    ),
    with_healthcheck: bool = typer.Option(
        False, help="Start a healthcheck server for the worker."
    ),
    install_policy: InstallPolicy = typer.Option(
        InstallPolicy.PROMPT.value,
        "--install-policy",
        help="Install policy to use workers from Prefect integration packages.",
        case_sensitive=False,
    ),
    base_job_template: typer.FileText = typer.Option(
        None,
        "--base-job-template",
        help=(
            "The path to a JSON file containing the base job template to use. If"
            " unspecified, Prefect will use the default base job template for the given"
            " worker type. If the work pool already exists, this will be ignored."
        ),
    ),
):
    """
    Start a worker process to poll a work pool for flow runs.
    """

    is_paused = await _check_work_pool_paused(work_pool_name)
    if is_paused:
        app.console.print(
            (
                f"The work pool {work_pool_name!r} is currently paused. This worker"
                " will not execute any flow runs until the work pool is unpaused."
            ),
            style="yellow",
        )

    worker_cls = await _get_worker_class(worker_type, work_pool_name, install_policy)

    if worker_cls is None:
        exit_with_error(
            "Unable to start worker. Please ensure you have the necessary dependencies"
            " installed to run your desired worker type."
        )

    worker_process_id = os.getpid()
    setup_signal_handlers_worker(
        worker_process_id, f"the {worker_type} worker", app.console.print
    )

    template_contents = None
    if base_job_template is not None:
        template_contents = json.load(fp=base_job_template)

    async with worker_cls(
        name=worker_name,
        work_pool_name=work_pool_name,
        work_queues=work_queues,
        limit=limit,
        prefetch_seconds=prefetch_seconds,
        heartbeat_interval_seconds=PREFECT_WORKER_HEARTBEAT_SECONDS.value(),
        base_job_template=template_contents,
    ) as worker:
        app.console.print(f"Worker {worker.name!r} started!", style="green")
        async with anyio.create_task_group() as tg:
            # wait for an initial heartbeat to configure the worker
            await worker.sync_with_backend()
            # schedule the scheduled flow run polling loop
            tg.start_soon(
                partial(
                    critical_service_loop,
                    workload=worker.get_and_submit_flow_runs,
                    interval=PREFECT_WORKER_QUERY_SECONDS.value(),
                    run_once=run_once,
                    printer=app.console.print,
                    jitter_range=0.3,
                    backoff=4,  # Up to ~1 minute interval during backoff
                )
            )
            # schedule the sync loop
            tg.start_soon(
                partial(
                    critical_service_loop,
                    workload=worker.sync_with_backend,
                    interval=worker.heartbeat_interval_seconds,
                    run_once=run_once,
                    printer=app.console.print,
                    jitter_range=0.3,
                    backoff=4,
                )
            )
            tg.start_soon(
                partial(
                    critical_service_loop,
                    workload=worker.check_for_cancelled_flow_runs,
                    interval=PREFECT_WORKER_QUERY_SECONDS.value() * 2,
                    run_once=run_once,
                    printer=app.console.print,
                    jitter_range=0.3,
                    backoff=4,
                )
            )

            started_event = await worker._emit_worker_started_event()

            # if --with-healthcheck was passed, start the healthcheck server
            if with_healthcheck:
                # we'll start the ASGI server in a separate thread so that
                # uvicorn does not block the main thread
                server_thread = threading.Thread(
                    name="healthcheck-server-thread",
                    target=partial(
                        start_healthcheck_server,
                        worker=worker,
                        query_interval_seconds=PREFECT_WORKER_QUERY_SECONDS.value(),
                    ),
                    daemon=True,
                )
                server_thread.start()

    await worker._emit_worker_stopped_event(started_event)
    app.console.print(f"Worker {worker.name!r} stopped!")