Skip to content

prefect.infrastructure

DockerContainer

Bases: Infrastructure

Runs a command in a container.

Requires a Docker Engine to be connectable. Docker settings will be retrieved from the environment.

Click here to see a tutorial.

Attributes:

Name Type Description
auto_remove bool

If set, the container will be removed on completion. Otherwise, the container will remain after exit for inspection.

command bool

A list of strings specifying the command to run in the container to start the flow run. In most cases you should not override this.

env bool

Environment variables to set for the container.

image str

An optional string specifying the tag of a Docker image to use. Defaults to the Prefect image.

image_pull_policy Optional[ImagePullPolicy]

Specifies if the image should be pulled. One of 'ALWAYS', 'NEVER', 'IF_NOT_PRESENT'.

image_registry Optional[DockerRegistry]

A DockerRegistry block containing credentials to use if image is stored in a private image registry.

labels Optional[DockerRegistry]

An optional dictionary of labels, mapping name to value.

name Optional[DockerRegistry]

An optional name for the container.

network_mode Optional[str]

Set the network mode for the created container. Defaults to 'host' if a local API url is detected, otherwise the Docker default of 'bridge' is used. If 'networks' is set, this cannot be set.

networks List[str]

An optional list of strings specifying Docker networks to connect the container to.

stream_output bool

If set, stream output from the container to local standard output.

volumes List[str]

An optional list of volume mount strings in the format of "local_path:container_path".

memswap_limit Union[int, str]

Total memory (memory + swap), -1 to disable swap. Should only be set if mem_limit is also set. If mem_limit is set, this defaults to allowing the container to use as much swap as memory. For example, if mem_limit is 300m and memswap_limit is not set, the container can use 600m in total of memory and swap.

mem_limit Union[float, str]

Memory limit of the created container. Accepts float values to enforce a limit in bytes or a string with a unit e.g. 100000b, 1000k, 128m, 1g. If a string is given without a unit, bytes are assumed.

privileged bool

Give extended privileges to this container.

Connecting to a locally hosted Prefect API

If using a local API URL on Linux, we will update the network mode default to 'host' to enable connectivity. If using another OS or an alternative network mode is used, we will replace 'localhost' in the API URL with 'host.docker.internal'. Generally, this will enable connectivity, but the API URL can be provided as an environment variable to override inference in more complex use-cases.

Note, if using 'host.docker.internal' in the API URL on Linux, the API must be bound to 0.0.0.0 or the Docker IP address to allow connectivity. On macOS, this is not necessary and the API is connectable while bound to localhost.

