Compositions in Python

Maturity: preview (the API may change before 1.0).

A composition deploys an app built from several Git repositories. The main path keeps everything Piceli-specific in one repository, the composition repository, in typed Python:

  • the app is a Pipeline (App, sidecars, generated Secrets, RBAC, checks, restore points: everything a single-repository pipeline can declare);

  • its images come from a host build spec whose contexts read the other repositories;

  • a module, usually infra.py, says where the app runs and when it deploys.

The product repositories carry nothing Piceli-specific: a push there only triggers a build and a sync. For simple components, a piceli.toml in each repository is an optional alternative (see Component contracts (piceli.toml)); both kinds of environment can live in one composition.

infra repo (the composition)       api repo        worker repo
├── infra.py      where and when   └── site/ …     └── jobs/ …
├── example_app.py  the Pipeline
├── host-build.toml contexts: infra, api, worker
└── config/ …

The example in examples/python_composition/ is this layout: infra/ is the content of the composition repository, api/ and worker/ of the two product repositories. The tests in tests/unit/infra/test_pipeline_composition.py run its controller against local bare Git remotes.

The composition module

from piceli.envs import Branches, Environment, Stack, Tag
from piceli.infra import Cluster, Controller, Source

name = "example"

cluster = Cluster(
    "my-cluster",
    api="https://127.0.0.1:6443",
    credentials="my-cluster",  # a `piceli login` profile, never in Git
    registry=registry,
    controller=Controller(on=REGISTRY_NODE),
)

infra = Source(
    os.environ.get("EXAMPLE_INFRA_URL", "https://example.com/infra.git"), name="infra"
)
api = Source(
    os.environ.get("EXAMPLE_API_URL", "https://example.com/api.git"), name="api"
)
worker = Source(
    os.environ.get("EXAMPLE_WORKER_URL", "https://example.com/worker.git"),
    name="worker",
)

full = Stack("full", workloads=["api", "worker", "cache"])
small = Stack("small", workloads=["api", "cache"])

environments = [
    Environment(
        "main",
        namespace="example-main",
        pipeline=pipeline,
        stack=full,
        cluster=cluster,
        follow={infra: "main", api: "main", worker: "main"},
        auto_approve=True,
    ),
    Environment(
        "rc",
        namespace="example-rc",
        pipeline=pipeline,
        stack=full,
        cluster=cluster,
        follow={infra: "main", api: Tag("v*"), worker: "main"},
    ),
    Environment.per_branch(
        Branches("wp-*"),
        namespace="example-{branch}",
        pipeline=pipeline,
        stack=small,
        cluster=cluster,
        follow={infra: "main", api: "{branch}", worker: "main"},
        on_nodes=[os.environ.get("EXAMPLE_BRANCH_NODE", "my-cluster-worker2")],
        limit=2,
        idle_stop="24h",
        auto_approve=True,
    ),
]
  • Environment(name, namespace=…, pipeline=PIPELINE, follow={Source: rule}, stack=Stack(name, workloads=[…]), cluster=…, on_nodes=…, quota=…, auto_approve=…): the environment deploys the pipeline’s app. stack names the app’s workloads it runs; checks, rollback_on_failed_checks, restore points and the approval policy are the pipeline’s (auto_approve=True with no pipeline policy uses the default ApprovalPolicy(): creates and updates). A rule is a branch name, Tag("v*"), Promote() or a list of them, as for Component contracts (piceli.toml).

  • Environment.per_branch(Branches("wp-*"), namespace="<prefix>{branch}", pipeline=PIPELINE, follow={source: "{branch}", …}, stack=…, on_nodes=…, limit=…, idle_stop=…, claim_sizes=…, auto_approve=…): one environment per branch, removed with its branch.

  • A pipeline environment never mixes with contract components: a Stack of Components, settings= or secrets= next to pipeline= is refused (env-config-invalid). The pipeline has one target (a pipeline with one target per app environment: pass pipeline.for_environment(NAME)).

  • The cluster’s registry is Registry.in_cluster(...): built images go there, and so do the third-party images of its mirror=[ref@digest] (and of the pipeline’s own delivery mirror=). They are copied when an environment syncs (the whole index, by digest) and the app’s references are rewritten to the copy: nodes never pull from a hosted registry at run time.

Builds: contexts from sources, change-aware per image

The pipeline’s builds are host builds (Build.spec("host-build.toml", builder="host"); a Docker build needs a Docker engine and is refused with component-build-unsupported):

[context.infra]
source = "infra"
include = ["config/**"]

