Skip to content

prefect.cli.dev

Command line interface for working with Prefect Server

agent async

Starts a hot-reloading development agent process.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/cli/dev.py
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
@dev_app.command()
async def agent(
    api_url: str = SettingsOption(PREFECT_API_URL),
    work_queues: List[str] = typer.Option(
        ["default"],
        "-q",
        "--work-queue",
        help="One or more work queue names for the agent to pull from.",
    ),
):
    """
    Starts a hot-reloading development agent process.
    """
    # Delayed import since this is only a 'dev' dependency
    import watchfiles

    app.console.print("Creating hot-reloading agent process...")

    try:
        await watchfiles.arun_process(
            prefect.__module_path__,
            target=agent_process_entrypoint,
            kwargs=dict(api=api_url, work_queues=work_queues),
        )
    except RuntimeError as err:
        # a bug in watchfiles causes an 'Already borrowed' error from Rust when
        # exiting: https://github.com/samuelcolvin/watchfiles/issues/200
        if str(err).strip() != "Already borrowed":
            raise

agent_process_entrypoint

An entrypoint for starting an agent in a subprocess. Adds a Rich console to the Typer app, processes Typer default parameters, then starts an agent. All kwargs are forwarded to prefect.cli.agent.start.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/cli/dev.py
 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
def agent_process_entrypoint(**kwargs):
    """
    An entrypoint for starting an agent in a subprocess. Adds a Rich console
    to the Typer app, processes Typer default parameters, then starts an agent.
    All kwargs are forwarded to  `prefect.cli.agent.start`.
    """
    import inspect

    import rich

    # import locally so only the `dev` command breaks if Typer internals change
    from typer.models import ParameterInfo

    # Typer does not process default parameters when calling a function
    # directly, so we must set `start_agent`'s default parameters manually.
    # get the signature of the `start_agent` function
    start_agent_signature = inspect.signature(start_agent)

    # for any arguments not present in kwargs, use the default value.
    for name, param in start_agent_signature.parameters.items():
        if name not in kwargs:
            # All `param.default` values for start_agent are Typer params that store the
            # actual default value in their `default` attribute and we must call
            # `param.default.default` to get the actual default value. We should also
            # ensure we extract the right default if non-Typer defaults are added
            # to `start_agent` in the future.
            if isinstance(param.default, ParameterInfo):
                default = param.default.default
            else:
                default = param.default

            # Some defaults are Prefect `SettingsOption.value` methods
            # that must be called to get the actual value.
            kwargs[name] = default() if callable(default) else default

    # add a console, because calling the agent start function directly
    # instead of via CLI call means `app` has no `console` attached.
    app.console = (
        rich.console.Console(
            highlight=False,
            color_system="auto" if PREFECT_CLI_COLORS else None,
            soft_wrap=not PREFECT_CLI_WRAP_LINES.value(),
        )
        if not getattr(app, "console", None)
        else app.console
    )

    try:
        start_agent(**kwargs)  # type: ignore
    except KeyboardInterrupt:
        # expected when watchfiles kills the process
        pass

api async

Starts a hot-reloading development API.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/cli/dev.py
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
@dev_app.command()
async def api(
    host: str = SettingsOption(PREFECT_SERVER_API_HOST),
    port: int = SettingsOption(PREFECT_SERVER_API_PORT),
    log_level: str = "DEBUG",
    services: bool = True,
):
    """
    Starts a hot-reloading development API.
    """
    import watchfiles

    server_env = os.environ.copy()
    server_env["PREFECT_API_SERVICES_RUN_IN_APP"] = str(services)
    server_env["PREFECT_API_SERVICES_UI"] = "False"
    server_env["PREFECT_UI_API_URL"] = f"http://{host}:{port}/api"

    command = [
        sys.executable,
        "-m",
        "uvicorn",
        "--factory",
        "prefect.server.api.server:create_app",
        "--host",
        str(host),
        "--port",
        str(port),
        "--log-level",
        log_level.lower(),
    ]

    app.console.print(f"Running: {' '.join(command)}")
    import signal

    stop_event = anyio.Event()
    start_command = partial(
        run_process, command=command, env=server_env, stream_output=True
    )

    async with anyio.create_task_group() as tg:
        try:
            server_pid = await tg.start(start_command)
            async for _ in watchfiles.awatch(
                prefect.__module_path__, stop_event=stop_event  # type: ignore
            ):
                # when any watched files change, restart the server
                app.console.print("Restarting Prefect Server...")
                os.kill(server_pid, signal.SIGTERM)  # type: ignore
                # start a new server
                server_pid = await tg.start(start_command)
        except RuntimeError as err:
            # a bug in watchfiles causes an 'Already borrowed' error from Rust when
            # exiting: https://github.com/samuelcolvin/watchfiles/issues/200
            if str(err).strip() != "Already borrowed":
                raise
        except KeyboardInterrupt:
            # exit cleanly on ctrl-c by killing the server process if it's
            # still running
            try:
                os.kill(server_pid, signal.SIGTERM)  # type: ignore
            except ProcessLookupError:
                # process already exited
                pass

            stop_event.set()

build_docs

Builds REST API reference documentation for static display.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/cli/dev.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
@dev_app.command()
def build_docs(
    schema_path: str = None,
):
    """
    Builds REST API reference documentation for static display.
    """
    exit_with_error_if_not_editable_install()

    from prefect.server.api.server import create_app

    schema = create_app(ephemeral=True).openapi()

    if not schema_path:
        schema_path = (
            prefect.__development_base_path__ / "docs" / "api-ref" / "schema.json"
        ).absolute()
    # overwrite info for display purposes
    schema["info"] = {}
    with open(schema_path, "w") as f:
        json.dump(schema, f)
    app.console.print(f"OpenAPI schema written to {schema_path}")

build_image

Build a docker image for development.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/cli/dev.py
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
@dev_app.command()
def build_image(
    arch: str = typer.Option(
        None,
        help=(
            "The architecture to build the container for. "
            "Defaults to the architecture of the host Python. "
            f"[default: {platform.machine()}]"
        ),
    ),
    python_version: str = typer.Option(
        None,
        help=(
            "The Python version to build the container for. "
            "Defaults to the version of the host Python. "
            f"[default: {python_version_minor()}]"
        ),
    ),
    flavor: str = typer.Option(
        None,
        help=(
            "An alternative flavor to build, for example 'conda'. "
            "Defaults to the standard Python base image"
        ),
    ),
    dry_run: bool = False,
):
    """
    Build a docker image for development.
    """
    exit_with_error_if_not_editable_install()
    # TODO: Once https://github.com/tiangolo/typer/issues/354 is addresesd, the
    #       default can be set in the function signature
    arch = arch or platform.machine()
    python_version = python_version or python_version_minor()

    tag = get_prefect_image_name(python_version=python_version, flavor=flavor)

    # Here we use a subprocess instead of the docker-py client to easily stream output
    # as it comes
    command = [
        "docker",
        "build",
        str(prefect.__development_base_path__),
        "--tag",
        tag,
        "--platform",
        f"linux/{arch}",
        "--build-arg",
        "PREFECT_EXTRAS=[dev]",
        "--build-arg",
        f"PYTHON_VERSION={python_version}",
    ]

    if flavor:
        command += ["--build-arg", f"BASE_IMAGE=prefect-{flavor}"]

    if dry_run:
        print(" ".join(command))
        return

    try:
        subprocess.check_call(command, shell=sys.platform == "win32")
    except subprocess.CalledProcessError:
        exit_with_error("Failed to build image!")
    else:
        exit_with_success(f"Built image {tag!r} for linux/{arch}")

container

Run a docker container with local code mounted and installed.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/cli/dev.py
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
@dev_app.command()
def container(bg: bool = False, name="prefect-dev", api: bool = True, tag: str = None):
    """
    Run a docker container with local code mounted and installed.
    """
    exit_with_error_if_not_editable_install()
    import docker
    from docker.models.containers import Container

    client = docker.from_env()

    containers = client.containers.list()
    container_names = {container.name for container in containers}
    if name in container_names:
        exit_with_error(
            f"Container {name!r} already exists. Specify a different name or stop "
            "the existing container."
        )

    blocking_cmd = "prefect dev api" if api else "sleep infinity"
    tag = tag or get_prefect_image_name()

    container: Container = client.containers.create(
        image=tag,
        command=[
            "/bin/bash",
            "-c",
            (  # noqa
                "pip install -e /opt/prefect/repo\\[dev\\] && touch /READY &&"
                f" {blocking_cmd}"
            ),
        ],
        name=name,
        auto_remove=True,
        working_dir="/opt/prefect/repo",
        volumes=[f"{prefect.__development_base_path__}:/opt/prefect/repo"],
        shm_size="4G",
    )

    print(f"Starting container for image {tag!r}...")
    container.start()

    print("Waiting for installation to complete", end="", flush=True)
    try:
        ready = False
        while not ready:
            print(".", end="", flush=True)
            result = container.exec_run("test -f /READY")
            ready = result.exit_code == 0
            if not ready:
                time.sleep(3)
    except BaseException:
        print("\nInterrupted. Stopping container...")
        container.stop()
        raise

    print(
        textwrap.dedent(
            f"""
            Container {container.name!r} is ready! To connect to the container, run:

                docker exec -it {container.name} /bin/bash
            """
        )
    )

    if bg:
        print(
            textwrap.dedent(
                f"""
                The container will run forever. Stop the container with:

                    docker stop {container.name}
                """
            )
        )
        # Exit without stopping
        return

    try:
        print("Send a keyboard interrupt to exit...")
        container.wait()
    except KeyboardInterrupt:
        pass  # Avoid showing "Abort"
    finally:
        print("\nStopping container...")
        container.stop()

kubernetes_manifest

Generates a Kubernetes manifest for development.

Example

$ prefect dev kubernetes-manifest | kubectl apply -f -

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/cli/dev.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
@dev_app.command()
def kubernetes_manifest():
    """
    Generates a Kubernetes manifest for development.

    Example:
        $ prefect dev kubernetes-manifest | kubectl apply -f -
    """
    exit_with_error_if_not_editable_install()

    template = Template(
        (
            prefect.__module_path__ / "cli" / "templates" / "kubernetes-dev.yaml"
        ).read_text()
    )
    manifest = template.substitute(
        {
            "prefect_root_directory": prefect.__development_base_path__,
            "image_name": get_prefect_image_name(),
        }
    )
    print(manifest)

start async

Starts a hot-reloading development server with API, UI, and agent processes.

Each service has an individual command if you wish to start them separately. Each service can be excluded here as well.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/cli/dev.py
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
@dev_app.command()
async def start(
    exclude_api: bool = typer.Option(False, "--no-api"),
    exclude_ui: bool = typer.Option(False, "--no-ui"),
    exclude_agent: bool = typer.Option(False, "--no-agent"),
    work_queues: List[str] = typer.Option(
        ["default"],
        "-q",
        "--work-queue",
        help="One or more work queue names for the dev agent to pull from.",
    ),
):
    """
    Starts a hot-reloading development server with API, UI, and agent processes.

    Each service has an individual command if you wish to start them separately.
    Each service can be excluded here as well.
    """
    async with anyio.create_task_group() as tg:
        if not exclude_api:
            tg.start_soon(
                partial(
                    api,
                    host=PREFECT_SERVER_API_HOST.value(),
                    port=PREFECT_SERVER_API_PORT.value(),
                )
            )
        if not exclude_ui:
            tg.start_soon(ui)
        if not exclude_agent:
            # Hook the agent to the hosted API if running
            if not exclude_api:
                host = f"http://{PREFECT_SERVER_API_HOST.value()}:{PREFECT_SERVER_API_PORT.value()}/api"  # noqa
            else:
                host = PREFECT_API_URL.value()
            tg.start_soon(agent, host, work_queues)

ui async

Starts a hot-reloading development UI.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/cli/dev.py
178
179
180
181
182
183
184
185
186
187
188
189
190
@dev_app.command()
async def ui():
    """
    Starts a hot-reloading development UI.
    """
    exit_with_error_if_not_editable_install()
    with tmpchdir(prefect.__development_base_path__):
        with tmpchdir(prefect.__development_base_path__ / "ui"):
            app.console.print("Installing npm packages...")
            await run_process(["npm", "install"], stream_output=True)

            app.console.print("Starting UI development server...")
            await run_process(command=["npm", "run", "serve"], stream_output=True)