Source code in prefect/infrastructure/container.py
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
@deprecated_class(
    start_date="Mar 2024",
    help="Use the Docker worker from prefect-docker instead."
    " Refer to the upgrade guide for more information:"
    " https://docs.prefect.io/latest/guides/upgrade-guide-agents-to-workers/.",
)
class DockerContainer(Infrastructure):
    """
    Runs a command in a container.

    Requires a Docker Engine to be connectable. Docker settings will be retrieved from
    the environment.

    Click [here](https://docs.prefect.io/guides/deployment/docker) to see a tutorial.

    Attributes:
        auto_remove: If set, the container will be removed on completion. Otherwise,
            the container will remain after exit for inspection.
        command: A list of strings specifying the command to run in the container to
            start the flow run. In most cases you should not override this.
        env: Environment variables to set for the container.
        image: An optional string specifying the tag of a Docker image to use.
            Defaults to the Prefect image.
        image_pull_policy: Specifies if the image should be pulled. One of 'ALWAYS',
            'NEVER', 'IF_NOT_PRESENT'.
        image_registry: A `DockerRegistry` block containing credentials to use if `image` is stored in a private
            image registry.
        labels: An optional dictionary of labels, mapping name to value.
        name: An optional name for the container.
        network_mode: Set the network mode for the created container. Defaults to 'host'
            if a local API url is detected, otherwise the Docker default of 'bridge' is
            used. If 'networks' is set, this cannot be set.
        networks: An optional list of strings specifying Docker networks to connect the
            container to.
        stream_output: If set, stream output from the container to local standard output.
        volumes: An optional list of volume mount strings in the format of
            "local_path:container_path".
        memswap_limit: Total memory (memory + swap), -1 to disable swap. Should only be
            set if `mem_limit` is also set. If `mem_limit` is set, this defaults to
            allowing the container to use as much swap as memory. For example, if
            `mem_limit` is 300m and `memswap_limit` is not set, the container can use
            600m in total of memory and swap.
        mem_limit: Memory limit of the created container. Accepts float values to enforce
            a limit in bytes or a string with a unit e.g. 100000b, 1000k, 128m, 1g.
            If a string is given without a unit, bytes are assumed.
        privileged: Give extended privileges to this container.

    ## Connecting to a locally hosted Prefect API

    If using a local API URL on Linux, we will update the network mode default to 'host'
    to enable connectivity. If using another OS or an alternative network mode is used,
    we will replace 'localhost' in the API URL with 'host.docker.internal'. Generally,
    this will enable connectivity, but the API URL can be provided as an environment
    variable to override inference in more complex use-cases.

    Note, if using 'host.docker.internal' in the API URL on Linux, the API must be bound
    to 0.0.0.0 or the Docker IP address to allow connectivity. On macOS, this is not
    necessary and the API is connectable while bound to localhost.
    """

    type: Literal["docker-container"] = Field(
        default="docker-container", description="The type of infrastructure."
    )
    image: str = Field(
        default_factory=get_prefect_image_name,
        description="Tag of a Docker image to use. Defaults to the Prefect image.",
    )
    image_pull_policy: Optional[ImagePullPolicy] = Field(
        default=None, description="Specifies if the image should be pulled."
    )
    image_registry: Optional[DockerRegistry] = None
    networks: List[str] = Field(
        default_factory=list,
        description=(
            "A list of strings specifying Docker networks to connect the container to."
        ),
    )
    network_mode: Optional[str] = Field(
        default=None,
        description=(
            "The network mode for the created container (e.g. host, bridge). If"
            " 'networks' is set, this cannot be set."
        ),
    )
    auto_remove: bool = Field(
        default=False,
        description="If set, the container will be removed on completion.",
    )
    volumes: List[str] = Field(
        default_factory=list,
        description=(
            "A list of volume mount strings in the format of"
            ' "local_path:container_path".'
        ),
    )
    stream_output: bool = Field(
        default=True,
        description=(
            "If set, the output will be streamed from the container to local standard"
            " output."
        ),
    )
    memswap_limit: Union[int, str] = Field(
        default=None,
        description=(
            "Total memory (memory + swap), -1 to disable swap. Should only be "
            "set if `mem_limit` is also set. If `mem_limit` is set, this defaults to"
            "allowing the container to use as much swap as memory. For example, if "
            "`mem_limit` is 300m and `memswap_limit` is not set, the container can use "
            "600m in total of memory and swap."
        ),
    )
    mem_limit: Union[float, str] = Field(
        default=None,
        description=(
            "Memory limit of the created container. Accepts float values to enforce "
            "a limit in bytes or a string with a unit e.g. 100000b, 1000k, 128m, 1g. "
            "If a string is given without a unit, bytes are assumed."
        ),
    )
    privileged: bool = Field(
        default=False,
        description="Give extended privileges to this container.",
    )

    _block_type_name = "Docker Container"
    _logo_url = "https://cdn.sanity.io/images/3ugk85nk/production/14a315b79990200db7341e42553e23650b34bb96-250x250.png"
    _documentation_url = "https://docs.prefect.io/api-ref/prefect/infrastructure/#prefect.infrastructure.DockerContainer"

    @validator("labels")
    def convert_labels_to_docker_format(cls, labels: Dict[str, str]):
        labels = labels or {}
        new_labels = {}
        for name, value in labels.items():
            if "/" in name:
                namespace, key = name.split("/", maxsplit=1)
                new_namespace = ".".join(reversed(namespace.split(".")))
                new_labels[f"{new_namespace}.{key}"] = value
            else:
                new_labels[name] = value
        return new_labels

    @validator("volumes")
    def check_volume_format(cls, volumes):
        for volume in volumes:
            if ":" not in volume:
                raise ValueError(
                    "Invalid volume specification. "
                    f"Expected format 'path:container_path', but got {volume!r}"
                )

        return volumes

    @sync_compatible
    async def run(
        self,
        task_status: Optional[anyio.abc.TaskStatus] = None,
    ) -> Optional[bool]:
        if not self.command:
            raise ValueError("Docker container cannot be run with empty command.")

        # The `docker` library uses requests instead of an async http library so it must
        # be run in a thread to avoid blocking the event loop.
        container = await run_sync_in_worker_thread(self._create_and_start_container)
        container_pid = self._get_infrastructure_pid(container_id=container.id)

        # Mark as started and return the infrastructure id
        if task_status:
            task_status.started(container_pid)

        # Monitor the container
        container = await run_sync_in_worker_thread(
            self._watch_container_safe, container
        )

        exit_code = container.attrs["State"].get("ExitCode")
        return DockerContainerResult(
            status_code=exit_code if exit_code is not None else -1,
            identifier=container_pid,
        )

    async def kill(self, infrastructure_pid: str, grace_seconds: int = 30):
        docker_client = self._get_client()
        base_url, container_id = self._parse_infrastructure_pid(infrastructure_pid)

        if docker_client.api.base_url != base_url:
            raise InfrastructureNotAvailable(
                "".join(
                    [
                        (
                            f"Unable to stop container {container_id!r}: the current"
                            " Docker API "
                        ),
                        (
                            f"URL {docker_client.api.base_url!r} does not match the"
                            " expected "
                        ),
                        f"API base URL {base_url}.",
                    ]
                )
            )
        try:
            container = docker_client.containers.get(container_id=container_id)
        except docker.errors.NotFound:
            raise InfrastructureNotFound(
                f"Unable to stop container {container_id!r}: The container was not"
                " found."
            )

        try:
            container.stop(timeout=grace_seconds)
        except Exception:
            raise

    def preview(self):
        # TODO: build and document a more sophisticated preview
        docker_client = self._get_client()
        try:
            return json.dumps(self._build_container_settings(docker_client))
        finally:
            docker_client.close()

    async def generate_work_pool_base_job_template(self):
        from prefect.workers.utilities import (
            get_default_base_job_template_for_infrastructure_type,
        )

        base_job_template = await get_default_base_job_template_for_infrastructure_type(
            self.get_corresponding_worker_type()
        )
        if base_job_template is None:
            return await super().generate_work_pool_base_job_template()
        for key, value in self.dict(exclude_unset=True, exclude_defaults=True).items():
            if key == "command":
                base_job_template["variables"]["properties"]["command"][
                    "default"
                ] = shlex.join(value)
            elif key == "image_registry":
                self.logger.warning(
                    "Image registry blocks are not supported by Docker"
                    " work pools. Please authenticate to your registry using"
                    " the `docker login` command on your worker instances."
                )
            elif key in [
                "type",
                "block_type_slug",
                "_block_document_id",
                "_block_document_name",
                "_is_anonymous",
            ]:
                continue
            elif key == "image_pull_policy":
                new_value = None
                if value == ImagePullPolicy.ALWAYS:
                    new_value = "Always"
                elif value == ImagePullPolicy.NEVER:
                    new_value = "Never"
                elif value == ImagePullPolicy.IF_NOT_PRESENT:
                    new_value = "IfNotPresent"

                base_job_template["variables"]["properties"][key]["default"] = new_value
            elif key in base_job_template["variables"]["properties"]:
                base_job_template["variables"]["properties"][key]["default"] = value
            else:
                self.logger.warning(
                    f"Variable {key!r} is not supported by Docker work pools. Skipping."
                )

        return base_job_template

    def get_corresponding_worker_type(self):
        return "docker"

    def _get_infrastructure_pid(self, container_id: str) -> str:
        """Generates a Docker infrastructure_pid string in the form of
        `<docker_host_base_url>:<container_id>`.
        """
        docker_client = self._get_client()
        base_url = docker_client.api.base_url
        docker_client.close()
        return f"{base_url}:{container_id}"

    def _parse_infrastructure_pid(self, infrastructure_pid: str) -> Tuple[str, str]:
        """Splits a Docker infrastructure_pid into its component parts"""

        # base_url can contain `:` so we only want the last item of the split
        base_url, container_id = infrastructure_pid.rsplit(":", 1)
        return base_url, str(container_id)

    def _build_container_settings(
        self,
        docker_client: "DockerClient",
    ) -> Dict:
        network_mode = self._get_network_mode()
        return dict(
            image=self.image,
            network=self.networks[0] if self.networks else None,
            network_mode=network_mode,
            command=self.command,
            environment=self._get_environment_variables(network_mode),
            auto_remove=self.auto_remove,
            labels={**CONTAINER_LABELS, **self.labels},
            extra_hosts=self._get_extra_hosts(docker_client),
            name=self._get_container_name(),
            volumes=self.volumes,
            mem_limit=self.mem_limit,
            memswap_limit=self.memswap_limit,
            privileged=self.privileged,
        )

    def _create_and_start_container(self) -> "Container":
        if self.image_registry:
            # If an image registry block was supplied, load an authenticated Docker
            # client from the block. Otherwise, use an unauthenticated client to
            # pull images from public registries.
            docker_client = self.image_registry.get_docker_client()
        else:
            docker_client = self._get_client()
        container_settings = self._build_container_settings(docker_client)

        if self._should_pull_image(docker_client):
            self.logger.info(f"Pulling image {self.image!r}...")
            self._pull_image(docker_client)

        container = self._create_container(docker_client, **container_settings)

        # Add additional networks after the container is created; only one network can
        # be attached at creation time
        if len(self.networks) > 1:
            for network_name in self.networks[1:]:
                network = docker_client.networks.get(network_name)
                network.connect(container)

        # Start the container
        container.start()

        docker_client.close()

        return container

    def _get_image_and_tag(self) -> Tuple[str, Optional[str]]:
        return parse_image_tag(self.image)

    def _determine_image_pull_policy(self) -> ImagePullPolicy:
        """
        Determine the appropriate image pull policy.

        1. If they specified an image pull policy, use that.

        2. If they did not specify an image pull policy and gave us
           the "latest" tag, use ImagePullPolicy.always.

        3. If they did not specify an image pull policy and did not
           specify a tag, use ImagePullPolicy.always.

        4. If they did not specify an image pull policy and gave us
           a tag other than "latest", use ImagePullPolicy.if_not_present.

        This logic matches the behavior of Kubernetes.
        See:https://kubernetes.io/docs/concepts/containers/images/#imagepullpolicy-defaulting
        """
        if not self.image_pull_policy:
            _, tag = self._get_image_and_tag()
            if tag == "latest" or not tag:
                return ImagePullPolicy.ALWAYS
            return ImagePullPolicy.IF_NOT_PRESENT
        return self.image_pull_policy

    def _get_network_mode(self) -> Optional[str]:
        # User's value takes precedence; this may collide with the incompatible options
        # mentioned below.
        if self.network_mode:
            if sys.platform != "linux" and self.network_mode == "host":
                warnings.warn(
                    f"{self.network_mode!r} network mode is not supported on platform "
                    f"{sys.platform!r} and may not work as intended."
                )
            return self.network_mode

        # Network mode is not compatible with networks or ports (we do not support ports
        # yet though)
        if self.networks:
            return None

        # Check for a local API connection
        api_url = self.env.get("PREFECT_API_URL", PREFECT_API_URL.value())

        if api_url:
            try:
                _, netloc, _, _, _, _ = urllib.parse.urlparse(api_url)
            except Exception as exc:
                warnings.warn(
                    f"Failed to parse host from API URL {api_url!r} with exception: "
                    f"{exc}\nThe network mode will not be inferred."
                )
                return None

            host = netloc.split(":")[0]

            # If using a locally hosted API, use a host network on linux
            if sys.platform == "linux" and (host == "127.0.0.1" or host == "localhost"):
                return "host"

        # Default to unset
        return None

    def _should_pull_image(self, docker_client: "DockerClient") -> bool:
        """
        Decide whether we need to pull the Docker image.
        """
        image_pull_policy = self._determine_image_pull_policy()

        if image_pull_policy is ImagePullPolicy.ALWAYS:
            return True
        elif image_pull_policy is ImagePullPolicy.NEVER:
            return False
        elif image_pull_policy is ImagePullPolicy.IF_NOT_PRESENT:
            try:
                # NOTE: images.get() wants the tag included with the image
                # name, while images.pull() wants them split.
                docker_client.images.get(self.image)
            except docker.errors.ImageNotFound:
                self.logger.debug(f"Could not find Docker image locally: {self.image}")
                return True
        return False

    def _pull_image(self, docker_client: "DockerClient"):
        """
        Pull the image we're going to use to create the container.
        """
        image, tag = self._get_image_and_tag()

        return docker_client.images.pull(image, tag)

    def _create_container(self, docker_client: "DockerClient", **kwargs) -> "Container":
        """
        Create a docker container with retries on name conflicts.

        If the container already exists with the given name, an incremented index is
        added.
        """
        # Create the container with retries on name conflicts (with an incremented idx)
        index = 0
        container = None
        name = original_name = kwargs.pop("name")

        while not container:
            from docker.errors import APIError

            try:
                display_name = repr(name) if name else "with auto-generated name"
                self.logger.info(f"Creating Docker container {display_name}...")
                container = docker_client.containers.create(name=name, **kwargs)
            except APIError as exc:
                if "Conflict" in str(exc) and "container name" in str(exc):
                    self.logger.info(
                        f"Docker container name {display_name} already exists; "
                        "retrying..."
                    )
                    index += 1
                    name = f"{original_name}-{index}"
                else:
                    raise

        self.logger.info(
            f"Docker container {container.name!r} has status {container.status!r}"
        )
        return container

    def _watch_container_safe(self, container: "Container") -> "Container":
        # Monitor the container capturing the latest snapshot while capturing
        # not found errors
        docker_client = self._get_client()

        try:
            for latest_container in self._watch_container(docker_client, container.id):
                container = latest_container
        except docker.errors.NotFound:
            # The container was removed during watching
            self.logger.warning(
                f"Docker container {container.name} was removed before we could wait "
                "for its completion."
            )
        finally:
            docker_client.close()

        return container

    def _watch_container(
        self, docker_client: "DockerClient", container_id: str
    ) -> Generator[None, None, "Container"]:
        container: "Container" = docker_client.containers.get(container_id)

        status = container.status
        self.logger.info(
            f"Docker container {container.name!r} has status {container.status!r}"
        )
        yield container

        if self.stream_output:
            try:
                for log in container.logs(stream=True):
                    log: bytes
                    print(log.decode().rstrip())
            except docker.errors.APIError as exc:
                if "marked for removal" in str(exc):
                    self.logger.warning(
                        f"Docker container {container.name} was marked for removal"
                        " before logs could be retrieved. Output will not be"
                        " streamed. "
                    )
                else:
                    self.logger.exception(
                        "An unexpected Docker API error occurred while streaming"
                        f" output from container {container.name}."
                    )

            container.reload()
            if container.status != status:
                self.logger.info(
                    f"Docker container {container.name!r} has status"
                    f" {container.status!r}"
                )
            yield container

        container.wait()
        self.logger.info(
            f"Docker container {container.name!r} has status {container.status!r}"
        )
        yield container

    def _get_client(self):
        try:
            with warnings.catch_warnings():
                # Silence warnings due to use of deprecated methods within dockerpy
                # See https://github.com/docker/docker-py/pull/2931
                warnings.filterwarnings(
                    "ignore",
                    message="distutils Version classes are deprecated.*",
                    category=DeprecationWarning,
                )

                docker_client = docker.from_env()

        except docker.errors.DockerException as exc:
            raise RuntimeError("Could not connect to Docker.") from exc

        return docker_client

    def _get_container_name(self) -> Optional[str]:
        """
        Generates a container name to match the configured name, ensuring it is Docker
        compatible.
        """
        # Must match `/?[a-zA-Z0-9][a-zA-Z0-9_.-]+` in the end
        if not self.name:
            return None

        return (
            slugify(
                self.name,
                lowercase=False,
                # Docker does not limit length but URL limits apply eventually so
                # limit the length for safety
                max_length=250,
                # Docker allows these characters for container names
                regex_pattern=r"[^a-zA-Z0-9_.-]+",
            ).lstrip(
                # Docker does not allow leading underscore, dash, or period
                "_-."
            )
            # Docker does not allow 0 character names so cast to null if the name is
            # empty after slufification
            or None
        )

    def _get_extra_hosts(self, docker_client) -> Dict[str, str]:
        """
        A host.docker.internal -> host-gateway mapping is necessary for communicating
        with the API on Linux machines. Docker Desktop on macOS will automatically
        already have this mapping.
        """
        if sys.platform == "linux" and (
            # Do not warn if the user has specified a host manually that does not use
            # a local address
            "PREFECT_API_URL" not in self.env
            or re.search(
                ".*(localhost)|(127.0.0.1)|(host.docker.internal).*",
                self.env["PREFECT_API_URL"],
            )
        ):
            user_version = packaging.version.parse(
                format_outlier_version_name(docker_client.version()["Version"])
            )
            required_version = packaging.version.parse("20.10.0")

            if user_version < required_version:
                warnings.warn(
                    "`host.docker.internal` could not be automatically resolved to"
                    " your local ip address. This feature is not supported on Docker"
                    f" Engine v{user_version}, upgrade to v{required_version}+ if you"
                    " encounter issues."
                )
                return {}
            else:
                # Compatibility for linux -- https://github.com/docker/cli/issues/2290
                # Only supported by Docker v20.10.0+ which is our minimum recommend version
                return {"host.docker.internal": "host-gateway"}

    def _get_environment_variables(self, network_mode):
        # If the API URL has been set by the base environment rather than the by the
        # user, update the value to ensure connectivity when using a bridge network by
        # updating local connections to use the docker internal host unless the
        # network mode is "host" where localhost is available already.
        env = {**self._base_environment(), **self.env}

        if (
            "PREFECT_API_URL" in env
            and "PREFECT_API_URL" not in self.env
            and network_mode != "host"
        ):
            env["PREFECT_API_URL"] = (
                env["PREFECT_API_URL"]
                .replace("localhost", "host.docker.internal")
                .replace("127.0.0.1", "host.docker.internal")
            )

        # Drop null values allowing users to "unset" variables
        return {key: value for key, value in env.items() if value is not None}