[context.api]
source = "api"
include = ["site/**"]

[context.worker]
source = "worker"
include = ["jobs/**"]

[[output.image]]
name = "api"
repository = "example/api"
contexts = ["api", "infra"]
base = { image = "docker.io/library/busybox:1.37.0", digest = "sha256:bdf57e528e45e4433820e045b29b4597825a1c9e38353532d90a01445013f82e" }
files = { "api/site" = "/srv/site", "infra/config/api.json" = "/srv/site/config.json" }
user = "65534:65534"
entrypoint = ["httpd", "-f", "-p", "8080", "-h", "/srv/site"]

[[output.image]]
name = "worker"
repository = "example/worker"
contexts = ["worker"]
base = { image = "docker.io/library/busybox:1.37.0", digest = "sha256:bdf57e528e45e4433820e045b29b4597825a1c9e38353532d90a01445013f82e" }
files = { "worker/jobs" = "/opt/worker" }
user = "65534:65534"
entrypoint = ["sh", "/opt/worker/run.sh"]
  • [context.X] source = "X" reads the composition’s Source named X at the environment’s revision (its commit of that source). The composition repository is a source too: name it in follow (as the example does) or leave it out and it is read at the commit the controller imported. A context without source reads the composition repository, relative to the spec’s directory. A context of a source the environment does not follow is refused (composition-invalid, at gitops enable and at sync).

  • [[output.image]] contexts = ["api", "infra"] (optional, default every context) lists what an image reads. Each image has a change key: its output table, the spec’s [build] table and the Git blob id of every file its contexts include at their commits. No changed key: nothing is built. Otherwise one build runs (one Job, every source fetched at its commit with the one Git Secret piceli-build-git); only the images whose key changed are assembled, pushed and take the new image (0.68.0: a command declared { run = [...], images = [...] } runs only for them, see Builds without a VM); the others keep their cached digest, render identically and apply as no-op.

  • A derived image (from = "<image>", 0.89.0) has the base image’s key plus the files of its own contexts as its key. A change only it reads (a release decision) builds nothing: the controller appends its files to the recorded base digest (see Derived images (0.89.0)).

  • Build(node_facts=…) declared on the build is used for the build’s platform (page size); otherwise the facts of the controller’s first --platform.

The platforms a build compiles (0.68.0)

A pipeline environment’s build compiles only the platforms its pods can run on, out of those the controller enables (piceli gitops enable --platform):

  1. the nodes of the environment’s on_nodes (names or labels), when set; a DaemonSet ignores on_nodes and counts with its own selector;

  2. else the nodes that every workload’s node selector matches (node_selector= or the app’s pod_defaults), for example {"kubernetes.io/arch": "arm64"} on every workload;

  3. else every declared node (Cluster(nodes=[...])).

  • Only labels Piceli knows a declared node carries count: kubernetes.io/arch, kubernetes.io/hostname (the node’s name), kubernetes.io/os and the role labels (piceli.io/role-<role>). A workload with none of them, an app.override that sets a nodeSelector, or components added with app.add make it every node.

  • With Controller(delivery="nodes") the images go only into those nodes, and only their platforms must be enabled. With a registry delivery an unknown placement keeps every enabled platform (a node the composition does not declare may run the pods).

  • The platforms are part of each image’s change key: an environment whose platforms change rebuilds its images once.

  • An environment on another cluster than the controller’s builds every enabled platform, as before.

Declared platforms are all built (0.74.0)

A spec that declares platforms in [build] builds every declared platform, whatever nodes the pods run on, and pushes each image as one OCI (Open Container Initiative) image index over them:

[build]
platforms = ["linux/amd64", "linux/arm64"]
  • The status records the index digest (digest, with media_type and the per-platform platforms map), and so do the history and piceli gitops builds --json (digests). Nodes pull the index and get their own platform.

  • Every platform’s manifest stays in the registry under the index, so retention keeps it with the index. A release copies that digest to another registry with piceli artifacts copy (Promote a built image by digest: piceli artifacts copy (0.74.0)): build once, promote by digest. --in-cluster runs that copy as a Job next to the registry, so a dropped port-forward cannot fail the release, and --ledger lets a rerun continue where it stopped.

  • A spec without platforms keeps the 0.68.0 rule above. That is the way to build only what the pods run: leave platforms out.

  • A platform the nodes need that the spec does not declare fails the build (node-platform-mismatch), as before.

  • With Controller(delivery="nodes") nothing would keep the other platforms (no registry), so the 0.68.0 rule stays.

  • A declared platform need not be enabled with piceli gitops enable --platform: host builds cross-compile.

