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.stacknames the app’s workloads it runs; checks,rollback_on_failed_checks, restore points and the approval policy are the pipeline’s (auto_approve=Truewith no pipeline policy uses the defaultApprovalPolicy(): 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
StackofComponents,settings=orsecrets=next topipeline=is refused (env-config-invalid). The pipeline has one target (a pipeline with one target per app environment: passpipeline.for_environment(NAME)).The cluster’s registry is
Registry.in_cluster(...): built images go there, and so do the third-party images of itsmirror=[ref@digest](and of the pipeline’s own deliverymirror=). 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’sSourcenamedXat the environment’s revision (its commit of that source). The composition repository is a source too: name it infollow(as the example does) or leave it out and it is read at the commit the controller imported. A context withoutsourcereads the composition repository, relative to the spec’s directory. A context of a source the environment does not follow is refused (composition-invalid, atgitops enableand 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 Secretpiceli-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):
the nodes of the environment’s
on_nodes(names or labels), when set; a DaemonSet ignoreson_nodesand counts with its own selector;else the nodes that every workload’s node selector matches (
node_selector=or the app’spod_defaults), for example{"kubernetes.io/arch": "arm64"}on every workload;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/osand the role labels (piceli.io/role-<role>). A workload with none of them, anapp.overridethat sets anodeSelector, or components added withapp.addmake 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, withmedia_typeand the per-platformplatformsmap), and so do the history andpiceli 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-clusterruns that copy as a Job next to the registry, so a dropped port-forward cannot fail the release, and--ledgerlets a rerun continue where it stopped.A spec without
platformskeeps the 0.68.0 rule above. That is the way to build only what the pods run: leaveplatformsout.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: theoriginremote of--root), the branch to follow (--main-branch, defaultmain) and the module’s path in it; its source name is that of theSourcewith 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>:sourceandcommit(the first source it reads),sources(every source it reads, at its commit),source_digest(the change key),digestandimage(the pushed image),state(building,rolling,synced,unchanged,failed),healthandupdated_at; 0.74.0: an image built for several platforms also hasmedia_type(application/vnd.oci.image.index.v1+json:digestis the OCI index) andplatforms(each platform’s manifest digest);envs.<env>.revisionholds the composition repository’s commit too;controller.composition_repo:source,branch,entry,commit(the imported one),errorandfailed(a commit that did not import).envs.<env>.deletedandenvs.<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 itsdeletechanges andkept_orphanedtoo, and every run of the deployment history (piceli-gitops-history) hasdeletedandkept_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.