DockerContainerResult

Bases: InfrastructureResult

Contains information about a completed Docker container

Source code in prefect/infrastructure/container.py
192
193
class DockerContainerResult(InfrastructureResult):
    """Contains information about a completed Docker container"""

Infrastructure

Bases: Block, ABC

Source code in prefect/infrastructure/base.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
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
@deprecated_class(
    start_date="Mar 2024",
    help="Use the `BaseWorker` class to create custom infrastructure integrations instead."
    " Refer to the upgrade guide for more information:"
    " https://docs.prefect.io/latest/guides/upgrade-guide-agents-to-workers/.",
)
class Infrastructure(Block, abc.ABC):
    _block_schema_capabilities = ["run-infrastructure"]

    type: str

    env: Dict[str, Optional[str]] = pydantic.Field(
        default_factory=dict,
        title="Environment",
        description="Environment variables to set in the configured infrastructure.",
    )
    labels: Dict[str, str] = pydantic.Field(
        default_factory=dict,
        description="Labels applied to the infrastructure for metadata purposes.",
    )
    name: Optional[str] = pydantic.Field(
        default=None,
        description="Name applied to the infrastructure for identification.",
    )
    command: Optional[List[str]] = pydantic.Field(
        default=None,
        description="The command to run in the infrastructure.",
    )

    async def generate_work_pool_base_job_template(self):
        if self._block_document_id is None:
            raise BlockNotSavedError(
                "Cannot publish as work pool, block has not been saved. Please call"
                " `.save()` on your block before publishing."
            )

        block_schema = self.__class__.schema()
        return {
            "job_configuration": {"block": "{{ block }}"},
            "variables": {
                "type": "object",
                "properties": {
                    "block": {
                        "title": "Block",
                        "description": (
                            "The infrastructure block to use for job creation."
                        ),
                        "allOf": [{"$ref": f"#/definitions/{self.__class__.__name__}"}],
                        "default": {
                            "$ref": {"block_document_id": str(self._block_document_id)}
                        },
                    }
                },
                "required": ["block"],
                "definitions": {self.__class__.__name__: block_schema},
            },
        }

    def get_corresponding_worker_type(self):
        return "block"

    @sync_compatible
    async def publish_as_work_pool(self, work_pool_name: Optional[str] = None):
        """
        Creates a work pool configured to use the given block as the job creator.

        Used to migrate from a agents setup to a worker setup.

        Args:
            work_pool_name: The name to give to the created work pool. If not provided, the name of the current
                block will be used.
        """

        base_job_template = await self.generate_work_pool_base_job_template()
        work_pool_name = work_pool_name or self._block_document_name

        if work_pool_name is None:
            raise ValueError(
                "`work_pool_name` must be provided if the block has not been saved."
            )

        console = Console()

        try:
            async with prefect.get_client() as client:
                work_pool = await client.create_work_pool(
                    work_pool=WorkPoolCreate(
                        name=work_pool_name,
                        type=self.get_corresponding_worker_type(),
                        base_job_template=base_job_template,
                    )
                )
        except ObjectAlreadyExists:
            console.print(
                (
                    f"Work pool with name {work_pool_name!r} already exists, please use"
                    " a different name."
                ),
                style="red",
            )
            return

        console.print(
            f"Work pool {work_pool.name} created!",
            style="green",
        )
        if PREFECT_UI_URL:
            console.print(
                "You see your new work pool in the UI at"
                f" {PREFECT_UI_URL.value()}/work-pools/work-pool/{work_pool.name}"
            )

        deploy_script = (
            "my_flow.deploy(work_pool_name='{work_pool.name}', image='my_image:tag')"
        )
        if not hasattr(self, "image"):
            deploy_script = (
                "my_flow.from_source(source='https://github.com/org/repo.git',"
                f" entrypoint='flow.py:my_flow').deploy(work_pool_name='{work_pool.name}')"
            )
        console.print(
            "\nYou can deploy a flow to this work pool by calling"
            f" [blue].deploy[/]:\n\n\t{deploy_script}\n"
        )
        console.print(
            "\nTo start a worker to execute flow runs in this work pool run:\n"
        )
        console.print(f"\t[blue]prefect worker start --pool {work_pool.name}[/]\n")

    @abc.abstractmethod
    async def run(
        self,
        task_status: anyio.abc.TaskStatus = None,
    ) -> InfrastructureResult:
        """
        Run the infrastructure.

        If provided a `task_status`, the status will be reported as started when the
        infrastructure is successfully created. The status return value will be an
        identifier for the infrastructure.

        The call will then monitor the created infrastructure, returning a result at
        the end containing a status code indicating if the infrastructure exited cleanly
        or encountered an error.
        """
        # Note: implementations should include `sync_compatible`

    @abc.abstractmethod
    def preview(self) -> str:
        """
        View a preview of the infrastructure that would be run.
        """

    @property
    def logger(self):
        return get_logger(f"prefect.infrastructure.{self.type}")

    @property
    def is_using_a_runner(self):
        return self.command is not None and "prefect flow-run execute" in shlex.join(
            self.command
        )

    @classmethod
    def _base_environment(cls) -> Dict[str, str]:
        """
        Environment variables that should be passed to all created infrastructure.

        These values should be overridable with the `env` field.
        """
        return get_current_settings().to_environment_variables(exclude_unset=True)

    def prepare_for_flow_run(
        self: Self,
        flow_run: "FlowRun",
        deployment: Optional["Deployment"] = None,
        flow: Optional["Flow"] = None,
    ) -> Self:
        """
        Return an infrastructure block that is prepared to execute a flow run.
        """
        if deployment is not None:
            deployment_labels = self._base_deployment_labels(deployment)
        else:
            deployment_labels = {}

        if flow is not None:
            flow_labels = self._base_flow_labels(flow)
        else:
            flow_labels = {}

        return self.copy(
            update={
                "env": {**self._base_flow_run_environment(flow_run), **self.env},
                "labels": {
                    **self._base_flow_run_labels(flow_run),
                    **deployment_labels,
                    **flow_labels,
                    **self.labels,
                },
                "name": self.name or flow_run.name,
                "command": self.command or self._base_flow_run_command(),
            }
        )

    @staticmethod
    def _base_flow_run_command() -> List[str]:
        """
        Generate a command for a flow run job.
        """
        if experiment_enabled("enhanced_cancellation"):
            if (
                PREFECT_EXPERIMENTAL_WARN
                and PREFECT_EXPERIMENTAL_WARN_ENHANCED_CANCELLATION
            ):
                warnings.warn(
                    EXPERIMENTAL_WARNING.format(
                        feature="Enhanced flow run cancellation",
                        group="enhanced_cancellation",
                        help="",
                    ),
                    ExperimentalFeature,
                    stacklevel=3,
                )
            return ["prefect", "flow-run", "execute"]

        return ["python", "-m", "prefect.engine"]

    @staticmethod
    def _base_flow_run_labels(flow_run: "FlowRun") -> Dict[str, str]:
        """
        Generate a dictionary of labels for a flow run job.
        """
        return {
            "prefect.io/flow-run-id": str(flow_run.id),
            "prefect.io/flow-run-name": flow_run.name,
            "prefect.io/version": prefect.__version__,
        }

    @staticmethod
    def _base_flow_run_environment(flow_run: "FlowRun") -> Dict[str, str]:
        """
        Generate a dictionary of environment variables for a flow run job.
        """
        environment = {}
        environment["PREFECT__FLOW_RUN_ID"] = str(flow_run.id)
        return environment

    @staticmethod
    def _base_deployment_labels(deployment: "Deployment") -> Dict[str, str]:
        labels = {
            "prefect.io/deployment-name": deployment.name,
        }
        if deployment.updated is not None:
            labels["prefect.io/deployment-updated"] = deployment.updated.in_timezone(
                "utc"
            ).to_iso8601_string()
        return labels

    @staticmethod
    def _base_flow_labels(flow: "Flow") -> Dict[str, str]:
        return {
            "prefect.io/flow-name": flow.name,
        }

prepare_for_flow_run

Return an infrastructure block that is prepared to execute a flow run.

Source code in prefect/infrastructure/base.py
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
def prepare_for_flow_run(
    self: Self,
    flow_run: "FlowRun",
    deployment: Optional["Deployment"] = None,
    flow: Optional["Flow"] = None,
) -> Self:
    """
    Return an infrastructure block that is prepared to execute a flow run.
    """
    if deployment is not None:
        deployment_labels = self._base_deployment_labels(deployment)
    else:
        deployment_labels = {}

    if flow is not None:
        flow_labels = self._base_flow_labels(flow)
    else:
        flow_labels = {}

    return self.copy(
        update={
            "env": {**self._base_flow_run_environment(flow_run), **self.env},
            "labels": {
                **self._base_flow_run_labels(flow_run),
                **deployment_labels,
                **flow_labels,
                **self.labels,
            },
            "name": self.name or flow_run.name,
            "command": self.command or self._base_flow_run_command(),
        }
    )

preview abstractmethod

View a preview of the infrastructure that would be run.

Source code in prefect/infrastructure/base.py
207
208
209
210
211
@abc.abstractmethod
def preview(self) -> str:
    """
    View a preview of the infrastructure that would be run.
    """

publish_as_work_pool async

Creates a work pool configured to use the given block as the job creator.

Used to migrate from a agents setup to a worker setup.

Parameters:

Name Type Description Default
work_pool_name Optional[str]

The name to give to the created work pool. If not provided, the name of the current block will be used.

None
Source code in prefect/infrastructure/base.py
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
@sync_compatible
async def publish_as_work_pool(self, work_pool_name: Optional[str] = None):
    """
    Creates a work pool configured to use the given block as the job creator.

    Used to migrate from a agents setup to a worker setup.

    Args:
        work_pool_name: The name to give to the created work pool. If not provided, the name of the current
            block will be used.
    """

    base_job_template = await self.generate_work_pool_base_job_template()
    work_pool_name = work_pool_name or self._block_document_name

    if work_pool_name is None:
        raise ValueError(
            "`work_pool_name` must be provided if the block has not been saved."
        )

    console = Console()

    try:
        async with prefect.get_client() as client:
            work_pool = await client.create_work_pool(
                work_pool=WorkPoolCreate(
                    name=work_pool_name,
                    type=self.get_corresponding_worker_type(),
                    base_job_template=base_job_template,
                )
            )
    except ObjectAlreadyExists:
        console.print(
            (
                f"Work pool with name {work_pool_name!r} already exists, please use"
                " a different name."
            ),
            style="red",
        )
        return

    console.print(
        f"Work pool {work_pool.name} created!",
        style="green",
    )
    if PREFECT_UI_URL:
        console.print(
            "You see your new work pool in the UI at"
            f" {PREFECT_UI_URL.value()}/work-pools/work-pool/{work_pool.name}"
        )

    deploy_script = (
        "my_flow.deploy(work_pool_name='{work_pool.name}', image='my_image:tag')"
    )
    if not hasattr(self, "image"):
        deploy_script = (
            "my_flow.from_source(source='https://github.com/org/repo.git',"
            f" entrypoint='flow.py:my_flow').deploy(work_pool_name='{work_pool.name}')"
        )
    console.print(
        "\nYou can deploy a flow to this work pool by calling"
        f" [blue].deploy[/]:\n\n\t{deploy_script}\n"
    )
    console.print(
        "\nTo start a worker to execute flow runs in this work pool run:\n"
    )
    console.print(f"\t[blue]prefect worker start --pool {work_pool.name}[/]\n")

run abstractmethod async

Run the infrastructure.

If provided a task_status, the status will be reported as started when the infrastructure is successfully created. The status return value will be an identifier for the infrastructure.

The call will then monitor the created infrastructure, returning a result at the end containing a status code indicating if the infrastructure exited cleanly or encountered an error.

Source code in prefect/infrastructure/base.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
@abc.abstractmethod
async def run(
    self,
    task_status: anyio.abc.TaskStatus = None,
) -> InfrastructureResult:
    """
    Run the infrastructure.

    If provided a `task_status`, the status will be reported as started when the
    infrastructure is successfully created. The status return value will be an
    identifier for the infrastructure.

    The call will then monitor the created infrastructure, returning a result at
    the end containing a status code indicating if the infrastructure exited cleanly
    or encountered an error.
    """

KubernetesClusterConfig

Bases: Block

Stores configuration for interaction with Kubernetes clusters.

See from_file for creation.

Attributes:

Name Type Description
config Dict

The entire loaded YAML contents of a kubectl config file

context_name str

The name of the kubectl context to use

Example

Load a saved Kubernetes cluster config:

from prefect.blocks.kubernetes import KubernetesClusterConfig

cluster_config_block = KubernetesClusterConfig.load("BLOCK_NAME")

Source code in prefect/blocks/kubernetes.py
 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
@deprecated_class(
    start_date="Mar 2024",
    help="Use the KubernetesClusterConfig block from prefect-kubernetes instead.",
)
class KubernetesClusterConfig(Block):
    """
    Stores configuration for interaction with Kubernetes clusters.

    See `from_file` for creation.

    Attributes:
        config: The entire loaded YAML contents of a kubectl config file
        context_name: The name of the kubectl context to use

    Example:
        Load a saved Kubernetes cluster config:
        ```python
        from prefect.blocks.kubernetes import KubernetesClusterConfig

        cluster_config_block = KubernetesClusterConfig.load("BLOCK_NAME")
        ```
    """

    _block_type_name = "Kubernetes Cluster Config"
    _logo_url = "https://cdn.sanity.io/images/3ugk85nk/production/2d0b896006ad463b49c28aaac14f31e00e32cfab-250x250.png"
    _documentation_url = "https://docs.prefect.io/api-ref/prefect/blocks/kubernetes/#prefect.blocks.kubernetes.KubernetesClusterConfig"

    config: Dict = Field(
        default=..., description="The entire contents of a kubectl config file."
    )
    context_name: str = Field(
        default=..., description="The name of the kubectl context to use."
    )

    @validator("config", pre=True)
    def parse_yaml_config(cls, value):
        return validate_yaml(value)

    @classmethod
    def from_file(cls: Type[Self], path: Path = None, context_name: str = None) -> Self:
        """
        Create a cluster config from the a Kubernetes config file.

        By default, the current context in the default Kubernetes config file will be
        used.

        An alternative file or context may be specified.

        The entire config file will be loaded and stored.
        """
        kube_config = kubernetes.config.kube_config

        path = Path(path or kube_config.KUBE_CONFIG_DEFAULT_LOCATION)
        path = path.expanduser().resolve()

        # Determine the context
        existing_contexts, current_context = kube_config.list_kube_config_contexts(
            config_file=str(path)
        )
        context_names = {ctx["name"] for ctx in existing_contexts}
        if context_name:
            if context_name not in context_names:
                raise ValueError(
                    f"Context {context_name!r} not found. "
                    f"Specify one of: {listrepr(context_names, sep=', ')}."
                )
        else:
            context_name = current_context["name"]

        # Load the entire config file
        config_file_contents = path.read_text()
        config_dict = yaml.safe_load(config_file_contents)

        return cls(config=config_dict, context_name=context_name)

    def get_api_client(self) -> "ApiClient":
        """
        Returns a Kubernetes API client for this cluster config.
        """
        return kubernetes.config.kube_config.new_client_from_config_dict(
            config_dict=self.config, context=self.context_name
        )

    def configure_client(self) -> None:
        """
        Activates this cluster configuration by loading the configuration into the
        Kubernetes Python client. After calling this, Kubernetes API clients can use
        this config's context.
        """
        kubernetes.config.kube_config.load_kube_config_from_dict(
            config_dict=self.config, context=self.context_name
        )

configure_client

Activates this cluster configuration by loading the configuration into the Kubernetes Python client. After calling this, Kubernetes API clients can use this config's context.

Source code in prefect/blocks/kubernetes.py
111
112
113
114
115
116
117
118
119
def configure_client(self) -> None:
    """
    Activates this cluster configuration by loading the configuration into the
    Kubernetes Python client. After calling this, Kubernetes API clients can use
    this config's context.
    """
    kubernetes.config.kube_config.load_kube_config_from_dict(
        config_dict=self.config, context=self.context_name
    )

from_file classmethod

Create a cluster config from the a Kubernetes config file.

By default, the current context in the default Kubernetes config file will be used.

An alternative file or context may be specified.

The entire config file will be loaded and stored.

Source code in prefect/blocks/kubernetes.py
 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
@classmethod
def from_file(cls: Type[Self], path: Path = None, context_name: str = None) -> Self:
    """
    Create a cluster config from the a Kubernetes config file.

    By default, the current context in the default Kubernetes config file will be
    used.

    An alternative file or context may be specified.

    The entire config file will be loaded and stored.
    """
    kube_config = kubernetes.config.kube_config

    path = Path(path or kube_config.KUBE_CONFIG_DEFAULT_LOCATION)
    path = path.expanduser().resolve()

    # Determine the context
    existing_contexts, current_context = kube_config.list_kube_config_contexts(
        config_file=str(path)
    )
    context_names = {ctx["name"] for ctx in existing_contexts}
    if context_name:
        if context_name not in context_names:
            raise ValueError(
                f"Context {context_name!r} not found. "
                f"Specify one of: {listrepr(context_names, sep=', ')}."
            )
    else:
        context_name = current_context["name"]

    # Load the entire config file
    config_file_contents = path.read_text()
    config_dict = yaml.safe_load(config_file_contents)

    return cls(config=config_dict, context_name=context_name)

get_api_client

Returns a Kubernetes API client for this cluster config.

Source code in prefect/blocks/kubernetes.py
103
104
105
106
107
108
109
def get_api_client(self) -> "ApiClient":
    """
    Returns a Kubernetes API client for this cluster config.
    """
    return kubernetes.config.kube_config.new_client_from_config_dict(
        config_dict=self.config, context=self.context_name
    )

KubernetesJob

Bases: Infrastructure

Runs a command as a Kubernetes Job.

For a guided tutorial, see How to use Kubernetes with Prefect. For more information, including examples for customizing the resulting manifest, see KubernetesJob infrastructure concepts.

Attributes:

Name Type Description
cluster_config Optional[KubernetesClusterConfig]

An optional Kubernetes cluster config to use for this job.

command Optional[KubernetesClusterConfig]

A list of strings specifying the command to run in the container to start the flow run. In most cases you should not override this.

customizations JsonPatch

A list of JSON 6902 patches to apply to the base Job manifest.

env JsonPatch

Environment variables to set for the container.

finished_job_ttl Optional[int]

The number of seconds to retain jobs after completion. If set, finished jobs will be cleaned up by Kubernetes after the given delay. If None (default), jobs will need to be manually removed.

image Optional[str]

An optional string specifying the image reference of a container image to use for the job, for example, docker.io/prefecthq/prefect:2-latest. The behavior is as described in https://kubernetes.io/docs/concepts/containers/images/#image-names. Defaults to the Prefect image.

image_pull_policy Optional[KubernetesImagePullPolicy]

The Kubernetes image pull policy to use for job containers.

job KubernetesManifest

The base manifest for the Kubernetes Job.

job_watch_timeout_seconds Optional[int]

Number of seconds to wait for the job to complete before marking it as crashed. Defaults to None, which means no timeout will be enforced.

labels Optional[int]

An optional dictionary of labels to add to the job.

name Optional[int]

An optional name for the job.

namespace Optional[str]

An optional string signifying the Kubernetes namespace to use.

pod_watch_timeout_seconds int

Number of seconds to watch for pod creation before timing out (default 60).

service_account_name Optional[str]

An optional string specifying which Kubernetes service account to use.

stream_output bool

If set, stream output from the job to local standard output.

Source code in prefect/infrastructure/kubernetes.py
 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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
@deprecated_class(
    start_date="Mar 2024",
    help="Use the Kubernetes worker from prefect-kubernetes instead."
    " Refer to the upgrade guide for more information:"
    " https://docs.prefect.io/latest/guides/upgrade-guide-agents-to-workers/.",
)
class KubernetesJob(Infrastructure):
    """
    Runs a command as a Kubernetes Job.

    For a guided tutorial, see [How to use Kubernetes with Prefect](https://medium.com/the-prefect-blog/how-to-use-kubernetes-with-prefect-419b2e8b8cb2/).
    For more information, including examples for customizing the resulting manifest, see [`KubernetesJob` infrastructure concepts](https://docs.prefect.io/concepts/infrastructure/#kubernetesjob).

    Attributes:
        cluster_config: An optional Kubernetes cluster config to use for this job.
        command: A list of strings specifying the command to run in the container to
            start the flow run. In most cases you should not override this.
        customizations: A list of JSON 6902 patches to apply to the base Job manifest.
        env: Environment variables to set for the container.
        finished_job_ttl: The number of seconds to retain jobs after completion. If set, finished jobs will
            be cleaned up by Kubernetes after the given delay. If None (default), jobs will need to be
            manually removed.
        image: An optional string specifying the image reference of a container image
            to use for the job, for example, docker.io/prefecthq/prefect:2-latest. The
            behavior is as described in https://kubernetes.io/docs/concepts/containers/images/#image-names.
            Defaults to the Prefect image.
        image_pull_policy: The Kubernetes image pull policy to use for job containers.
        job: The base manifest for the Kubernetes Job.
        job_watch_timeout_seconds: Number of seconds to wait for the job to complete
            before marking it as crashed. Defaults to `None`, which means no timeout will be enforced.
        labels: An optional dictionary of labels to add to the job.
        name: An optional name for the job.
        namespace: An optional string signifying the Kubernetes namespace to use.
        pod_watch_timeout_seconds: Number of seconds to watch for pod creation before timing out (default 60).
        service_account_name: An optional string specifying which Kubernetes service account to use.
        stream_output: If set, stream output from the job to local standard output.
    """

    _logo_url = "https://cdn.sanity.io/images/3ugk85nk/production/2d0b896006ad463b49c28aaac14f31e00e32cfab-250x250.png"
    _documentation_url = "https://docs.prefect.io/api-ref/prefect/infrastructure/#prefect.infrastructure.KubernetesJob"

    type: Literal["kubernetes-job"] = Field(
        default="kubernetes-job", description="The type of infrastructure."
    )
    # shortcuts for the most common user-serviceable settings
    image: Optional[str] = Field(
        default=None,
        description=(
            "The image reference of a container image to use for the job, for example,"
            " `docker.io/prefecthq/prefect:2-latest`.The behavior is as described in"
            " the Kubernetes documentation and uses the latest version of Prefect by"
            " default, unless an image is already present in a provided job manifest."
        ),
    )
    namespace: Optional[str] = Field(
        default=None,
        description=(
            "The Kubernetes namespace to use for this job. Defaults to 'default' "
            "unless a namespace is already present in a provided job manifest."
        ),
    )
    service_account_name: Optional[str] = Field(
        default=None, description="The Kubernetes service account to use for this job."
    )
    image_pull_policy: Optional[KubernetesImagePullPolicy] = Field(
        default=None,
        description="The Kubernetes image pull policy to use for job containers.",
    )

    # connection to a cluster
    cluster_config: Optional[KubernetesClusterConfig] = Field(
        default=None, description="The Kubernetes cluster config to use for this job."
    )

    # settings allowing full customization of the Job
    job: KubernetesManifest = Field(
        default_factory=lambda: KubernetesJob.base_job_manifest(),
        description="The base manifest for the Kubernetes Job.",
        title="Base Job Manifest",
    )
    customizations: JsonPatch = Field(
        default_factory=lambda: JsonPatch([]),
        description="A list of JSON 6902 patches to apply to the base Job manifest.",
    )

    # controls the behavior of execution
    job_watch_timeout_seconds: Optional[int] = Field(
        default=None,
        description=(
            "Number of seconds to wait for the job to complete before marking it as"
            " crashed. Defaults to `None`, which means no timeout will be enforced."
        ),
    )
    pod_watch_timeout_seconds: int = Field(
        default=60,
        description="Number of seconds to watch for pod creation before timing out.",
    )
    stream_output: bool = Field(
        default=True,
        description=(
            "If set, output will be streamed from the job to local standard output."
        ),
    )
    finished_job_ttl: Optional[int] = Field(
        default=None,
        description=(
            "The number of seconds to retain jobs after completion. If set, finished"
            " jobs will be cleaned up by Kubernetes after the given delay. If None"
            " (default), jobs will need to be manually removed."
        ),
    )

    # internal-use only right now
    _api_dns_name: Optional[str] = None  # Replaces 'localhost' in API URL

    _block_type_name = "Kubernetes Job"

    @validator("job")
    def ensure_job_includes_all_required_components(cls, value: KubernetesManifest):
        return validate_k8s_job_required_components(cls, value)

    @validator("job")
    def ensure_job_has_compatible_values(cls, value: KubernetesManifest):
        return validate_k8s_job_compatible_values(cls, value)

    @validator("customizations", pre=True)
    def cast_customizations_to_a_json_patch(
        cls, value: Union[List[Dict], JsonPatch, str]
    ) -> JsonPatch:
        return cast_k8s_job_customizations(cls, value)

    @root_validator
    def default_namespace(cls, values):
        return set_default_namespace(values)

    @root_validator
    def default_image(cls, values):
        return set_default_image(values)

    # Support serialization of the 'JsonPatch' type
    class Config:
        arbitrary_types_allowed = True
        json_encoders = {JsonPatch: lambda p: p.patch}

    def dict(self, *args, **kwargs) -> Dict:
        d = super().dict(*args, **kwargs)
        d["customizations"] = self.customizations.patch
        return d

    @classmethod
    def base_job_manifest(cls) -> KubernetesManifest:
        """Produces the bare minimum allowed Job manifest"""
        return {
            "apiVersion": "batch/v1",
            "kind": "Job",
            "metadata": {"labels": {}},
            "spec": {
                "template": {
                    "spec": {
                        "parallelism": 1,
                        "completions": 1,
                        "restartPolicy": "Never",
                        "containers": [
                            {
                                "name": "prefect-job",
                                "env": [],
                            }
                        ],
                    }
                }
            },
        }

    # Note that we're using the yaml package to load both YAML and JSON files below.
    # This works because YAML is a strict superset of JSON:
    #
    #   > The YAML 1.23 specification was published in 2009. Its primary focus was
    #   > making YAML a strict superset of JSON. It also removed many of the problematic
    #   > implicit typing recommendations.
    #
    #   https://yaml.org/spec/1.2.2/#12-yaml-history

    @classmethod
    def job_from_file(cls, filename: str) -> KubernetesManifest:
        """Load a Kubernetes Job manifest from a YAML or JSON file."""
        with open(filename, "r", encoding="utf-8") as f:
            return yaml.load(f, yaml.SafeLoader)

    @classmethod
    def customize_from_file(cls, filename: str) -> JsonPatch:
        """Load an RFC 6902 JSON patch from a YAML or JSON file."""
        with open(filename, "r", encoding="utf-8") as f:
            return JsonPatch(yaml.load(f, yaml.SafeLoader))

    @sync_compatible
    async def run(
        self,
        task_status: Optional[anyio.abc.TaskStatus] = None,
    ) -> KubernetesJobResult:
        if not self.command:
            raise ValueError("Kubernetes job cannot be run with empty command.")

        self._configure_kubernetes_library_client()
        manifest = self.build_job()
        job = await run_sync_in_worker_thread(self._create_job, manifest)

        pid = await run_sync_in_worker_thread(self._get_infrastructure_pid, job)
        # Indicate that the job has started
        if task_status is not None:
            task_status.started(pid)

        # Monitor the job until completion
        status_code = await run_sync_in_worker_thread(
            self._watch_job, job.metadata.name
        )
        return KubernetesJobResult(identifier=pid, status_code=status_code)

    async def kill(self, infrastructure_pid: str, grace_seconds: int = 30):
        self._configure_kubernetes_library_client()
        job_cluster_uid, job_namespace, job_name = self._parse_infrastructure_pid(
            infrastructure_pid
        )

        if not job_namespace == self.namespace:
            raise InfrastructureNotAvailable(
                f"Unable to kill job {job_name!r}: The job is running in namespace "
                f"{job_namespace!r} but this block is configured to use "
                f"{self.namespace!r}."
            )

        current_cluster_uid = self._get_cluster_uid()
        if job_cluster_uid != current_cluster_uid:
            raise InfrastructureNotAvailable(
                f"Unable to kill job {job_name!r}: The job is running on another "
                "cluster."
            )

        with self.get_batch_client() as batch_client:
            try:
                batch_client.delete_namespaced_job(
                    name=job_name,
                    namespace=job_namespace,
                    grace_period_seconds=grace_seconds,
                    # Foreground propagation deletes dependent objects before deleting owner objects.
                    # This ensures that the pods are cleaned up before the job is marked as deleted.
                    # See: https://kubernetes.io/docs/concepts/architecture/garbage-collection/#foreground-deletion
                    propagation_policy="Foreground",
                )
            except kubernetes.client.exceptions.ApiException as exc:
                if exc.status == 404:
                    raise InfrastructureNotFound(
                        f"Unable to kill job {job_name!r}: The job was not found."
                    ) from exc
                else:
                    raise

    def preview(self):
        return yaml.dump(self.build_job())

    def get_corresponding_worker_type(self):
        return "kubernetes"

    async def generate_work_pool_base_job_template(self):
        from prefect.workers.utilities import (
            get_default_base_job_template_for_infrastructure_type,
        )

        base_job_template = await get_default_base_job_template_for_infrastructure_type(
            self.get_corresponding_worker_type()
        )
        assert (
            base_job_template is not None
        ), "Failed to retrieve default base job template."
        for key, value in self.dict(exclude_unset=True, exclude_defaults=True).items():
            if key == "command":
                base_job_template["variables"]["properties"]["command"][
                    "default"
                ] = shlex.join(value)
            elif key in [
                "type",
                "block_type_slug",
                "_block_document_id",
                "_block_document_name",
                "_is_anonymous",
                "job",
                "customizations",
            ]:
                continue
            elif key == "image_pull_policy":
                base_job_template["variables"]["properties"]["image_pull_policy"][
                    "default"
                ] = value.value
            elif key == "cluster_config":
                base_job_template["variables"]["properties"]["cluster_config"][
                    "default"
                ] = {
                    "$ref": {
                        "block_document_id": str(self.cluster_config._block_document_id)
                    }
                }
            elif key in base_job_template["variables"]["properties"]:
                base_job_template["variables"]["properties"][key]["default"] = value
            else:
                self.logger.warning(
                    f"Variable {key!r} is not supported by Kubernetes work pools."
                    " Skipping."
                )

        custom_job_manifest = self.dict(exclude_unset=True, exclude_defaults=True).get(
            "job"
        )
        if custom_job_manifest:
            job_manifest = self.build_job()
        else:
            job_manifest = copy.deepcopy(
                base_job_template["job_configuration"]["job_manifest"]
            )
            job_manifest = self.customizations.apply(job_manifest)
        base_job_template["job_configuration"]["job_manifest"] = job_manifest

        return base_job_template

    def build_job(self) -> KubernetesManifest:
        """Builds the Kubernetes Job Manifest"""
        job_manifest = copy.copy(self.job)
        job_manifest = self._shortcut_customizations().apply(job_manifest)
        job_manifest = self.customizations.apply(job_manifest)
        return job_manifest

    @contextmanager
    def get_batch_client(self) -> Generator["BatchV1Api", None, None]:
        with kubernetes.client.ApiClient() as client:
            try:
                yield kubernetes.client.BatchV1Api(api_client=client)
            finally:
                client.rest_client.pool_manager.clear()

    @contextmanager
    def get_client(self) -> Generator["CoreV1Api", None, None]:
        with kubernetes.client.ApiClient() as client:
            try:
                yield kubernetes.client.CoreV1Api(api_client=client)
            finally:
                client.rest_client.pool_manager.clear()

    def _get_infrastructure_pid(self, job: "V1Job") -> str:
        """
        Generates a Kubernetes infrastructure PID.

        The PID is in the format: "<cluster uid>:<namespace>:<job name>".
        """
        cluster_uid = self._get_cluster_uid()
        pid = f"{cluster_uid}:{self.namespace}:{job.metadata.name}"
        return pid

    def _parse_infrastructure_pid(
        self, infrastructure_pid: str
    ) -> Tuple[str, str, str]:
        """
        Parse a Kubernetes infrastructure PID into its component parts.

        Returns a cluster UID, namespace, and job name.
        """
        cluster_uid, namespace, job_name = infrastructure_pid.split(":", 2)
        return cluster_uid, namespace, job_name

    def _get_cluster_uid(self) -> str:
        """
        Gets a unique id for the current cluster being used.

        There is no real unique identifier for a cluster. However, the `kube-system`
        namespace is immutable and has a persistence UID that we use instead.

        PREFECT_KUBERNETES_CLUSTER_UID can be set in cases where the `kube-system`
        namespace cannot be read e.g. when a cluster role cannot be created. If set,
        this variable will be used and we will not attempt to read the `kube-system`
        namespace.

        See https://github.com/kubernetes/kubernetes/issues/44954
        """
        # Default to an environment variable
        env_cluster_uid = os.environ.get("PREFECT_KUBERNETES_CLUSTER_UID")
        if env_cluster_uid:
            return env_cluster_uid

        # Read the UID from the cluster namespace
        with self.get_client() as client:
            namespace = client.read_namespace("kube-system")
        cluster_uid = namespace.metadata.uid

        return cluster_uid

    def _configure_kubernetes_library_client(self) -> None:
        """
        Set the correct kubernetes client configuration.

        WARNING: This action is not threadsafe and may override the configuration
                  specified by another `KubernetesJob` instance.
        """
        # TODO: Investigate returning a configured client so calls on other threads
        #       will not invalidate the config needed here

        # if a k8s cluster block is provided to the flow runner, use that
        if self.cluster_config:
            self.cluster_config.configure_client()
        else:
            # If no block specified, try to load Kubernetes configuration within a cluster. If that doesn't
            # work, try to load the configuration from the local environment, allowing
            # any further ConfigExceptions to bubble up.
            try:
                kubernetes.config.load_incluster_config()
            except kubernetes.config.ConfigException:
                kubernetes.config.load_kube_config()

    def _shortcut_customizations(self) -> JsonPatch:
        """Produces the JSON 6902 patch for the most commonly used customizations, like
        image and namespace, which we offer as top-level parameters (with sensible
        default values)"""
        shortcuts = []

        if self.namespace:
            shortcuts.append(
                {
                    "op": "add",
                    "path": "/metadata/namespace",
                    "value": self.namespace,
                }
            )

        if self.image:
            shortcuts.append(
                {
                    "op": "add",
                    "path": "/spec/template/spec/containers/0/image",
                    "value": self.image,
                }
            )

        shortcuts += [
            {
                "op": "add",
                "path": (
                    f"/metadata/labels/{self._slugify_label_key(key).replace('/', '~1', 1)}"
                ),
                "value": self._slugify_label_value(value),
            }
            for key, value in self.labels.items()
        ]

        shortcuts += [
            {
                "op": "add",
                "path": "/spec/template/spec/containers/0/env/-",
                "value": {"name": key, "value": value},
            }
            for key, value in self._get_environment_variables().items()
        ]

        if self.image_pull_policy:
            shortcuts.append(
                {
                    "op": "add",
                    "path": "/spec/template/spec/containers/0/imagePullPolicy",
                    "value": self.image_pull_policy.value,
                }
            )

        if self.service_account_name:
            shortcuts.append(
                {
                    "op": "add",
                    "path": "/spec/template/spec/serviceAccountName",
                    "value": self.service_account_name,
                }
            )

        if self.finished_job_ttl is not None:
            shortcuts.append(
                {
                    "op": "add",
                    "path": "/spec/ttlSecondsAfterFinished",
                    "value": self.finished_job_ttl,
                }
            )

        if self.command:
            shortcuts.append(
                {
                    "op": "add",
                    "path": "/spec/template/spec/containers/0/args",
                    "value": self.command,
                }
            )

        if self.name:
            shortcuts.append(
                {
                    "op": "add",
                    "path": "/metadata/generateName",
                    "value": self._slugify_name(self.name) + "-",
                }
            )
        else:
            # Generate name is required
            shortcuts.append(
                {
                    "op": "add",
                    "path": "/metadata/generateName",
                    "value": (
                        "prefect-job-"
                        # We generate a name using a hash of the primary job settings
                        + stable_hash(
                            *self.command if self.command else "",
                            *self.env.keys(),
                            *[v for v in self.env.values() if v is not None],
                        )
                        + "-"
                    ),
                }
            )

        return JsonPatch(shortcuts)

    def _get_job(self, job_id: str) -> Optional["V1Job"]:
        with self.get_batch_client() as batch_client:
            try:
                job = batch_client.read_namespaced_job(job_id, self.namespace)
            except kubernetes.client.exceptions.ApiException:
                self.logger.error(f"Job {job_id!r} was removed.", exc_info=True)
                return None
            return job

    def _get_job_pod(self, job_name: str) -> "V1Pod":
        """Get the first running pod for a job."""

        # Wait until we find a running pod for the job
        # if `pod_watch_timeout_seconds` is None, no timeout will be enforced
        watch = kubernetes.watch.Watch()
        self.logger.debug(f"Job {job_name!r}: Starting watch for pod start...")
        last_phase = None
        with self.get_client() as client:
            for event in watch.stream(
                func=client.list_namespaced_pod,
                namespace=self.namespace,
                label_selector=f"job-name={job_name}",
                timeout_seconds=self.pod_watch_timeout_seconds,
            ):
                phase = event["object"].status.phase
                if phase != last_phase:
                    self.logger.info(f"Job {job_name!r}: Pod has status {phase!r}.")

                if phase != "Pending":
                    watch.stop()
                    return event["object"]

                last_phase = phase

        self.logger.error(f"Job {job_name!r}: Pod never started.")

    def _watch_job(self, job_name: str) -> int:
        """
        Watch a job.

        Return the final status code of the first container.
        """
        self.logger.debug(f"Job {job_name!r}: Monitoring job...")

        job = self._get_job(job_name)
        if not job:
            return -1

        pod = self._get_job_pod(job_name)
        if not pod:
            return -1

        # Calculate the deadline before streaming output
        deadline = (
            (time.monotonic() + self.job_watch_timeout_seconds)
            if self.job_watch_timeout_seconds is not None
            else None
        )

        if self.stream_output:
            with self.get_client() as client:
                logs = client.read_namespaced_pod_log(
                    pod.metadata.name,
                    self.namespace,
                    follow=True,
                    _preload_content=False,
                    container="prefect-job",
                )
                try:
                    for log in logs.stream():
                        print(log.decode().rstrip())

                        # Check if we have passed the deadline and should stop streaming
                        # logs
                        remaining_time = (
                            deadline - time.monotonic() if deadline else None
                        )
                        if deadline and remaining_time <= 0:
                            break

                except Exception:
                    self.logger.warning(
                        (
                            "Error occurred while streaming logs - "
                            "Job will continue to run but logs will "
                            "no longer be streamed to stdout."
                        ),
                        exc_info=True,
                    )

        with self.get_batch_client() as batch_client:
            # Check if the job is completed before beginning a watch
            job = batch_client.read_namespaced_job(
                name=job_name, namespace=self.namespace
            )
            completed = job.status.completion_time is not None

            while not completed:
                remaining_time = (
                    math.ceil(deadline - time.monotonic()) if deadline else None
                )
                if deadline and remaining_time <= 0:
                    self.logger.error(
                        f"Job {job_name!r}: Job did not complete within "
                        f"timeout of {self.job_watch_timeout_seconds}s."
                    )
                    return -1

                watch = kubernetes.watch.Watch()
                # The kubernetes library will disable retries if the timeout kwarg is
                # present regardless of the value so we do not pass it unless given
                # https://github.com/kubernetes-client/python/blob/84f5fea2a3e4b161917aa597bf5e5a1d95e24f5a/kubernetes/base/watch/watch.py#LL160
                timeout_seconds = (
                    {"timeout_seconds": remaining_time} if deadline else {}
                )

                for event in watch.stream(
                    func=batch_client.list_namespaced_job,
                    field_selector=f"metadata.name={job_name}",
                    namespace=self.namespace,
                    **timeout_seconds,
                ):
                    if event["type"] == "DELETED":
                        self.logger.error(f"Job {job_name!r}: Job has been deleted.")
                        completed = True
                    elif event["object"].status.completion_time:
                        if not event["object"].status.succeeded:
                            # Job failed, exit while loop and return pod exit code
                            self.logger.error(f"Job {job_name!r}: Job failed.")
                        completed = True
                    # Check if the job has reached its backoff limit
                    # and stop watching if it has
                    elif (
                        event["object"].spec.backoff_limit is not None
                        and event["object"].status.failed is not None
                        and event["object"].status.failed
                        > event["object"].spec.backoff_limit
                    ):
                        self.logger.error(
                            f"Job {job_name!r}: Job reached backoff limit."
                        )
                        completed = True
                    # If the job has no backoff limit, check if it has failed
                    # and stop watching if it has
                    elif (
                        not event["object"].spec.backoff_limit
                        and event["object"].status.failed
                    ):
                        completed = True

                    if completed:
                        watch.stop()
                        break

        with self.get_client() as core_client:
            # Get all pods for the job
            pods = core_client.list_namespaced_pod(
                namespace=self.namespace, label_selector=f"job-name={job_name}"
            )
            # Get the status for only the most recently used pod
            pods.items.sort(
                key=lambda pod: pod.metadata.creation_timestamp, reverse=True
            )
            most_recent_pod = pods.items[0] if pods.items else None
            first_container_status = (
                most_recent_pod.status.container_statuses[0]
                if most_recent_pod
                else None
            )
            if not first_container_status:
                self.logger.error(f"Job {job_name!r}: No pods found for job.")
                return -1

            # In some cases, such as spot instance evictions, the pod will be forcibly
            # terminated and not report a status correctly.
            elif (
                first_container_status.state is None
                or first_container_status.state.terminated is None
                or first_container_status.state.terminated.exit_code is None
            ):
                self.logger.error(
                    f"Could not determine exit code for {job_name!r}."
                    "Exit code will be reported as -1."
                    "First container status info did not report an exit code."
                    f"First container info: {first_container_status}."
                )
                return -1

        return first_container_status.state.terminated.exit_code

    def _create_job(self, job_manifest: KubernetesManifest) -> "V1Job":
        """
        Given a Kubernetes Job Manifest, create the Job on the configured Kubernetes
        cluster and return its name.
        """
        with self.get_batch_client() as batch_client:
            job = batch_client.create_namespaced_job(self.namespace, job_manifest)
        return job

    def _slugify_name(self, name: str) -> str:
        """
        Slugify text for use as a name.

        Keeps only alphanumeric characters and dashes, and caps the length
        of the slug at 45 chars.

        The 45 character length allows room for the k8s utility
        "generateName" to generate a unique name from the slug while
        keeping the total length of a name below 63 characters, which is
        the limit for e.g. label names that follow RFC 1123 (hostnames) and
        RFC 1035 (domain names).

        Args:
            name: The name of the job

        Returns:
            the slugified job name
        """
        slug = slugify(
            name,
            max_length=45,  # Leave enough space for generateName
            regex_pattern=r"[^a-zA-Z0-9-]+",
        )

        # TODO: Handle the case that the name is an empty string after being
        # slugified.

        return slug

    def _slugify_label_key(self, key: str) -> str:
        """
        Slugify text for use as a label key.

        Keys are composed of an optional prefix and name, separated by a slash (/).

        Keeps only alphanumeric characters, dashes, underscores, and periods.
        Limits the length of the label prefix to 253 characters.
        Limits the length of the label name to 63 characters.

        See https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character-set

        Args:
            key: The label key

        Returns:
            The slugified label key
        """
        if "/" in key:
            prefix, name = key.split("/", maxsplit=1)
        else:
            prefix = None
            name = key

        name_slug = (
            slugify(name, max_length=63, regex_pattern=r"[^a-zA-Z0-9-_.]+").strip(
                "_-."  # Must start or end with alphanumeric characters
            )
            or name
        )
        # Fallback to the original if we end up with an empty slug, this will allow
        # Kubernetes to throw the validation error

        if prefix:
            prefix_slug = (
                slugify(
                    prefix,
                    max_length=253,
                    regex_pattern=r"[^a-zA-Z0-9-\.]+",
                ).strip("_-.")  # Must start or end with alphanumeric characters
                or prefix
            )

            return f"{prefix_slug}/{name_slug}"

        return name_slug

    def _slugify_label_value(self, value: str) -> str:
        """
        Slugify text for use as a label value.

        Keeps only alphanumeric characters, dashes, underscores, and periods.
        Limits the total length of label text to below 63 characters.

        See https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character-set

        Args:
            value: The text for the label

        Returns:
            The slugified value
        """
        slug = (
            slugify(value, max_length=63, regex_pattern=r"[^a-zA-Z0-9-_\.]+").strip(
                "_-."  # Must start or end with alphanumeric characters
            )
            or value
        )
        # Fallback to the original if we end up with an empty slug, this will allow
        # Kubernetes to throw the validation error

        return slug

    def _get_environment_variables(self):
        # If the API URL has been set by the base environment rather than the by the
        # user, update the value to ensure connectivity when using a bridge network by
        # updating local connections to use the internal host
        env = {**self._base_environment(), **self.env}

        if (
            "PREFECT_API_URL" in env
            and "PREFECT_API_URL" not in self.env
            and self._api_dns_name
        ):
            env["PREFECT_API_URL"] = (
                env["PREFECT_API_URL"]
                .replace("localhost", self._api_dns_name)
                .replace("127.0.0.1", self._api_dns_name)
            )

        # Drop null values allowing users to "unset" variables
        return {key: value for key, value in env.items() if value is not None}

base_job_manifest classmethod

Produces the bare minimum allowed Job manifest

Source code in prefect/infrastructure/kubernetes.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
@classmethod
def base_job_manifest(cls) -> KubernetesManifest:
    """Produces the bare minimum allowed Job manifest"""
    return {
        "apiVersion": "batch/v1",
        "kind": "Job",
        "metadata": {"labels": {}},
        "spec": {
            "template": {
                "spec": {
                    "parallelism": 1,
                    "completions": 1,
                    "restartPolicy": "Never",
                    "containers": [
                        {
                            "name": "prefect-job",
                            "env": [],
                        }
                    ],
                }
            }
        },
    }

build_job

Builds the Kubernetes Job Manifest

Source code in prefect/infrastructure/kubernetes.py
399
400
401
402
403
404
def build_job(self) -> KubernetesManifest:
    """Builds the Kubernetes Job Manifest"""
    job_manifest = copy.copy(self.job)
    job_manifest = self._shortcut_customizations().apply(job_manifest)
    job_manifest = self.customizations.apply(job_manifest)
    return job_manifest

customize_from_file classmethod

Load an RFC 6902 JSON patch from a YAML or JSON file.

Source code in prefect/infrastructure/kubernetes.py
265
266
267
268
269
@classmethod
def customize_from_file(cls, filename: str) -> JsonPatch:
    """Load an RFC 6902 JSON patch from a YAML or JSON file."""
    with open(filename, "r", encoding="utf-8") as f:
        return JsonPatch(yaml.load(f, yaml.SafeLoader))