Several images from one source

Two images built from different paths of the same repository each get a change key over their own paths only: declare one context per path, each with its own include, both with the same source, and let each image read its own context. A push that changes only jobs/ rebuilds only worker; one that changes only site/ rebuilds only api; a file neither includes (README.md) builds nothing. The build fetches the source once; each context selects its own files from that checkout.

[context.site]
source = "api"
include = ["site/**"]

[context.api_jobs]
source = "api"
include = ["jobs/**"]

[[output.image]]
name = "api"
repository = "example/api"
contexts = ["site"]
files = { "site/site" = "/srv/site" }

[[output.image]]
name = "worker"
repository = "example/worker"
contexts = ["api_jobs"]
files = { "api_jobs/jobs" = "/opt/jobs" }

One context with both paths in its include would give both images the same change key, so a change in either path would rebuild both.

Deploying it

piceli login my-cluster --kubeconfig ~/my-cluster.yaml   # once per machine
piceli cluster init infra.py:cluster                      # registry, nodes, controller
piceli secrets git --cluster infra.py:cluster --prompt    # the one Git Secret
piceli gitops enable infra.py --repo https://git.example.com/team/infra.git \
    --image REPO@sha256:… --builder-image REPO@sha256:… \
    --credentials-secret piceli-build-git                 # plan, then --approve HASH
piceli gitops status
piceli gitops sync main --component worker               # rebuild one image now

gitops enable infra.py (run from a clone of the composition repository, --root, default .) imports the module on your machine, checks every pipeline environment’s builds, and records in the controller’s config:

  • the composition repository: --repo (default: the origin remote of --root), the branch to follow (--main-branch, default main) and the module’s path in it; its source name is that of the Source with the same URL, if any;

  • a summary of every environment, so the install plan hash covers the rules the controller starts with.

The controller follows the composition repository like any source: at each poll it resolves the branch, and when it moved it imports the module at that commit from its own checkout (the helper modules next to it too). Every environment’s revision includes that commit, so a change in the composition repository re-renders every environment; images whose key did not change are not rebuilt. A module that fails to import is recorded (controller.composition_repo.error, composition-invalid, with the exception’s type and message) and the last good one keeps deploying until the branch moves again, also after a restart (0.27.1). A controller of another version tries the failed commit once more: a newer Piceli may import what an older one could not. While the head fails, piceli gitops status says so (composition at <commit> failed to import (...); deploying the last good commit <commit>, or nothing deploys when there is none) and the controller’s health is degraded.

Status

The status keeps the piceli.gitops-status.v1 schema of Component contracts (piceli.toml); an output image is a component:

  • envs.<env>.components.<image>: source and commit (the first source it reads), sources (every source it reads, at its commit), source_digest (the change key), digest and image (the pushed image), state (building, rolling, synced, unchanged, failed), health and updated_at; 0.74.0: an image built for several platforms also has media_type (application/vnd.oci.image.index.v1+json: digest is the OCI index) and platforms (each platform’s manifest digest);

  • envs.<env>.revision holds the composition repository’s commit too;

  • controller.composition_repo: source, branch, entry, commit (the imported one), error and failed (a commit that did not import).

  • envs.<env>.deleted and envs.<env>.kept_orphaned: what the last deploy pruned (objects the render no longer declares) and kept (claims, Secrets, retained objects, each with the command deleting it); a pending plan (envs.<env>.pending_plan) lists its delete changes and kept_orphaned too, and every run of the deployment history (piceli-gitops-history) has deleted and kept_orphaned. See GitOps: Piceli’s controller and manifest export (removed objects are deleted).

Several clusters and replicas per environment

A composition may declare several clusters: environments then name where they run (clusters=[Placement(...)]) and in which order (Rollout(order=[...])); see Several clusters from one controller.

Environment(..., replicas={"web": 3}) and Environment.per_branch(..., replicas={"db": 1}) set the replica count of Deployments and StatefulSets in that environment (0.15): a branch environment can run one member of a replicated StatefulSet while main runs three. Each name must be a Deployment or StatefulSet the environment renders; a workload a HorizontalPodAutoscaler scales is refused (set its min_replicas and max_replicas instead). Undeclared, nothing changes (the same config and plan hashes as before).

Not yet

  • A pipeline’s secrets= generators run in the controller’s pod (their store on its state volume); this is not yet tested end to end.

  • A build reads its node facts from Build(node_facts=…) or the platform’s defaults; the controller does not read a node’s page size.

  • Branch environments are not seeded from restore points.