Skip to content
intentdPublic

About

Run it once, however many replicas start. A startup task, like a migration or a seed, runs once per release across a Deployment's replicas: one does it, the others wait. An init container and a Kubernetes Lease; nothing to install.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

once: run it once, however many replicas start

Run it once, however many replicas start.

CI Go Reference License

Some work belongs to a release, not to each replica: a database migration, seeding data, creating a bucket or a topic, registering a schema. Start 3 replicas and it runs 3 times, all at once.

once gives your Deployment a step that runs once per release. Every replica runs it on startup; one does the work, the others wait for it, then they all start.

It's an init container and a Kubernetes Lease: nothing to install, nothing new to learn. It works for any language, and you don't change your app's code or its image.

Why not something you already have?

A Job or a hook. The usual fix is a one-off Job that runs before the rollout, like Argo CD's PreSync hook or Helm's pre-upgrade hook. That works, but:

  • the task then belongs to your deploy tool, not your app;
  • it doesn't run when you deploy another way (kubectl apply, a script, a new tool);
  • it repeats the pod's settings, its image, environment, Secrets, volumes and service account, in a second place. The two drift: a Secret added to the Deployment and not to the Job fails the migration in production.

A Job named after its files, like migrate-<hash of migrations/>, from Helm or Kustomize. Kubernetes allows one object per name, so the same files never run twice. But you build the rest yourself: the hash in your templates, an init container that waits for the Job, a way to prune old Jobs (and no ttlSecondsAfterFinished, or a deleted Job runs again on the next sync).

Your migration tool's lock. golang-migrate, Flyway and Liquibase take a database lock and record the steps they ran, so every replica can run migrate up safely. For database migrations, that's often all you need. It does nothing for other startup work: seeding, creating a bucket, registering a schema.

With once, any task runs inside your app's own pod, with its exact settings, when it starts, however it was deployed.

How it works

Replicas start; each claims the same Kubernetes Lease; one wins and runs the task while the others wait; then all replicas start

  • One winner, always. Every pod tries to take the same Kubernetes Lease. Kubernetes accepts only one of them, so only one pod is ever told to run the task.
  • Once per version. A claim is for a name and a version. You don't have to give the version: once works it out from your pod's images, so a new image means a new version. Restarts skip the task; a new release runs it again. Or tie it to files instead: with --version-from ./migrations, it runs again only when the migrations change.
  • A crash is handled. The pod running the task checks in every few seconds. If it stops (it crashed), the next pod takes over.
  • A failure is retried. If the task fails, the next pod runs it again.

Quick start

You change one Deployment. Nothing gets installed in the cluster.

1. Let your pods keep their claim. A small Role, in your app's namespace only:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: once
rules:
  - apiGroups:
      - coordination.k8s.io
    resources:
      - leases
    verbs:
      - get
      - create
      - update
  - apiGroups:
      - ""
    resources:
      - pods
    verbs:
      - get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: my-app-once
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: once
subjects:
  - kind: ServiceAccount
    name: my-app            # your app's service account

2. Add two init containers to your Deployment: the first copies once in, the second runs your task through it. Here the task is a migration:

spec:
  serviceAccountName: my-app
  initContainers:
    - name: once
      image: ghcr.io/intentd/once:0.1.0
      command:
        - /once
        - copy
        - /once-bin/once
      volumeMounts:
        - name: once-bin
          mountPath: /once-bin
    - name: migrate
      image: my-app:v42
      command:
        - /once-bin/once
        - run
        - --name
        - migrate
        - --
        - ./migrate
        - up
      volumeMounts:
        - name: once-bin
          mountPath: /once-bin
  containers:
    - name: my-app
      image: my-app:v42
  volumes:
    - name: once-bin
      emptyDir: {}

That's it. Start as many replicas as you like: the task runs once, and every app container waits for it.

once run exits with your command's own exit code. If the task fails, the init container fails, and Kubernetes restarts it as usual; the next try picks the work up again.

See it work

Three examples, run with jig as one suite on one local cluster:

jig run examples
  • examples/migrate starts three replicas of a small app, each running its migration through once, and checks that it ran once, not three times. shop.yaml is the part to copy.
  • examples/version-from ties the task to its files with --version-from: a restart with the same files skips it, and new files run it once more, while the image stays the same.
  • examples/service does the same with the once service: it installs the chart, and the app's pods, which have no permissions of their own, call it with --url.