job_from_file classmethod

Load a Kubernetes Job manifest from a YAML or JSON file.

Source code in prefect/infrastructure/kubernetes.py
259
260
261
262
263
@classmethod
def job_from_file(cls, filename: str) -> KubernetesManifest:
    """Load a Kubernetes Job manifest from a YAML or JSON file."""
    with open(filename, "r", encoding="utf-8") as f:
        return yaml.load(f, yaml.SafeLoader)

KubernetesJobResult

Bases: InfrastructureResult

Contains information about the final state of a completed Kubernetes Job

Source code in prefect/infrastructure/kubernetes.py
73
74
class KubernetesJobResult(InfrastructureResult):
    """Contains information about the final state of a completed Kubernetes Job"""

Process

Bases: Infrastructure

Run a command in a new process.

Current environment variables and Prefect settings will be included in the created process. Configured environment variables will override any current environment variables.

Attributes:

Name Type Description
command

A list of strings specifying the command to run in the container to start the flow run. In most cases you should not override this.

env

Environment variables to set for the new process.

labels

Labels for the process. Labels are for metadata purposes only and cannot be attached to the process itself.

name

A name for the process. For display purposes only.

stream_output bool

Whether to stream output to local stdout.

working_dir Union[str, Path, None]

Working directory where the process should be opened. If not set, a tmp directory will be used.

Source code in prefect/infrastructure/process.py
 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
@deprecated_class(
    start_date="Mar 2024",
    help="Use the process worker instead."
    " Refer to the upgrade guide for more information:"
    " https://docs.prefect.io/latest/guides/upgrade-guide-agents-to-workers/.",
)
class Process(Infrastructure):
    """
    Run a command in a new process.

    Current environment variables and Prefect settings will be included in the created
    process. Configured environment variables will override any current environment
    variables.

    Attributes:
        command: A list of strings specifying the command to run in the container to
            start the flow run. In most cases you should not override this.
        env: Environment variables to set for the new process.
        labels: Labels for the process. Labels are for metadata purposes only and
            cannot be attached to the process itself.
        name: A name for the process. For display purposes only.
        stream_output: Whether to stream output to local stdout.
        working_dir: Working directory where the process should be opened. If not set,
            a tmp directory will be used.
    """

    _logo_url = "https://cdn.sanity.io/images/3ugk85nk/production/356e6766a91baf20e1d08bbe16e8b5aaef4d8643-48x48.png"
    _documentation_url = "https://docs.prefect.io/concepts/infrastructure/#process"

    type: Literal["process"] = Field(
        default="process", description="The type of infrastructure."
    )
    stream_output: bool = Field(
        default=True,
        description=(
            "If set, output will be streamed from the process to local standard output."
        ),
    )
    working_dir: Union[str, Path, None] = Field(
        default=None,
        description=(
            "If set, the process will open within the specified path as the working"
            " directory. Otherwise, a temporary directory will be created."
        ),
    )  # Underlying accepted types are str, bytes, PathLike[str], None

    @sync_compatible
    async def run(
        self,
        task_status: anyio.abc.TaskStatus = None,
    ) -> "ProcessResult":
        if not self.command:
            raise ValueError("Process cannot be run with empty command.")

        display_name = f" {self.name!r}" if self.name else ""

        # Open a subprocess to execute the flow run
        self.logger.info(f"Opening process{display_name}...")
        working_dir_ctx = (
            tempfile.TemporaryDirectory(suffix="prefect")
            if not self.working_dir
            else contextlib.nullcontext(self.working_dir)
        )
        with working_dir_ctx as working_dir:
            self.logger.debug(
                f"Process{display_name} running command: {' '.join(self.command)} in"
                f" {working_dir}"
            )

            # We must add creationflags to a dict so it is only passed as a function
            # parameter on Windows, because the presence of creationflags causes
            # errors on Unix even if set to None
            kwargs: Dict[str, object] = {}
            if sys.platform == "win32":
                kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP

            process = await run_process(
                self.command,
                stream_output=self.stream_output,
                task_status=task_status,
                task_status_handler=_infrastructure_pid_from_process,
                env=self._get_environment_variables(),
                cwd=working_dir,
                **kwargs,
            )

        # Use the pid for display if no name was given
        display_name = display_name or f" {process.pid}"

        if process.returncode:
            help_message = None
            if process.returncode == -9:
                help_message = (
                    "This indicates that the process exited due to a SIGKILL signal. "
                    "Typically, this is either caused by manual cancellation or "
                    "high memory usage causing the operating system to "
                    "terminate the process."
                )
            if process.returncode == -15:
                help_message = (
                    "This indicates that the process exited due to a SIGTERM signal. "
                    "Typically, this is caused by manual cancellation."
                )
            elif process.returncode == 247:
                help_message = (
                    "This indicates that the process was terminated due to high "
                    "memory usage."
                )
            elif (
                sys.platform == "win32" and process.returncode == STATUS_CONTROL_C_EXIT
            ):
                help_message = (
                    "Process was terminated due to a Ctrl+C or Ctrl+Break signal. "
                    "Typically, this is caused by manual cancellation."
                )

            self.logger.error(
                f"Process{display_name} exited with status code: {process.returncode}"
                + (f"; {help_message}" if help_message else "")
            )
        else:
            self.logger.info(f"Process{display_name} exited cleanly.")

        return ProcessResult(
            status_code=process.returncode, identifier=str(process.pid)
        )

    async def kill(self, infrastructure_pid: str, grace_seconds: int = 30):
        hostname, pid = _parse_infrastructure_pid(infrastructure_pid)

        if hostname != socket.gethostname():
            raise InfrastructureNotAvailable(
                f"Unable to kill process {pid!r}: The process is running on a different"
                f" host {hostname!r}."
            )

        # In a non-windows environment first send a SIGTERM, then, after
        # `grace_seconds` seconds have passed subsequent send SIGKILL. In
        # Windows we use CTRL_BREAK_EVENT as SIGTERM is useless:
        # https://bugs.python.org/issue26350
        if sys.platform == "win32":
            try:
                os.kill(pid, signal.CTRL_BREAK_EVENT)
            except (ProcessLookupError, WindowsError):
                raise InfrastructureNotFound(
                    f"Unable to kill process {pid!r}: The process was not found."
                )
        else:
            try:
                os.kill(pid, signal.SIGTERM)
            except ProcessLookupError:
                raise InfrastructureNotFound(
                    f"Unable to kill process {pid!r}: The process was not found."
                )

            # Throttle how often we check if the process is still alive to keep
            # from making too many system calls in a short period of time.
            check_interval = max(grace_seconds / 10, 1)

            with anyio.move_on_after(grace_seconds):
                while True:
                    await anyio.sleep(check_interval)

                    # Detect if the process is still alive. If not do an early
                    # return as the process respected the SIGTERM from above.
                    try:
                        os.kill(pid, 0)
                    except ProcessLookupError:
                        return

            try:
                os.kill(pid, signal.SIGKILL)
            except OSError:
                # We shouldn't ever end up here, but it's possible that the
                # process ended right after the check above.
                return

    def preview(self):
        environment = self._get_environment_variables(include_os_environ=False)
        return " \\\n".join(
            [f"{key}={value}" for key, value in environment.items()]
            + [" ".join(self.command)]
        )

    def _get_environment_variables(self, include_os_environ: bool = True):
        os_environ = os.environ if include_os_environ else {}
        # The base environment must override the current environment or
        # the Prefect settings context may not be respected
        env = {**os_environ, **self._base_environment(), **self.env}

        # Drop null values allowing users to "unset" variables
        return {key: value for key, value in env.items() if value is not None}

    def _base_flow_run_command(self):
        return [get_sys_executable(), "-m", "prefect.engine"]

    def get_corresponding_worker_type(self):
        return "process"

    async def generate_work_pool_base_job_template(self):
        from prefect.workers.utilities import (
            get_default_base_job_template_for_infrastructure_type,
        )

        base_job_template = await get_default_base_job_template_for_infrastructure_type(
            self.get_corresponding_worker_type(),
        )
        assert (
            base_job_template is not None
        ), "Failed to generate default base job template for Process worker."
        for key, value in self.dict(exclude_unset=True, exclude_defaults=True).items():
            if key == "command":
                base_job_template["variables"]["properties"]["command"][
                    "default"
                ] = shlex.join(value)
            elif key in [
                "type",
                "block_type_slug",
                "_block_document_id",
                "_block_document_name",
                "_is_anonymous",
            ]:
                continue
            elif key in base_job_template["variables"]["properties"]:
                base_job_template["variables"]["properties"][key]["default"] = value
            else:
                self.logger.warning(
                    f"Variable {key!r} is not supported by Process work pools."
                    " Skipping."
                )

        return base_job_template

ProcessResult

Bases: InfrastructureResult

Contains information about the final state of a completed process

Source code in prefect/infrastructure/process.py
288
289
class ProcessResult(InfrastructureResult):
    """Contains information about the final state of a completed process"""