Each also runs on its own: jig run examples/migrate.

once run

once run --name NAME [--version VERSION | --version-from PATH] -- COMMAND [ARGS...]
Flag Default What it is
--name the task's name, like migrate or seed
--version worked out from the pod's images the version it runs for; set it when the task shouldn't re-run with every new image
--version-from files or directories whose contents are the version: the task runs again when they change, and not when only the image is rebuilt; repeat it for several
--ttl 30s how long the claim lasts without a check-in from its pod
--url $ONCE_URL, else none the once service's address, only when you use the service (below)

Permissions

What each pod needs, in its own namespace only:

It may On Why
get, create, update Leases (coordination.k8s.io) the claim is a Lease
get Pods to read its own images, when you give no --version

That's all:

  • Nothing cluster-wide.
  • No Secrets. It can't read or write any.
  • No changes to your workloads. It can't touch Deployments or anything else of yours.
  • No listing or watching. It only reads the one object it needs.
  • No deleting. Old claims stay as Leases until you remove them.

Or: with the once service

If your pods can't be given any permissions, run the once service in the cluster instead. Pods then call it over HTTP, and it keeps the claims for them. Your pods need no permissions at all; the service holds them instead.

helm install once oci://ghcr.io/intentd/charts/once --namespace once-system --create-namespace

(Or with one file: kubectl apply -f https://raw.githubusercontent.com/intentd/once/main/deploy/once.yaml.)

Then point once run at it, with --url http://once.once-system or ONCE_URL. Everything else stays the same.

Pods keep their claim (default) The once service
Runs in the cluster nothing a Deployment, always up
If it's down nothing to be down every startup waits
Your pods need a small Role in their namespace no permissions
Cluster-wide rights none yes, held by the service

The service's permissions:

It may On Why
get, create, update Leases it keeps the claims, in each app's namespace
get Pods to read the calling pod's images, when it gives no --version
create TokenReviews (authentication.k8s.io) to ask Kubernetes whose token a caller sent

By default these apply in every namespace. To limit the service to a few, list them when you install it:

helm install once oci://ghcr.io/intentd/charts/once -n once-system --create-namespace \
  --set 'namespaces={shop,blog}'

Then the Lease and Pod rights exist only in shop and blog, and the service refuses callers from anywhere else. Checking tokens stays cluster-wide: Kubernetes only grants that across the whole cluster.

The service's API. Every call sends the pod's service account token (Authorization: Bearer …), so a claim always lives in the caller's own namespace.

Call Does
POST /v1/claims/{name}?version=v42 claim it: 201 run it, 202 someone else is, 200 it's done. Without version, the service works it out from the caller's pod
GET /v1/claims/{name}?version=v42&wait=60s where it stands; waits until it's no longer running
POST /v1/claims/{name}/renew the runner's check-in, with {"version", "token"}
POST /v1/claims/{name}/done it worked
POST /v1/claims/{name}/fail it failed: the next pod retries
GET /healthz is the service up

One thing your task must allow

If a pod crashes halfway, the next one starts the task over. So the task must be safe to run again. Migration tools already handle this: they record which steps ran and skip them. For your own scripts, check that a second run does no harm.

What once is not

  • Not an operator. It adds no custom resources, and nothing in it watches or changes your workloads.
  • Not a migration tool. It doesn't know SQL or schemas. It runs whatever command you give it: Flyway, golang-migrate, Alembic, a script.
  • Not a job runner. It never runs anything on its own. Your pod runs the command; once only decides which pod.
  • Not a deploy tool. It doesn't replace Argo CD, Flux or Helm. It works the same under any of them, or none.
  • Not leader election for a long-running process. It's for one-off work at startup. For "one replica stays in charge", use Kubernetes' own leader election.
  • Not a database. It stores nothing of its own: each claim is a Kubernetes Lease, in your app's namespace.

The CLI on your machine

To try once locally (once version, once run --help):

brew install intentd/tap/once

Or download it from the releases.

Building

make build     # → ~/.once/bin/once
make test
make image     # the container image
make example   # the example, with jig

License

Apache 2.0. See LICENSE.

About

Run it once, however many replicas start. A startup task, like a migration or a seed, runs once per release across a Deployment's replicas: one does it, the others wait. An init container and a Kubernetes Lease; nothing to install.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages