diff --git a/apps/docs/content/docs/clouds/digitalocean.mdx b/apps/docs/content/docs/clouds/digitalocean.mdx index 95a03165..d865b985 100644 --- a/apps/docs/content/docs/clouds/digitalocean.mdx +++ b/apps/docs/content/docs/clouds/digitalocean.mdx @@ -5,24 +5,29 @@ description: Connect a DigitalOcean team and run services on App Platform with M import { Step, Steps } from 'fumadocs-ui/components/steps'; -Loomplane runs your services on DigitalOcean App Platform and gives them Managed PostgreSQL, MySQL and Valkey databases. App Platform builds each service from your repository, so you don't need a registry or a builder of your own. +Loomplane runs your services on DigitalOcean App Platform and gives them Managed PostgreSQL, MySQL and Valkey databases. Loomplane builds each service's image itself and pushes it to your DigitalOcean container registry, and App Platform runs that image. DigitalOcean never needs access to your repository. ## Connect DigitalOcean -In DigitalOcean, open **API**, then **Tokens**, and create a personal access token with read and write access. A custom-scoped token needs `app`, `database` and `account:read`. +In DigitalOcean, open **API**, then **Tokens**, and create a personal access token with read and write access. A custom-scoped token needs `app`, `database`, `registry` and `account:read`. -Under **Settings**, then **GitHub**, give DigitalOcean access to the repositories you'll deploy. App Platform clones them through that connection. Loomplane never hands it your code. +In Loomplane, open **Integrations**, choose **DigitalOcean** and paste the token. -In Loomplane, open **Integrations**, choose **DigitalOcean** and paste the token. +Still in **Integrations**, add a registry, choose the **DigitalOcean account** and its **Registry**, then **Check and connect**. If DigitalOcean has no container registry yet, create one under **Container Registry** first. Loomplane pushes the images it builds there, and App Platform pulls them without a password of its own, because the registry is in the same team. + + + + +Make sure a [runner pool](/docs/clouds/runners) can build for the project. Loomplane builds on the project's default pool, or the organization's. @@ -55,11 +60,22 @@ resources: The regions are App Platform's: `nyc`, `sfo`, `tor`, `atl`, `ams`, `fra`, `lon`, `blr`, `sgp` and `syd`. Leave `region` out and you get `nyc`. -Each service in each environment becomes an App Platform app of its own, named after the service, the environment and the project, with deploy on push turned off. A service with a Dockerfile builds from it. Anything else goes through App Platform's buildpacks. Workers run as App Platform workers and static sites as static sites. `size` picks the smallest instance that fits, from `apps-s-1vcpu-0.5gb` up to `apps-d-8vcpu-32gb`, and `scale.min` sets how many instances run. Secret variables go in as App Platform secrets. +Each service in each environment becomes an App Platform app of its own, named after the service, the environment and the project. Workers run as App Platform workers and static sites as static sites. `size` picks the smallest instance that fits, from `apps-s-1vcpu-0.5gb` up to `apps-d-8vcpu-32gb`, and `scale.min` sets how many instances run. Secret variables go in as App Platform secrets. + +## How a service gets built + +A service with a Dockerfile, or a Go module, is built by Loomplane from the commit you approved. The image goes to the DigitalOcean container registry, and the app runs it by digest, so what runs is exactly what you reviewed. The repository can live anywhere Loomplane reads from, a self-managed GitLab included. `build.builder` and `build.registry` pick another runner pool or registry. The registry has to be in the DigitalOcean team the app runs in, because that's the only place App Platform pulls from without a password, and the builder has to build amd64 images. A promotion deploys the image the earlier environment ran when both push to the same registry. + +Two kinds of service still build on App Platform from the repository: + +- Static sites, which App Platform can't run from an image. +- Services with neither a Dockerfile nor a Go module, which App Platform builds with its own buildpacks. + +The same goes for every service until there's a runner pool and a DigitalOcean registry to build with, and the plan warns which one is missing. Those builds need DigitalOcean's own connection to your GitHub or GitLab account, which only someone signed in to DigitalOcean can set up: in DigitalOcean, under **Settings**, then **GitHub**, give it access to the repositories you'll deploy. DigitalOcean's API has no way to do it, so Loomplane can't do it for you. The plan warns about every service that needs it, and a deployment without it fails with DigitalOcean's "GitHub user not authenticated". -## Which commit runs +## Which commit runs from the repository -Every other target here deploys the exact commit a plan approved. App Platform can't, because it always builds the newest commit of a branch and gives you no way to ask for a particular one. So Loomplane checks instead. +An image Loomplane built is the approved commit by construction. A build from the repository isn't, because App Platform always builds the newest commit of a branch and gives you no way to ask for a particular one. So Loomplane checks instead. It points the app at the branch your project reads, starts the deployment itself, and watches the commit App Platform reports for every component. If that's the approved commit, the deployment goes ahead. If someone pushed to the branch after you approved the plan, Loomplane cancels the deployment before it goes live and the step fails with both commits in the message. In the rare case a wrong build gets live before the check sees it, Loomplane rolls the app back to what ran before, or deletes the app if nothing approved ever ran there. @@ -95,7 +111,7 @@ Wildcard hostnames and blocked paths aren't supported yet. Neither is moving a h ## Limits -A private service is only reachable from inside its own App Platform app, and each service here gets its own app, so nothing can call one. The planner says so and asks you to make it public. Build logs stay on the app's **Activity** tab, and Loomplane shows the deployment's progress. +A private service is only reachable from inside its own App Platform app, and each service here gets its own app, so nothing can call one. The planner says so and asks you to make it public. An image Loomplane builds has its build log in Loomplane. A build on App Platform keeps its log on the app's **Activity** tab, and Loomplane shows the deployment's progress. ## Droplets and DNS diff --git a/apps/docs/content/docs/concepts/promotion-and-rollback.mdx b/apps/docs/content/docs/concepts/promotion-and-rollback.mdx index c4c107b6..5b187c5a 100644 --- a/apps/docs/content/docs/concepts/promotion-and-rollback.mdx +++ b/apps/docs/content/docs/concepts/promotion-and-rollback.mdx @@ -35,9 +35,10 @@ Where it can, a promotion deploys the image staging already built, named by its | Azure Container Apps | Yes | The conditions below don't hold, or the image is in another Azure container registry (the region doesn't matter) | | Your own servers, Kubernetes | Yes | The conditions below don't hold, or the target pushes to a different registry, or staging built on its server without one | | Render, Vercel | No | Always. They build each deployment from the commit themselves | -| DigitalOcean App Platform | No | Always. App Platform builds the newest commit of its branch, and the reason says a promotion only works while that's still the commit you're promoting | +| DigitalOcean App Platform, image Loomplane built | Yes | The conditions below don't hold, or the target pushes to a different registry | +| DigitalOcean App Platform, built from the repository | No | Always. App Platform builds the newest commit of its branch, and the reason says a promotion only works while that's still the commit you're promoting | -The conditions, for the first three rows: staging ran the same commit of the service on the same kind of target, built for the same architecture, from the same build inputs (source, Dockerfile, build context, ecosystem, build command and start command), and recorded the image by digest. A release that predates digest-pinned images, or one whose connection can't read digests, has only a tag, so it builds again. +The conditions, for every row that reuses: staging ran the same commit of the service on the same kind of target, built for the same architecture, from the same build inputs (source, Dockerfile, build context, ecosystem, build command and start command), and recorded the image by digest. A release that predates digest-pinned images, or one whose connection can't read digests, has only a tag, so it builds again. A gateway, a catalog service and a service pinned to an existing image have nothing built from a repository, so there's nothing to reuse. If the target environment's release strategy is `canary`, a reused image is what the canary ramps. diff --git a/apps/docs/content/docs/guides/gitlab-repositories.mdx b/apps/docs/content/docs/guides/gitlab-repositories.mdx index 07e1e958..a50356b1 100644 --- a/apps/docs/content/docs/guides/gitlab-repositories.mdx +++ b/apps/docs/content/docs/guides/gitlab-repositories.mdx @@ -99,4 +99,4 @@ Only pushes to a project's default branch re-analyze, and only in the organizati ## Deploying -Every deployment target but two builds from the archive Loomplane fetched. Render and DigitalOcean App Platform build from the repository themselves, through their own GitLab connection, so connect GitLab in Render's or DigitalOcean's dashboard first. They build gitlab.com sources only. A source on a self-managed GitLab can't deploy to either, and the plan reports it. +Every deployment target builds from the archive Loomplane fetched, with two exceptions. Render builds from the repository itself, through its own GitLab connection. So does DigitalOcean App Platform for a static site, for a service with no Dockerfile, and for any service while there's no runner pool and DigitalOcean registry for Loomplane to build with (see [DigitalOcean](/docs/clouds/digitalocean)). Connect GitLab in Render's or DigitalOcean's dashboard first for those. They build gitlab.com sources only. A source on a self-managed GitLab can't deploy that way, and the plan reports it. diff --git a/apps/docs/content/docs/how-it-works.mdx b/apps/docs/content/docs/how-it-works.mdx index b959dd8b..1dedcdec 100644 --- a/apps/docs/content/docs/how-it-works.mdx +++ b/apps/docs/content/docs/how-it-works.mdx @@ -27,7 +27,7 @@ A developer can plan anything. Only an admin's approval changes a cloud, and the ## 6. Deploy -Approval starts a durable workflow. It stores one source tarball per repository, provisions resources, builds each service on its cloud's own builder (Cloud Build, CodeBuild, Vercel, Render, App Platform or ACR Tasks), deploys it, and checks that public services answer. If a step fails, you retry from that step. See [Deployments and recovery](/docs/concepts/deployments-and-recovery). +Approval starts a durable workflow. It stores one source tarball per repository, provisions resources, builds each service on its cloud's own builder (Cloud Build, CodeBuild, Vercel, Render, App Platform or ACR Tasks) or on a runner pool, deploys it, and checks that public services answer. If a step fails, you retry from that step. See [Deployments and recovery](/docs/concepts/deployments-and-recovery). ## 7. Watch for drift diff --git a/extensions/planning/extension.go b/extensions/planning/extension.go index f4f341fc..95aef41b 100644 --- a/extensions/planning/extension.go +++ b/extensions/planning/extension.go @@ -309,9 +309,13 @@ func (e *Extension) Register(fapp forge.App) error { Ctrl: deployments.CtrlPlane{Providers: cp.Providers(), Instances: cp.Instances, Deploys: cp.Deploys}, Credentials: clouds, }, - "vercel": &deployments.Vercel{Client: vercelResourcesClient, Environments: nativeEnvironments}, - "render": &deployments.Render{Client: render.New(e.cfg.Clouds.RenderEndpoint), Environments: nativeEnvironments}, - "digitalocean": &deployments.DigitalOcean{Client: appPlatform}, + "vercel": &deployments.Vercel{Client: vercelResourcesClient, Environments: nativeEnvironments}, + "render": &deployments.Render{Client: render.New(e.cfg.Clouds.RenderEndpoint), Environments: nativeEnvironments}, + // App Platform runs the images Loomplane's builders build, so + // DigitalOcean needs no access to the repository. + "digitalocean": &deployments.DigitalOcean{Client: appPlatform, Builder: &deployments.ImageBuilder{ + FirecrackerAuthority: deployStore, NodeStreams: e.streams, Gate: &e.metering, Runners: e.runners, AWS: awsClient(), + }}, "azure-container-apps": &deployments.Azure{Client: azureClient()}, "azure-database": &deployments.AzureDatabase{Client: azureClient()}, "azure-managed-redis": &deployments.AzureRedis{Client: azureClient()}, diff --git a/internal/agentknowledge/docs.json b/internal/agentknowledge/docs.json index 51161a1e..7b7269a7 100644 --- a/internal/agentknowledge/docs.json +++ b/internal/agentknowledge/docs.json @@ -1,6 +1,6 @@ { "version": 1, - "digest": "56b24d8f61ff8dd586361e0fe95256287eb54812cd40385fff948470b255fc22", + "digest": "94bf67d8fc451d3d4572038cdcfba23778127105c13e4eff039f0980b91f3f9d", "pages": [ { "path": "", @@ -140,7 +140,7 @@ "title": "DigitalOcean", "description": "Connect a DigitalOcean team and run services on App Platform with Managed PostgreSQL, MySQL and Valkey.", "url": "https://www.loomplane.com/docs/clouds/digitalocean", - "text": "Loomplane runs your services on DigitalOcean App Platform and gives them Managed PostgreSQL, MySQL and Valkey databases. App Platform builds each service from your repository, so you don't need a registry or a builder of your own.\n\n## Connect DigitalOcean\n\n\nIn DigitalOcean, open **API**, then **Tokens**, and create a personal access token with read and write access. A custom-scoped token needs `app`, `database` and `account:read`.\n\n\nUnder **Settings**, then **GitHub**, give DigitalOcean access to the repositories you'll deploy. App Platform clones them through that connection. Loomplane never hands it your code.\n\n\nIn Loomplane, open **Integrations**, choose **DigitalOcean** and paste the token.\n\n\nLoomplane asks DigitalOcean whose token it is before it keeps it. A token belongs to one team, and that team is where every app and database is made. A token from a locked account is refused.\n\n## Sign in instead of a token\n\nIf a platform owner or admin has registered a DigitalOcean OAuth app, the connect dialog offers **Sign in with DigitalOcean** first and **Use a token instead** underneath. You approve Loomplane on DigitalOcean, and Loomplane renews the grant itself. The app asks for the `read write` scope, which covers what the token steps above grant. [Connect a cloud by signing in](/docs/clouds/cloud-sign-in) covers registering the app and what happens if DigitalOcean stops accepting the sign-in.\n\n## Use it in a manifest\n\n```yaml\nversion: 1\ndefaults:\n provider: digitalocean\n region: ams\nservices:\n web:\n source: apps/web\n needs: [api]\n api:\n source: services/api\n needs: [db]\nresources:\n db:\n kind: postgres\n version: \"16\"\n```\n\nThe regions are App Platform's: `nyc`, `sfo`, `tor`, `atl`, `ams`, `fra`, `lon`, `blr`, `sgp` and `syd`. Leave `region` out and you get `nyc`.\n\nEach service in each environment becomes an App Platform app of its own, named after the service, the environment and the project, with deploy on push turned off. A service with a Dockerfile builds from it. Anything else goes through App Platform's buildpacks. Workers run as App Platform workers and static sites as static sites. `size` picks the smallest instance that fits, from `apps-s-1vcpu-0.5gb` up to `apps-d-8vcpu-32gb`, and `scale.min` sets how many instances run. Secret variables go in as App Platform secrets.\n\n## Which commit runs\n\nEvery other target here deploys the exact commit a plan approved. App Platform can't, because it always builds the newest commit of a branch and gives you no way to ask for a particular one. So Loomplane checks instead.\n\nIt points the app at the branch your project reads, starts the deployment itself, and watches the commit App Platform reports for every component. If that's the approved commit, the deployment goes ahead. If someone pushed to the branch after you approved the plan, Loomplane cancels the deployment before it goes live and the step fails with both commits in the message. In the rare case a wrong build gets live before the check sees it, Loomplane rolls the app back to what ran before, or deletes the app if nothing approved ever ran there.\n\nSo don't push to a branch while a plan for it waits for approval. If your repository's default branch isn't `main`, set the branch on the project's repository in Loomplane, because a repository left on its default branch is built from `main`. To deploy another branch for a while, analyze it with **Another branch**: a plan builds the branch its analysis read.\n\nA brand-new app's `ondigitalocean.app` address takes a few minutes to appear in DNS after App Platform says it's live. Loomplane waits for it in public DNS for up to ten minutes before it checks that the service answers. If it still isn't there, the step says the app is deployed, and retrying checks again.\n\n## Databases\n\n| Manifest kind | Made on DigitalOcean | Versions |\n|---|---|---|\n| `postgres` | Managed PostgreSQL | 17, 16, 15 |\n| `mysql` | Managed MySQL | 8 |\n| `redis` | Managed Valkey, which speaks the Redis protocol | DigitalOcean's current one |\n\nEach is a single `db-s-1vcpu-1gb` node in the datacenter that matches the region: `nyc` gets `nyc3`, `ams` gets `ams3`, `fra` gets `fra1`, and so on. You can name a datacenter outright, such as `nyc1`, as a resource's region. Services that need a database get its connection string as a secret, with TLS required. Loomplane doesn't set trusted sources, so add them in DigitalOcean if you want only your apps to reach it.\n\nRemoving a database from the manifest deletes it with its data, so take a backup first if you need one.\n\n## Hostnames\n\nOpen the service's page and use **Add hostname**, the same dialog you use anywhere else. The hostname reaches the service's public HTTP port and nothing else. A private service can't take one, so make it public in the manifest and deploy it first. A public service with no port set can't either, and neither can a static site yet.\n\nWhat happens next depends on who runs the domain's DNS. If Loomplane manages it, Loomplane writes the records, and the preview refuses before anything is written if the name already has A, AAAA or CNAME records. A subdomain gets a CNAME to the app's `ondigitalocean.app` address. The domain itself (the apex) gets App Platform's static addresses, which are A records for `162.159.140.98` and `172.66.0.96`, and AAAA records for `2606:4700:7::60` and `2a06:98c1:58::60`. If you run the DNS somewhere else, the dialog lists the records and you add them yourself. Loomplane can't see that zone, so remove any A, AAAA or CNAME record already at the name before you add its records.\n\nLoomplane adds the hostname to the app as an alias domain, which leaves the app's own address alone, and DigitalOcean issues the certificate. The hostname shows **Issuing** until DigitalOcean reports the certificate active.\n\nIf the app is mid-deployment when you add the hostname, Loomplane waits for that deployment to finish first. Adding a hostname can make App Platform start a deployment of its own. Loomplane checks that it built the commit you reviewed. If it didn't, Loomplane cancels it, or rolls back if it already went live, and asks you to deploy the service and then retry the hostname. If the app runs a different commit from the one you reviewed, the hostname waits until the service's deploy finishes.\n\nDeploys keep the app's hostnames, including any you added in DigitalOcean's control panel.\n\nWildcard hostnames and blocked paths aren't supported yet. Neither is moving a hostname to another app: remove it and add it again.\n\n## Limits\n\nA private service is only reachable from inside its own App Platform app, and each service here gets its own app, so nothing can call one. The planner says so and asks you to make it public. Build logs stay on the app's **Activity** tab, and Loomplane shows the deployment's progress.\n\n## Droplets and DNS\n\nYou can also provision managed Droplets in an organization Cloud, adopt a pinned SSH/Docker host, and place services through server pools. That uses the server runtime, and your App Platform manifests keep using the managed runtime. [Your own servers](/docs/clouds/your-own-servers) has the commands.\n\nGPU Droplets work too, with a GPU-ready image and the NVIDIA Container Toolkit set up for you at first boot. The hourly price shows before you approve. See [GPUs](/docs/clouds/gpus) for pools, ceilings and what happens if the setup fails.\n\nDigitalOcean's compute and DNS capabilities are checked independently. Your App Platform token scopes don't establish Droplet or DNS permissions, so an operation without the permission it needs fails before any new effects. For a managed DNS zone you can use a different account than the one for compute.\n\nWhen `LOOMPLANE_MANAGED_SSH_ALLOWED_CIDRS` is set, creating a Droplet also needs firewall and tag access (`firewall:create`, `firewall:read`, `firewall:update`, `tag:create` and `tag:read` on a custom-scoped token). Loomplane keeps one firewall per SSH port, named `loomplane-ssh-`, and the Droplets join it through a tag of the same name. Don't change its rules: Loomplane puts them back the next time it creates a server or checks one.\n\n Fixture-backed provider and ACME checks don't qualify your DigitalOcean account, DNS propagation or public certificate issuance. Verify those with your own authorized live scope before a production move." + "text": "Loomplane runs your services on DigitalOcean App Platform and gives them Managed PostgreSQL, MySQL and Valkey databases. Loomplane builds each service's image itself and pushes it to your DigitalOcean container registry, and App Platform runs that image. DigitalOcean never needs access to your repository.\n\n## Connect DigitalOcean\n\n\nIn DigitalOcean, open **API**, then **Tokens**, and create a personal access token with read and write access. A custom-scoped token needs `app`, `database`, `registry` and `account:read`.\n\n\nIn Loomplane, open **Integrations**, choose **DigitalOcean** and paste the token.\n\n\nStill in **Integrations**, add a registry, choose the **DigitalOcean account** and its **Registry**, then **Check and connect**. If DigitalOcean has no container registry yet, create one under **Container Registry** first. Loomplane pushes the images it builds there, and App Platform pulls them without a password of its own, because the registry is in the same team.\n\n\nMake sure a [runner pool](/docs/clouds/runners) can build for the project. Loomplane builds on the project's default pool, or the organization's.\n\n\nLoomplane asks DigitalOcean whose token it is before it keeps it. A token belongs to one team, and that team is where every app and database is made. A token from a locked account is refused.\n\n## Sign in instead of a token\n\nIf a platform owner or admin has registered a DigitalOcean OAuth app, the connect dialog offers **Sign in with DigitalOcean** first and **Use a token instead** underneath. You approve Loomplane on DigitalOcean, and Loomplane renews the grant itself. The app asks for the `read write` scope, which covers what the token steps above grant. [Connect a cloud by signing in](/docs/clouds/cloud-sign-in) covers registering the app and what happens if DigitalOcean stops accepting the sign-in.\n\n## Use it in a manifest\n\n```yaml\nversion: 1\ndefaults:\n provider: digitalocean\n region: ams\nservices:\n web:\n source: apps/web\n needs: [api]\n api:\n source: services/api\n needs: [db]\nresources:\n db:\n kind: postgres\n version: \"16\"\n```\n\nThe regions are App Platform's: `nyc`, `sfo`, `tor`, `atl`, `ams`, `fra`, `lon`, `blr`, `sgp` and `syd`. Leave `region` out and you get `nyc`.\n\nEach service in each environment becomes an App Platform app of its own, named after the service, the environment and the project. Workers run as App Platform workers and static sites as static sites. `size` picks the smallest instance that fits, from `apps-s-1vcpu-0.5gb` up to `apps-d-8vcpu-32gb`, and `scale.min` sets how many instances run. Secret variables go in as App Platform secrets.\n\n## How a service gets built\n\nA service with a Dockerfile, or a Go module, is built by Loomplane from the commit you approved. The image goes to the DigitalOcean container registry, and the app runs it by digest, so what runs is exactly what you reviewed. The repository can live anywhere Loomplane reads from, a self-managed GitLab included. `build.builder` and `build.registry` pick another runner pool or registry. The registry has to be in the DigitalOcean team the app runs in, because that's the only place App Platform pulls from without a password, and the builder has to build amd64 images. A promotion deploys the image the earlier environment ran when both push to the same registry.\n\nTwo kinds of service still build on App Platform from the repository:\n\n- Static sites, which App Platform can't run from an image.\n- Services with neither a Dockerfile nor a Go module, which App Platform builds with its own buildpacks.\n\nThe same goes for every service until there's a runner pool and a DigitalOcean registry to build with, and the plan warns which one is missing. Those builds need DigitalOcean's own connection to your GitHub or GitLab account, which only someone signed in to DigitalOcean can set up: in DigitalOcean, under **Settings**, then **GitHub**, give it access to the repositories you'll deploy. DigitalOcean's API has no way to do it, so Loomplane can't do it for you. The plan warns about every service that needs it, and a deployment without it fails with DigitalOcean's \"GitHub user not authenticated\".\n\n## Which commit runs from the repository\n\nAn image Loomplane built is the approved commit by construction. A build from the repository isn't, because App Platform always builds the newest commit of a branch and gives you no way to ask for a particular one. So Loomplane checks instead.\n\nIt points the app at the branch your project reads, starts the deployment itself, and watches the commit App Platform reports for every component. If that's the approved commit, the deployment goes ahead. If someone pushed to the branch after you approved the plan, Loomplane cancels the deployment before it goes live and the step fails with both commits in the message. In the rare case a wrong build gets live before the check sees it, Loomplane rolls the app back to what ran before, or deletes the app if nothing approved ever ran there.\n\nSo don't push to a branch while a plan for it waits for approval. If your repository's default branch isn't `main`, set the branch on the project's repository in Loomplane, because a repository left on its default branch is built from `main`. To deploy another branch for a while, analyze it with **Another branch**: a plan builds the branch its analysis read.\n\nA brand-new app's `ondigitalocean.app` address takes a few minutes to appear in DNS after App Platform says it's live. Loomplane waits for it in public DNS for up to ten minutes before it checks that the service answers. If it still isn't there, the step says the app is deployed, and retrying checks again.\n\n## Databases\n\n| Manifest kind | Made on DigitalOcean | Versions |\n|---|---|---|\n| `postgres` | Managed PostgreSQL | 17, 16, 15 |\n| `mysql` | Managed MySQL | 8 |\n| `redis` | Managed Valkey, which speaks the Redis protocol | DigitalOcean's current one |\n\nEach is a single `db-s-1vcpu-1gb` node in the datacenter that matches the region: `nyc` gets `nyc3`, `ams` gets `ams3`, `fra` gets `fra1`, and so on. You can name a datacenter outright, such as `nyc1`, as a resource's region. Services that need a database get its connection string as a secret, with TLS required. Loomplane doesn't set trusted sources, so add them in DigitalOcean if you want only your apps to reach it.\n\nRemoving a database from the manifest deletes it with its data, so take a backup first if you need one.\n\n## Hostnames\n\nOpen the service's page and use **Add hostname**, the same dialog you use anywhere else. The hostname reaches the service's public HTTP port and nothing else. A private service can't take one, so make it public in the manifest and deploy it first. A public service with no port set can't either, and neither can a static site yet.\n\nWhat happens next depends on who runs the domain's DNS. If Loomplane manages it, Loomplane writes the records, and the preview refuses before anything is written if the name already has A, AAAA or CNAME records. A subdomain gets a CNAME to the app's `ondigitalocean.app` address. The domain itself (the apex) gets App Platform's static addresses, which are A records for `162.159.140.98` and `172.66.0.96`, and AAAA records for `2606:4700:7::60` and `2a06:98c1:58::60`. If you run the DNS somewhere else, the dialog lists the records and you add them yourself. Loomplane can't see that zone, so remove any A, AAAA or CNAME record already at the name before you add its records.\n\nLoomplane adds the hostname to the app as an alias domain, which leaves the app's own address alone, and DigitalOcean issues the certificate. The hostname shows **Issuing** until DigitalOcean reports the certificate active.\n\nIf the app is mid-deployment when you add the hostname, Loomplane waits for that deployment to finish first. Adding a hostname can make App Platform start a deployment of its own. Loomplane checks that it built the commit you reviewed. If it didn't, Loomplane cancels it, or rolls back if it already went live, and asks you to deploy the service and then retry the hostname. If the app runs a different commit from the one you reviewed, the hostname waits until the service's deploy finishes.\n\nDeploys keep the app's hostnames, including any you added in DigitalOcean's control panel.\n\nWildcard hostnames and blocked paths aren't supported yet. Neither is moving a hostname to another app: remove it and add it again.\n\n## Limits\n\nA private service is only reachable from inside its own App Platform app, and each service here gets its own app, so nothing can call one. The planner says so and asks you to make it public. An image Loomplane builds has its build log in Loomplane. A build on App Platform keeps its log on the app's **Activity** tab, and Loomplane shows the deployment's progress.\n\n## Droplets and DNS\n\nYou can also provision managed Droplets in an organization Cloud, adopt a pinned SSH/Docker host, and place services through server pools. That uses the server runtime, and your App Platform manifests keep using the managed runtime. [Your own servers](/docs/clouds/your-own-servers) has the commands.\n\nGPU Droplets work too, with a GPU-ready image and the NVIDIA Container Toolkit set up for you at first boot. The hourly price shows before you approve. See [GPUs](/docs/clouds/gpus) for pools, ceilings and what happens if the setup fails.\n\nDigitalOcean's compute and DNS capabilities are checked independently. Your App Platform token scopes don't establish Droplet or DNS permissions, so an operation without the permission it needs fails before any new effects. For a managed DNS zone you can use a different account than the one for compute.\n\nWhen `LOOMPLANE_MANAGED_SSH_ALLOWED_CIDRS` is set, creating a Droplet also needs firewall and tag access (`firewall:create`, `firewall:read`, `firewall:update`, `tag:create` and `tag:read` on a custom-scoped token). Loomplane keeps one firewall per SSH port, named `loomplane-ssh-`, and the Droplets join it through a tag of the same name. Don't change its rules: Loomplane puts them back the next time it creates a server or checks one.\n\n Fixture-backed provider and ACME checks don't qualify your DigitalOcean account, DNS propagation or public certificate issuance. Verify those with your own authorized live scope before a production move." }, { "path": "clouds/google-cloud", @@ -259,7 +259,7 @@ "title": "Promotion and rollback", "description": "Promote what staging runs to production, roll an environment back to its previous release, and let Loomplane watch a release after it deploys.", "url": "https://www.loomplane.com/docs/concepts/promotion-and-rollback", - "text": "Three things sit on top of an ordinary release. A promotion deploys to one environment exactly what another environment already runs. A rollback plans an environment back to the release before its current one. And a post-deploy watch keeps judging a release for a while after it goes live, so a bad one can be rolled back without anybody staring at a graph.\n\nAll three are plans. Nothing deploys until someone approves, with one exception that's covered under [automatic rollback](#automatic-rollback).\n\n## Promote staging to production\n\n```bash\nloomctl promote my-project\nloomctl promote my-project --from staging --to production --scope web\nloomctl approve \n```\n\n`--from` defaults to `staging` and `--to` to `production`. `loomctl plan my-project --env production --from staging` does the same thing. In the dashboard, open Deployments and choose Promote.\n\nThe plan pins what the source environment runs, read in one snapshot. Each repository moves to the commit and analysis its last successful deployment there recorded, with the root and branch that deployment used. Repositories you leave out with `--scope` stay at what the target already runs, and a repository the source doesn't run is held the same way. If a held repository has never been deployed to the target, the plan is refused and tells you to add it to the scope.\n\nA promotion also uses the manifest revision the source environment last deployed with, not the latest one. If you've saved a newer manifest since, the plan carries a `newer-manifest` warning that names both revisions: deploy the new one to staging first if you want it in production. When the source never recorded a revision, the plan uses the latest and warns about that instead.\n\nA repository whose commit nothing has analyzed (the source runs it, but the deployment didn't record an analysis) gets an analysis queued when you ask for the promotion. The plan stays in planning until that finishes, and gives up with the analysis error after about six minutes. When the source recorded no release of a repository and its services run it at more than one commit, the plan is refused and names the commits: deploy one commit of it there first.\n\nYou approve a promotion like any plan. If staging releases again before you approve, what the plan would reuse can change, and the approval comes back stale.\n\n### Which images a promotion reuses\n\nWhere it can, a promotion deploys the image staging already built, named by its digest, so production runs the bytes you tested and nothing builds twice. The plan lists a choice for every service it builds, reused or not, with the reason.\n\n| Target | Reuses the image | Builds again when |\n|---|---|---|\n| Cloud Run, ECS Fargate | Yes | The conditions below don't hold, or the image sits in another Google Cloud project or region, or another AWS account or region |\n| Azure Container Apps | Yes | The conditions below don't hold, or the image is in another Azure container registry (the region doesn't matter) |\n| Your own servers, Kubernetes | Yes | The conditions below don't hold, or the target pushes to a different registry, or staging built on its server without one |\n| Render, Vercel | No | Always. They build each deployment from the commit themselves |\n| DigitalOcean App Platform | No | Always. App Platform builds the newest commit of its branch, and the reason says a promotion only works while that's still the commit you're promoting |\n\nThe conditions, for the first three rows: staging ran the same commit of the service on the same kind of target, built for the same architecture, from the same build inputs (source, Dockerfile, build context, ecosystem, build command and start command), and recorded the image by digest. A release that predates digest-pinned images, or one whose connection can't read digests, has only a tag, so it builds again.\n\nA gateway, a catalog service and a service pinned to an existing image have nothing built from a repository, so there's nothing to reuse. If the target environment's release strategy is `canary`, a reused image is what the canary ramps.\n\n### The staging soak\n\nA promotion plan shows how long the source environment has run exactly the commits you're about to ship, and whether it ran them healthily. The Plan tab in the dashboard has it under Source environment, and `loomctl promote` prints it before the approve line:\n\n```text\nSoak: staging has run these commits for 2h30m, healthy\n```\n\nThe clock starts when the last of the commits was deployed to the source. Every service built from those commits is judged over that stretch, up to the last 24 hours, with the target environment's thresholds. A soak has no baseline to compare against, so only two of them count: the error ceiling (`error_rate`) and `min_requests`. The soak is healthy when every one of those services passes.\n\nUnverified means missing evidence. A soak is unverified when the source runs the commits but a service had too little traffic to judge, its cloud reports no metrics to Loomplane, or they've been running for less than a few minutes. A service that exceeded the error ceiling is evidence, so that's reported as not healthy and isn't unverified. If the source doesn't run the commits at all, the line says so and why.\n\nThe soak informs your decision and nothing else. It never blocks an approval.\n\n## Roll back an environment\n\n```bash\nloomctl rollback my-project --env production --reason \"checkout 500s after release\"\nloomctl approve \n```\n\nThe reason is required, up to 2,000 characters, and goes in the audit trail and in front of whoever approves. Before it plans, `loomctl rollback` prints which deployment it undoes and which it restores, with each repository's commits. In the dashboard, open the environment's newest deployment and choose Roll back.\n\nA rollback is a normal plan. A developer creates it, an admin approves it, it expires if nobody decides, and it shows up in `loomctl plans` beside everything else. What's different is what it contains.\n\n### What it restores\n\nThe previous release is the newest successful deployment of that environment that finished before the one you're undoing started. A rollback's own deployment counts, because it restored a state somebody approved. Cloud syncs and standalone catalog plans don't count, since they change where infrastructure runs and not the application.\n\nA release that an earlier rollback undid is skipped, and so is one whose rollback failed. Say production ran R1, then R2, then R3. Rolling back R3 restores R2. If R2's rollback had failed before R3 shipped, rolling back R3 skips R2 and restores R1. To go to a release that was skipped, promote or deploy it explicitly.\n\nThe rollback pins every repository to the commits that release deployed, all of them moving, and uses the manifest revision it deployed with. Services return to that release's image under the same rules as a promotion (the table above), except on DigitalOcean App Platform, where a rollback goes back to the App Platform deployment Loomplane recorded for that release. If there is no such deployment, it predates the record, it ran another commit, or the release you're undoing moved the service off App Platform, the plan has a problem and can't be approved.\n\n### What it leaves alone\n\nA rollback only reverts services' code and settings. It never deletes, replaces or reverts a data-bearing resource, so a database keeps the rows and the schema the bad release left it with.\n\nIn practice: an update or replacement of a service that holds no data goes back. Anything else the restore would have done stays as the bad release left it, and the plan lists it under Left in place with the reason. That covers every resource (a bucket, a cache, a database), a service the release created, a service it removed, and any service that runs a catalog recipe or a component with storage.\n\nIf a service you're restoring links to a resource the release you're undoing removed, the plan has a problem called `rollback-needs-resource`. A rollback never recreates a resource, so it can't bring that service back. Release a version that creates the resource instead.\n\nA rollback goes back all at once. It never ramps as a canary, even in an environment whose strategy is `canary`, and it arms no watch.\n\n### When it's refused\n\n| Situation | What you do |\n|---|---|\n| A deployment is running or paused in the environment | Wait for it, or cancel it |\n| The environment has no earlier successful release | Nothing to restore. Deploy or promote |\n| The current release is a rollback | Deploy or promote to move forward. Rolling a rollback back would only bring back the release it undid |\n| The current release is a rollback that failed | Retry that rollback deployment, which finishes the move it was approved for |\n| The newest deployment's canary already returned to the baseline | Nothing to roll back |\n| A canary's revert or promotion failed | Fix the traffic split from the deployment, then roll back |\n| You named a deployment that isn't the newest | Roll back the newest first. Naming an older one would undo every release after it |\n| A release still holds a route handoff | Finish the handoff. The rollback waits for it like any other plan |\n\n## Watch a release after it deploys\n\nA canary judges a release while it ramps. The post-deploy watch judges it afterward, from the same cloud monitoring and with the same thresholds, and rolls it back if a service breaches them.\n\n### Turn it on\n\nThe watch is a setting of the environment's `release` block in `loomplane.yaml`:\n\n```yaml\nenvironments:\n production:\n release:\n strategy: direct\n watch: 30m\n thresholds:\n error_rate: 1%\n```\n\n`watch` is a duration in whole minutes, up to `24h`. Leave it out and a `canary` or `blue_green` environment is watched for 15 minutes while a `direct` one isn't watched at all. `watch: \"0\"` turns it off. The plan pins the watch with the rest of the release block, so changing it gives you a new revision to approve. An environment with no `release` block deploys exactly as it always has: no watch is armed.\n\n### What gets watched\n\nThe watch starts when a deployment finishes successfully, and covers the services that release created, updated or replaced. It skips the services a canary ramped, because the canary already judged them. It isn't armed for a rollback, a Cloud sync, a standalone catalog plan, a failed deployment, a canary that didn't promote, or a release that changed no service.\n\nA service can be watched when its cloud reports both requests and errors to Loomplane, which today means Cloud Run, ECS Fargate, Azure Container Apps and Render (the Requests and 5xx columns in the [canary table](/docs/concepts/canary-releases#where-canaries-run)). Services on your own servers and clusters report to your own monitoring, which Loomplane doesn't read. Vercel and DigitalOcean report nothing it can use. Each service the watch can't judge is listed with the reason, and it leaves the release unverified. If none of the changed services can be watched, the watch settles as inconclusive straight away.\n\nThe first reading comes about four minutes after the release finishes, because cloud monitoring reports a few minutes late. After that the watch checks every minute. It reads the service's health since the release finished and compares it with the same length of time before the deployment started. A service the release created or moved has no history, so it's judged on the thresholds alone.\n\n| Status | Meaning |\n|---|---|\n| `watching` | The window is still open or the readings aren't decisive yet |\n| `passed` | Every watched service passed through the whole window |\n| `inconclusive` | The watch couldn't decide by 15 minutes after its window ended, usually from too little traffic. The release is unverified and nothing is rolled back |\n| `superseded` | A newer release replaced this one before the watch finished |\n| `rolling_back` | A service breached, and the rollback is being planned, approved or deployed |\n| `rolled_back` | The rollback deployment succeeded |\n| `rollback_blocked` | The rollback couldn't go ahead on its own, and the watch says why |\n| `rollback_failed` | The rollback deployment failed, was cancelled or never started |\n\nA breach doesn't wait for the window to end. One failing service is enough.\n\nUnverified means missing evidence, and it never goes back to false. A release is unverified when a changed service wasn't watched, when the watch settled inconclusive, or when a newer release superseded the watch before it could judge. The release may well be fine, but nobody has the readings to say so, and that's worth a look from you.\n\nA newer release supersedes the watch if it starts while the watch is open, or if it changes a service the watch is judging. The watch stops and settles `superseded`. It doesn't roll back, because rolling back the older release would undo the newer one too. The same holds once a rollback is planned: if you plan the environment again before it deploys, or a newer release deploys while the rollback waits behind a Cloud sync, the rollback deploys nothing and the watch settles `superseded`.\n\n### Automatic rollback\n\nWhen a service breaches, Loomplane plans the rollback of that release, using the same rules as a manual one, and approves it itself. The plan's reason names the service and what it measured. The plan says it was started by Loomplane automation, and so does every audit entry it makes: the breach (`release_watch.breach`), the approval (`plan.approve`, marked automatic) and the settled watch (`release_watch.settle`).\n\nThis is the one place a plan is approved without a person, and the rules around it are narrow. Loomplane automation holds a role that can read a project, create deployments and approve them, but the planning service lets it create and approve only a rollback that a watch started. Every other plan, and every promotion or manual rollback, refuses it, and no session or API key ever acts as it. If Loomplane automation can't create or approve the rollback, for example because its role assignment failed, the watch settles `rollback_blocked`, and the rollback plan, if there is one, stays ready for a person to approve.\n\nTo turn automatic rollback off, turn the watch off for that environment in the manifest: set `release.watch: \"0\"`, use the `direct` strategy without a `watch`, or leave out the `release` block. Nothing is watched there, so nothing rolls back on its own, and every release there is unverified. The change goes through a plan like any other, so it's reviewed. Removing the `loomplane-automation` assignment in Warden doesn't last: Loomplane writes it back the next time it starts.\n\nPlanning can also refuse for good, for the reasons in [When it's refused](#when-its-refused), and then the watch settles `rollback_blocked` with the reason. If the rollback plan never finishes planning, or its deployment never starts within an hour, the watch gives up and settles `rollback_failed`. You can find the plan from the watch, and from there you decide.\n\n## Where to see it\n\nOn a deployment's page, a Release watch panel shows the status, each watched service's verdict, the services it couldn't watch and why, and the rollback plan if it breached. Roll back sits beside Retry on a deployment that has finished, is the newest in its environment and isn't a rollback itself. The dialog shows what the rollback restores and asks for a reason, and a refusal from the server appears there in plain text.\n\nFrom a terminal, `loomctl deployment ` prints a `Watch:` section, and `loomctl promote` prints the `Soak:` line. An agent reads the watch with `get_release_watch`, and can plan a rollback with `create_rollback` when you start the MCP server with `--allow-deploy`. A person still approves it. See [loomctl](/docs/reference/loomctl), [MCP server](/docs/agents/mcp-server) and the [HTTP API](/docs/reference/http-api)." + "text": "Three things sit on top of an ordinary release. A promotion deploys to one environment exactly what another environment already runs. A rollback plans an environment back to the release before its current one. And a post-deploy watch keeps judging a release for a while after it goes live, so a bad one can be rolled back without anybody staring at a graph.\n\nAll three are plans. Nothing deploys until someone approves, with one exception that's covered under [automatic rollback](#automatic-rollback).\n\n## Promote staging to production\n\n```bash\nloomctl promote my-project\nloomctl promote my-project --from staging --to production --scope web\nloomctl approve \n```\n\n`--from` defaults to `staging` and `--to` to `production`. `loomctl plan my-project --env production --from staging` does the same thing. In the dashboard, open Deployments and choose Promote.\n\nThe plan pins what the source environment runs, read in one snapshot. Each repository moves to the commit and analysis its last successful deployment there recorded, with the root and branch that deployment used. Repositories you leave out with `--scope` stay at what the target already runs, and a repository the source doesn't run is held the same way. If a held repository has never been deployed to the target, the plan is refused and tells you to add it to the scope.\n\nA promotion also uses the manifest revision the source environment last deployed with, not the latest one. If you've saved a newer manifest since, the plan carries a `newer-manifest` warning that names both revisions: deploy the new one to staging first if you want it in production. When the source never recorded a revision, the plan uses the latest and warns about that instead.\n\nA repository whose commit nothing has analyzed (the source runs it, but the deployment didn't record an analysis) gets an analysis queued when you ask for the promotion. The plan stays in planning until that finishes, and gives up with the analysis error after about six minutes. When the source recorded no release of a repository and its services run it at more than one commit, the plan is refused and names the commits: deploy one commit of it there first.\n\nYou approve a promotion like any plan. If staging releases again before you approve, what the plan would reuse can change, and the approval comes back stale.\n\n### Which images a promotion reuses\n\nWhere it can, a promotion deploys the image staging already built, named by its digest, so production runs the bytes you tested and nothing builds twice. The plan lists a choice for every service it builds, reused or not, with the reason.\n\n| Target | Reuses the image | Builds again when |\n|---|---|---|\n| Cloud Run, ECS Fargate | Yes | The conditions below don't hold, or the image sits in another Google Cloud project or region, or another AWS account or region |\n| Azure Container Apps | Yes | The conditions below don't hold, or the image is in another Azure container registry (the region doesn't matter) |\n| Your own servers, Kubernetes | Yes | The conditions below don't hold, or the target pushes to a different registry, or staging built on its server without one |\n| Render, Vercel | No | Always. They build each deployment from the commit themselves |\n| DigitalOcean App Platform, image Loomplane built | Yes | The conditions below don't hold, or the target pushes to a different registry |\n| DigitalOcean App Platform, built from the repository | No | Always. App Platform builds the newest commit of its branch, and the reason says a promotion only works while that's still the commit you're promoting |\n\nThe conditions, for every row that reuses: staging ran the same commit of the service on the same kind of target, built for the same architecture, from the same build inputs (source, Dockerfile, build context, ecosystem, build command and start command), and recorded the image by digest. A release that predates digest-pinned images, or one whose connection can't read digests, has only a tag, so it builds again.\n\nA gateway, a catalog service and a service pinned to an existing image have nothing built from a repository, so there's nothing to reuse. If the target environment's release strategy is `canary`, a reused image is what the canary ramps.\n\n### The staging soak\n\nA promotion plan shows how long the source environment has run exactly the commits you're about to ship, and whether it ran them healthily. The Plan tab in the dashboard has it under Source environment, and `loomctl promote` prints it before the approve line:\n\n```text\nSoak: staging has run these commits for 2h30m, healthy\n```\n\nThe clock starts when the last of the commits was deployed to the source. Every service built from those commits is judged over that stretch, up to the last 24 hours, with the target environment's thresholds. A soak has no baseline to compare against, so only two of them count: the error ceiling (`error_rate`) and `min_requests`. The soak is healthy when every one of those services passes.\n\nUnverified means missing evidence. A soak is unverified when the source runs the commits but a service had too little traffic to judge, its cloud reports no metrics to Loomplane, or they've been running for less than a few minutes. A service that exceeded the error ceiling is evidence, so that's reported as not healthy and isn't unverified. If the source doesn't run the commits at all, the line says so and why.\n\nThe soak informs your decision and nothing else. It never blocks an approval.\n\n## Roll back an environment\n\n```bash\nloomctl rollback my-project --env production --reason \"checkout 500s after release\"\nloomctl approve \n```\n\nThe reason is required, up to 2,000 characters, and goes in the audit trail and in front of whoever approves. Before it plans, `loomctl rollback` prints which deployment it undoes and which it restores, with each repository's commits. In the dashboard, open the environment's newest deployment and choose Roll back.\n\nA rollback is a normal plan. A developer creates it, an admin approves it, it expires if nobody decides, and it shows up in `loomctl plans` beside everything else. What's different is what it contains.\n\n### What it restores\n\nThe previous release is the newest successful deployment of that environment that finished before the one you're undoing started. A rollback's own deployment counts, because it restored a state somebody approved. Cloud syncs and standalone catalog plans don't count, since they change where infrastructure runs and not the application.\n\nA release that an earlier rollback undid is skipped, and so is one whose rollback failed. Say production ran R1, then R2, then R3. Rolling back R3 restores R2. If R2's rollback had failed before R3 shipped, rolling back R3 skips R2 and restores R1. To go to a release that was skipped, promote or deploy it explicitly.\n\nThe rollback pins every repository to the commits that release deployed, all of them moving, and uses the manifest revision it deployed with. Services return to that release's image under the same rules as a promotion (the table above), except on DigitalOcean App Platform, where a rollback goes back to the App Platform deployment Loomplane recorded for that release. If there is no such deployment, it predates the record, it ran another commit, or the release you're undoing moved the service off App Platform, the plan has a problem and can't be approved.\n\n### What it leaves alone\n\nA rollback only reverts services' code and settings. It never deletes, replaces or reverts a data-bearing resource, so a database keeps the rows and the schema the bad release left it with.\n\nIn practice: an update or replacement of a service that holds no data goes back. Anything else the restore would have done stays as the bad release left it, and the plan lists it under Left in place with the reason. That covers every resource (a bucket, a cache, a database), a service the release created, a service it removed, and any service that runs a catalog recipe or a component with storage.\n\nIf a service you're restoring links to a resource the release you're undoing removed, the plan has a problem called `rollback-needs-resource`. A rollback never recreates a resource, so it can't bring that service back. Release a version that creates the resource instead.\n\nA rollback goes back all at once. It never ramps as a canary, even in an environment whose strategy is `canary`, and it arms no watch.\n\n### When it's refused\n\n| Situation | What you do |\n|---|---|\n| A deployment is running or paused in the environment | Wait for it, or cancel it |\n| The environment has no earlier successful release | Nothing to restore. Deploy or promote |\n| The current release is a rollback | Deploy or promote to move forward. Rolling a rollback back would only bring back the release it undid |\n| The current release is a rollback that failed | Retry that rollback deployment, which finishes the move it was approved for |\n| The newest deployment's canary already returned to the baseline | Nothing to roll back |\n| A canary's revert or promotion failed | Fix the traffic split from the deployment, then roll back |\n| You named a deployment that isn't the newest | Roll back the newest first. Naming an older one would undo every release after it |\n| A release still holds a route handoff | Finish the handoff. The rollback waits for it like any other plan |\n\n## Watch a release after it deploys\n\nA canary judges a release while it ramps. The post-deploy watch judges it afterward, from the same cloud monitoring and with the same thresholds, and rolls it back if a service breaches them.\n\n### Turn it on\n\nThe watch is a setting of the environment's `release` block in `loomplane.yaml`:\n\n```yaml\nenvironments:\n production:\n release:\n strategy: direct\n watch: 30m\n thresholds:\n error_rate: 1%\n```\n\n`watch` is a duration in whole minutes, up to `24h`. Leave it out and a `canary` or `blue_green` environment is watched for 15 minutes while a `direct` one isn't watched at all. `watch: \"0\"` turns it off. The plan pins the watch with the rest of the release block, so changing it gives you a new revision to approve. An environment with no `release` block deploys exactly as it always has: no watch is armed.\n\n### What gets watched\n\nThe watch starts when a deployment finishes successfully, and covers the services that release created, updated or replaced. It skips the services a canary ramped, because the canary already judged them. It isn't armed for a rollback, a Cloud sync, a standalone catalog plan, a failed deployment, a canary that didn't promote, or a release that changed no service.\n\nA service can be watched when its cloud reports both requests and errors to Loomplane, which today means Cloud Run, ECS Fargate, Azure Container Apps and Render (the Requests and 5xx columns in the [canary table](/docs/concepts/canary-releases#where-canaries-run)). Services on your own servers and clusters report to your own monitoring, which Loomplane doesn't read. Vercel and DigitalOcean report nothing it can use. Each service the watch can't judge is listed with the reason, and it leaves the release unverified. If none of the changed services can be watched, the watch settles as inconclusive straight away.\n\nThe first reading comes about four minutes after the release finishes, because cloud monitoring reports a few minutes late. After that the watch checks every minute. It reads the service's health since the release finished and compares it with the same length of time before the deployment started. A service the release created or moved has no history, so it's judged on the thresholds alone.\n\n| Status | Meaning |\n|---|---|\n| `watching` | The window is still open or the readings aren't decisive yet |\n| `passed` | Every watched service passed through the whole window |\n| `inconclusive` | The watch couldn't decide by 15 minutes after its window ended, usually from too little traffic. The release is unverified and nothing is rolled back |\n| `superseded` | A newer release replaced this one before the watch finished |\n| `rolling_back` | A service breached, and the rollback is being planned, approved or deployed |\n| `rolled_back` | The rollback deployment succeeded |\n| `rollback_blocked` | The rollback couldn't go ahead on its own, and the watch says why |\n| `rollback_failed` | The rollback deployment failed, was cancelled or never started |\n\nA breach doesn't wait for the window to end. One failing service is enough.\n\nUnverified means missing evidence, and it never goes back to false. A release is unverified when a changed service wasn't watched, when the watch settled inconclusive, or when a newer release superseded the watch before it could judge. The release may well be fine, but nobody has the readings to say so, and that's worth a look from you.\n\nA newer release supersedes the watch if it starts while the watch is open, or if it changes a service the watch is judging. The watch stops and settles `superseded`. It doesn't roll back, because rolling back the older release would undo the newer one too. The same holds once a rollback is planned: if you plan the environment again before it deploys, or a newer release deploys while the rollback waits behind a Cloud sync, the rollback deploys nothing and the watch settles `superseded`.\n\n### Automatic rollback\n\nWhen a service breaches, Loomplane plans the rollback of that release, using the same rules as a manual one, and approves it itself. The plan's reason names the service and what it measured. The plan says it was started by Loomplane automation, and so does every audit entry it makes: the breach (`release_watch.breach`), the approval (`plan.approve`, marked automatic) and the settled watch (`release_watch.settle`).\n\nThis is the one place a plan is approved without a person, and the rules around it are narrow. Loomplane automation holds a role that can read a project, create deployments and approve them, but the planning service lets it create and approve only a rollback that a watch started. Every other plan, and every promotion or manual rollback, refuses it, and no session or API key ever acts as it. If Loomplane automation can't create or approve the rollback, for example because its role assignment failed, the watch settles `rollback_blocked`, and the rollback plan, if there is one, stays ready for a person to approve.\n\nTo turn automatic rollback off, turn the watch off for that environment in the manifest: set `release.watch: \"0\"`, use the `direct` strategy without a `watch`, or leave out the `release` block. Nothing is watched there, so nothing rolls back on its own, and every release there is unverified. The change goes through a plan like any other, so it's reviewed. Removing the `loomplane-automation` assignment in Warden doesn't last: Loomplane writes it back the next time it starts.\n\nPlanning can also refuse for good, for the reasons in [When it's refused](#when-its-refused), and then the watch settles `rollback_blocked` with the reason. If the rollback plan never finishes planning, or its deployment never starts within an hour, the watch gives up and settles `rollback_failed`. You can find the plan from the watch, and from there you decide.\n\n## Where to see it\n\nOn a deployment's page, a Release watch panel shows the status, each watched service's verdict, the services it couldn't watch and why, and the rollback plan if it breached. Roll back sits beside Retry on a deployment that has finished, is the newest in its environment and isn't a rollback itself. The dialog shows what the rollback restores and asks for a reason, and a refusal from the server appears there in plain text.\n\nFrom a terminal, `loomctl deployment ` prints a `Watch:` section, and `loomctl promote` prints the `Soak:` line. An agent reads the watch with `get_release_watch`, and can plan a rollback with `create_rollback` when you start the MCP server with `--allow-deploy`. A person still approves it. See [loomctl](/docs/reference/loomctl), [MCP server](/docs/agents/mcp-server) and the [HTTP API](/docs/reference/http-api)." }, { "path": "concepts/repository-discovery", @@ -343,7 +343,7 @@ "title": "GitLab repositories", "description": "Register a GitLab OAuth application once, sign in from Integrations, and re-analyze projects when their default branch moves.", "url": "https://www.loomplane.com/docs/guides/gitlab-repositories", - "text": "Loomplane reads public projects on gitlab.com with no setup. A source is written `gitlab.com//`, and you can paste the project's URL wherever Loomplane asks for one. Nested groups work, and so does a self-managed GitLab on version 17.0 or newer. An older version connects too, with a warning on its card.\n\nTo read private projects you register an OAuth application once for the whole Loomplane instance, and your organization's owners and admins sign in to it from Integrations.\n\n## Register the application on gitlab.com\n\nIn GitLab, open **Preferences**, then **Applications**, then **Add new application**.\n\n| Setting | Value |\n|---|---|\n| Name | Anything, such as Loomplane |\n| Redirect URI | `/integrations/gitlab/callback` |\n| Confidential | On |\n| Scopes | `read_api`, and nothing else |\n\nSave it and copy the Application ID and the Secret. GitLab shows the secret once. `config.yaml` already has a `gitlab:` block wired to environment variables, so set these for both `loomplane` and `loomplane-worker`, and keep the secret out of any file you commit:\n\n```sh\nLOOMPLANE_GITLAB_CLIENT_ID=\"\"\nLOOMPLANE_GITLAB_CLIENT_SECRET=\"\"\n```\n\nOn Helm, set `gitlab.clientID` in your values and `secrets.gitlabClientSecret`, or put `LOOMPLANE_GITLAB_CLIENT_SECRET` in the Secret named by `secrets.existingSecret`. You can also put a `gitlab:` block with `client_id` and `client_secret` in `config.local.yaml`. Set both or neither. Loomplane refuses to start with only one. With neither, public projects still work and private ones can't be read.\n\nYou can set the application in the instance console instead, under **Integrations** at `/__console/@integrations`, if you're a platform owner or admin. It's live in `loomplane` at once and in `loomplane-worker` within 30 seconds, with no restart, and **Check with GitLab** tells you whether GitLab knows the Application ID and Secret before anyone signs in. The variables win while they're set. GitLab sign-ins belong to their application, so with a different one each GitLab connection made with the old one has to sign in again.\n\n## A self-managed GitLab\n\nThe operator can list it under `gitlab.hosts`, with an application registered on that GitLab the same way as above:\n\n```yaml\ngitlab:\n hosts:\n - web_url: https://git.example.com\n client_id: \"\"\n client_secret: \"\"\n```\n\nA list can't come from one environment variable, so `gitlab.hosts` has none. Put it in a `gitlab:` block in `config.local.yaml`. `web_url` has no path and may be http or https. Loomplane trusts these hosts, so a GitLab on your private network works. Links Loomplane builds to a repository, such as **Open on git.example.com**, always use https, so a GitLab served over plain http gets https links that only open if the host answers https too. The instance console's **Integrations** section lists these hosts and can check their applications with **Check with GitLab**, but you change them only here.\n\nAn organization can add its own instead. Someone who may connect repositories opens **Integrations**, chooses **Add a self-managed GitLab**, and enters the address, an Application ID and a Secret. The dialog shows the callback URL to use. Loomplane is stricter about these:\n\n- The address has to be https and a host name of its own. A GitLab served under a path is refused.\n- Loomplane won't call private, loopback or link-local addresses for it, and it won't follow a redirect to http or to another host.\n\nAn operator who doesn't want organizations adding their own sets `gitlab.allow_organization_hosts: false`. It defaults to true. The full list of settings, with their environment variables, is:\n\n| Setting | Variable |\n|---|---|\n| `gitlab.api_url` (gitlab.com's API, `https://gitlab.com` by default) | `LOOMPLANE_GITLAB_API_URL` |\n| `gitlab.client_id` | `LOOMPLANE_GITLAB_CLIENT_ID` |\n| `gitlab.client_secret` | `LOOMPLANE_GITLAB_CLIENT_SECRET` |\n| `gitlab.allow_organization_hosts` | `LOOMPLANE_GITLAB_ALLOW_ORGANIZATION_HOSTS` |\n| `gitlab.webhook_url` | `LOOMPLANE_GITLAB_WEBHOOK_URL` |\n| `gitlab.hosts` | None. Use `config.local.yaml` |\n\n## Sign in\n\nAn owner or admin opens **Integrations**, finds the GitLab card and signs in to gitlab.com or to a self-managed GitLab. GitLab asks them to approve the application and sends them back.\n\nLoomplane acts as the GitLab user who signed in, so it can read whatever that user can. Create a dedicated GitLab user with Reporter access on the groups Loomplane should read, and sign in as that user. Once it's connected, any project in the organization whose repository that user can read is analyzed with access to it.\n\nLoomplane seals the tokens in its vault, and GitLab rotates them every two hours. If GitLab refuses to renew one, the card shows **Sign in again**, and signing in again replaces the old sign-in. Disconnecting removes the connection and revokes the sign-in at GitLab.\n\n## Re-analyze on push\n\nEach connection gets a webhook URL and a secret that proves a delivery came from your GitLab. The URL is `/api/v1/gitlab/webhook/`, where `gitlab.webhook_url` (`LOOMPLANE_GITLAB_WEBHOOK_URL`) defaults to your `public_url`. Set it only when GitLab reaches Loomplane at a different address than people do.\n\n\nIn GitLab, open **Settings**, then **Webhooks**, on the project or on its group. Paste the URL from the connection's **Webhook** panel on Integrations and tick **Push events**. Group webhooks need GitLab Premium on gitlab.com.\n\n\nSet the secret. Which way it goes depends on your GitLab version.\n\nOn GitLab 19 and newer, GitLab makes the signing token. Choose **Generate signing token** in GitLab and copy it, because GitLab shows it once. Paste it into **Paste GitLab's signing token** on the panel and choose **Save signing token**. Loomplane keeps it and checks every delivery's signature with it.\n\nOn older versions, choose **Create secret** on the panel. Copy the secret token it shows, once, and paste it into GitLab's **Secret token** field.\n\n\nPush a change to the default branch. **Analyses**, under **Settings** then **Source** on the project, should show another analysis finishing at the new commit, with `created_by` set to `gitlab-push`.\n\n\nOnly pushes to a project's default branch re-analyze, and only in the organization that owns the connection. A push to any other branch, a tag or a deleted branch does nothing.\n\n## Deploying\n\nEvery deployment target but two builds from the archive Loomplane fetched. Render and DigitalOcean App Platform build from the repository themselves, through their own GitLab connection, so connect GitLab in Render's or DigitalOcean's dashboard first. They build gitlab.com sources only. A source on a self-managed GitLab can't deploy to either, and the plan reports it." + "text": "Loomplane reads public projects on gitlab.com with no setup. A source is written `gitlab.com//`, and you can paste the project's URL wherever Loomplane asks for one. Nested groups work, and so does a self-managed GitLab on version 17.0 or newer. An older version connects too, with a warning on its card.\n\nTo read private projects you register an OAuth application once for the whole Loomplane instance, and your organization's owners and admins sign in to it from Integrations.\n\n## Register the application on gitlab.com\n\nIn GitLab, open **Preferences**, then **Applications**, then **Add new application**.\n\n| Setting | Value |\n|---|---|\n| Name | Anything, such as Loomplane |\n| Redirect URI | `/integrations/gitlab/callback` |\n| Confidential | On |\n| Scopes | `read_api`, and nothing else |\n\nSave it and copy the Application ID and the Secret. GitLab shows the secret once. `config.yaml` already has a `gitlab:` block wired to environment variables, so set these for both `loomplane` and `loomplane-worker`, and keep the secret out of any file you commit:\n\n```sh\nLOOMPLANE_GITLAB_CLIENT_ID=\"\"\nLOOMPLANE_GITLAB_CLIENT_SECRET=\"\"\n```\n\nOn Helm, set `gitlab.clientID` in your values and `secrets.gitlabClientSecret`, or put `LOOMPLANE_GITLAB_CLIENT_SECRET` in the Secret named by `secrets.existingSecret`. You can also put a `gitlab:` block with `client_id` and `client_secret` in `config.local.yaml`. Set both or neither. Loomplane refuses to start with only one. With neither, public projects still work and private ones can't be read.\n\nYou can set the application in the instance console instead, under **Integrations** at `/__console/@integrations`, if you're a platform owner or admin. It's live in `loomplane` at once and in `loomplane-worker` within 30 seconds, with no restart, and **Check with GitLab** tells you whether GitLab knows the Application ID and Secret before anyone signs in. The variables win while they're set. GitLab sign-ins belong to their application, so with a different one each GitLab connection made with the old one has to sign in again.\n\n## A self-managed GitLab\n\nThe operator can list it under `gitlab.hosts`, with an application registered on that GitLab the same way as above:\n\n```yaml\ngitlab:\n hosts:\n - web_url: https://git.example.com\n client_id: \"\"\n client_secret: \"\"\n```\n\nA list can't come from one environment variable, so `gitlab.hosts` has none. Put it in a `gitlab:` block in `config.local.yaml`. `web_url` has no path and may be http or https. Loomplane trusts these hosts, so a GitLab on your private network works. Links Loomplane builds to a repository, such as **Open on git.example.com**, always use https, so a GitLab served over plain http gets https links that only open if the host answers https too. The instance console's **Integrations** section lists these hosts and can check their applications with **Check with GitLab**, but you change them only here.\n\nAn organization can add its own instead. Someone who may connect repositories opens **Integrations**, chooses **Add a self-managed GitLab**, and enters the address, an Application ID and a Secret. The dialog shows the callback URL to use. Loomplane is stricter about these:\n\n- The address has to be https and a host name of its own. A GitLab served under a path is refused.\n- Loomplane won't call private, loopback or link-local addresses for it, and it won't follow a redirect to http or to another host.\n\nAn operator who doesn't want organizations adding their own sets `gitlab.allow_organization_hosts: false`. It defaults to true. The full list of settings, with their environment variables, is:\n\n| Setting | Variable |\n|---|---|\n| `gitlab.api_url` (gitlab.com's API, `https://gitlab.com` by default) | `LOOMPLANE_GITLAB_API_URL` |\n| `gitlab.client_id` | `LOOMPLANE_GITLAB_CLIENT_ID` |\n| `gitlab.client_secret` | `LOOMPLANE_GITLAB_CLIENT_SECRET` |\n| `gitlab.allow_organization_hosts` | `LOOMPLANE_GITLAB_ALLOW_ORGANIZATION_HOSTS` |\n| `gitlab.webhook_url` | `LOOMPLANE_GITLAB_WEBHOOK_URL` |\n| `gitlab.hosts` | None. Use `config.local.yaml` |\n\n## Sign in\n\nAn owner or admin opens **Integrations**, finds the GitLab card and signs in to gitlab.com or to a self-managed GitLab. GitLab asks them to approve the application and sends them back.\n\nLoomplane acts as the GitLab user who signed in, so it can read whatever that user can. Create a dedicated GitLab user with Reporter access on the groups Loomplane should read, and sign in as that user. Once it's connected, any project in the organization whose repository that user can read is analyzed with access to it.\n\nLoomplane seals the tokens in its vault, and GitLab rotates them every two hours. If GitLab refuses to renew one, the card shows **Sign in again**, and signing in again replaces the old sign-in. Disconnecting removes the connection and revokes the sign-in at GitLab.\n\n## Re-analyze on push\n\nEach connection gets a webhook URL and a secret that proves a delivery came from your GitLab. The URL is `/api/v1/gitlab/webhook/`, where `gitlab.webhook_url` (`LOOMPLANE_GITLAB_WEBHOOK_URL`) defaults to your `public_url`. Set it only when GitLab reaches Loomplane at a different address than people do.\n\n\nIn GitLab, open **Settings**, then **Webhooks**, on the project or on its group. Paste the URL from the connection's **Webhook** panel on Integrations and tick **Push events**. Group webhooks need GitLab Premium on gitlab.com.\n\n\nSet the secret. Which way it goes depends on your GitLab version.\n\nOn GitLab 19 and newer, GitLab makes the signing token. Choose **Generate signing token** in GitLab and copy it, because GitLab shows it once. Paste it into **Paste GitLab's signing token** on the panel and choose **Save signing token**. Loomplane keeps it and checks every delivery's signature with it.\n\nOn older versions, choose **Create secret** on the panel. Copy the secret token it shows, once, and paste it into GitLab's **Secret token** field.\n\n\nPush a change to the default branch. **Analyses**, under **Settings** then **Source** on the project, should show another analysis finishing at the new commit, with `created_by` set to `gitlab-push`.\n\n\nOnly pushes to a project's default branch re-analyze, and only in the organization that owns the connection. A push to any other branch, a tag or a deleted branch does nothing.\n\n## Deploying\n\nEvery deployment target builds from the archive Loomplane fetched, with two exceptions. Render builds from the repository itself, through its own GitLab connection. So does DigitalOcean App Platform for a static site, for a service with no Dockerfile, and for any service while there's no runner pool and DigitalOcean registry for Loomplane to build with (see [DigitalOcean](/docs/clouds/digitalocean)). Connect GitLab in Render's or DigitalOcean's dashboard first for those. They build gitlab.com sources only. A source on a self-managed GitLab can't deploy that way, and the plan reports it." }, { "path": "guides/notifications-and-webhooks", @@ -364,7 +364,7 @@ "title": "How it works", "description": "The path from a repository to a running service, and what Loomplane checks along the way.", "url": "https://www.loomplane.com/docs/how-it-works", - "text": "Every deployment follows the same seven steps. Once you know them the rest of these docs are easier to read, since each page takes one step and goes deep.\n\n## 1. Analyze\n\nYou add one or more repositories to a project. A worker downloads a tarball of each at one commit and reads it. Nothing from the repository runs: no build scripts, no package managers. The worker finds services, the packages they share, and the databases and caches they need, and it records the file and line behind every finding. See [Repository discovery](/docs/concepts/repository-discovery).\n\n## 2. Draft the manifest\n\nFrom that analysis Loomplane drafts a `loomplane.yaml`. You edit it in the dashboard or with `loomctl manifest save`, and every save is a new revision. This file says what deploys, where, and what each service needs. See [The manifest](/docs/concepts/the-manifest).\n\n## 3. Connect clouds\n\nUnder Integrations you add credentials for the clouds your manifest names. Loomplane checks each with its cloud first and tells you which permissions are missing. Credentials live in Vault, encrypted with a key derived from your secret key. See [Clouds](/docs/clouds).\n\n## 4. Plan\n\nA plan is for one environment. It lists every action a deployment would take, in order, with the problems that would block it and the warnings worth reading. Planning never touches a cloud. A plan names the manifest revision and the exact commit of every repository it moves.\n\n## 5. Approve\n\nA developer can plan anything. Only an admin's approval changes a cloud, and the approval names the plan's revision. If the world changed since you looked, the plan comes back stale and nothing happens. See [Plans and approvals](/docs/concepts/plans-and-approvals).\n\n## 6. Deploy\n\nApproval starts a durable workflow. It stores one source tarball per repository, provisions resources, builds each service on its cloud's own builder (Cloud Build, CodeBuild, Vercel, Render, App Platform or ACR Tasks), deploys it, and checks that public services answer. If a step fails, you retry from that step. See [Deployments and recovery](/docs/concepts/deployments-and-recovery).\n\n## 7. Watch for drift\n\nOn a schedule (every 30 minutes by default), Loomplane compares everything it deployed with what each cloud has live. It records differences and changes nothing. The next plan, approved like any other, puts things back. See [Drift](/docs/concepts/drift).\n\n## Where each piece runs\n\nLoomplane is two processes over one PostgreSQL database. `loomplane` serves the API and dashboard, runs the deployment workflows and records everything. `loomplane-worker` analyzes repositories, in a separate process that holds no sessions and serves nothing but health checks.\n\nYour builds run on your clouds' builders, in your accounts. Gateways and provider plugins run on your infrastructure. Application traffic goes straight to your services." + "text": "Every deployment follows the same seven steps. Once you know them the rest of these docs are easier to read, since each page takes one step and goes deep.\n\n## 1. Analyze\n\nYou add one or more repositories to a project. A worker downloads a tarball of each at one commit and reads it. Nothing from the repository runs: no build scripts, no package managers. The worker finds services, the packages they share, and the databases and caches they need, and it records the file and line behind every finding. See [Repository discovery](/docs/concepts/repository-discovery).\n\n## 2. Draft the manifest\n\nFrom that analysis Loomplane drafts a `loomplane.yaml`. You edit it in the dashboard or with `loomctl manifest save`, and every save is a new revision. This file says what deploys, where, and what each service needs. See [The manifest](/docs/concepts/the-manifest).\n\n## 3. Connect clouds\n\nUnder Integrations you add credentials for the clouds your manifest names. Loomplane checks each with its cloud first and tells you which permissions are missing. Credentials live in Vault, encrypted with a key derived from your secret key. See [Clouds](/docs/clouds).\n\n## 4. Plan\n\nA plan is for one environment. It lists every action a deployment would take, in order, with the problems that would block it and the warnings worth reading. Planning never touches a cloud. A plan names the manifest revision and the exact commit of every repository it moves.\n\n## 5. Approve\n\nA developer can plan anything. Only an admin's approval changes a cloud, and the approval names the plan's revision. If the world changed since you looked, the plan comes back stale and nothing happens. See [Plans and approvals](/docs/concepts/plans-and-approvals).\n\n## 6. Deploy\n\nApproval starts a durable workflow. It stores one source tarball per repository, provisions resources, builds each service on its cloud's own builder (Cloud Build, CodeBuild, Vercel, Render, App Platform or ACR Tasks) or on a runner pool, deploys it, and checks that public services answer. If a step fails, you retry from that step. See [Deployments and recovery](/docs/concepts/deployments-and-recovery).\n\n## 7. Watch for drift\n\nOn a schedule (every 30 minutes by default), Loomplane compares everything it deployed with what each cloud has live. It records differences and changes nothing. The next plan, approved like any other, puts things back. See [Drift](/docs/concepts/drift).\n\n## Where each piece runs\n\nLoomplane is two processes over one PostgreSQL database. `loomplane` serves the API and dashboard, runs the deployment workflows and records everything. `loomplane-worker` analyzes repositories, in a separate process that holds no sessions and serves nothing but health checks.\n\nYour builds run on your clouds' builders, in your accounts. Gateways and provider plugins run on your infrastructure. Application traffic goes straight to your services." }, { "path": "operations/backing-up-loomplane", diff --git a/internal/clouds/digitalocean/digitalocean.go b/internal/clouds/digitalocean/digitalocean.go index b28ce23b..8f8a6a44 100644 --- a/internal/clouds/digitalocean/digitalocean.go +++ b/internal/clouds/digitalocean/digitalocean.go @@ -283,6 +283,10 @@ type Component struct { // GitLab is the source of a gitlab.com project. At most one of GitHub // and GitLab is set. GitLab *GitLabSource `json:"gitlab,omitempty"` + // Image is a built image App Platform runs instead of building, for a + // service or worker; never with GitHub or GitLab, and never for a + // static site, which App Platform only builds from a repository. + Image *ImageSource `json:"image,omitempty"` // SourceDir and DockerfilePath are paths from the repository's root. SourceDir string `json:"source_dir,omitempty"` DockerfilePath string `json:"dockerfile_path,omitempty"` @@ -299,6 +303,23 @@ type Component struct { Envs []Env `json:"envs,omitempty"` } +// RegistryDOCR is the image source registry type of DigitalOcean's own +// container registry. +const RegistryDOCR = "DOCR" + +// ImageSource is an image in the app's own account's container registry, +// pinned by digest, so App Platform runs exactly the image that was built. +// Per the app spec reference +// (docs.digitalocean.com/products/app-platform/reference/app-spec/, read +// 2026-11-24): Registry is left empty for DOCR but names the registry when +// the account has several, and a digest excludes a tag. +type ImageSource struct { + RegistryType string `json:"registry_type"` + Registry string `json:"registry,omitempty"` + Repository string `json:"repository"` + Digest string `json:"digest"` +} + // GitHubSource is a branch of a GitHub repository, as owner/name. // DeployOnPush is always false here: Loomplane deploys what was approved, // not whatever was pushed last. @@ -438,7 +459,7 @@ func (c *Client) CreateApp(ctx context.Context, token string, spec AppSpec) (*Ap if err := c.do(ctx, token, http.MethodPost, "/v2/apps", nil, map[string]any{"spec": spec}, &out); err != nil { var ae *APIError if errors.As(err, &ae) && strings.Contains(strings.ToLower(ae.Message), "github") { - return nil, fmt.Errorf("%w. App Platform builds from your repository through DigitalOcean's own GitHub connection: give DigitalOcean access to it in the control panel, under Settings, GitHub", err) + return nil, fmt.Errorf("%w. App Platform builds from your repository through DigitalOcean's own GitHub connection: give DigitalOcean access to it in the control panel, under Settings, GitHub. DigitalOcean's API can't set that up. For a service with a Dockerfile or a Go module, Loomplane can build the image instead and App Platform needs no access: add a runner pool and the account's container registry, as a registry under Integrations, then plan again", err) } return nil, err } @@ -570,6 +591,45 @@ func sameCommit(a, b string) bool { // deployment before it goes live. A live deployment must have reported a // matching commit for every component. func (c *Client) WaitDeployment(ctx context.Context, token, appID, id, commit string) (*Deployment, error) { + return c.waitDeployment(ctx, token, appID, id, func(d *Deployment, live bool) error { + for _, comp := range d.components() { + if (live || comp.SourceCommitHash != "") && !sameCommit(comp.SourceCommitHash, commit) { + return &CommitMismatchError{Deployment: d, Component: comp.Name, Built: comp.SourceCommitHash, Want: commit} + } + } + return nil + }) +} + +// WaitImageDeployment polls a deployment of an app that runs an image +// until it's live, and fails if it doesn't get there. Nothing is built +// from a commit, so instead the live deployment's spec must run digest in +// every service and worker. +func (c *Client) WaitImageDeployment(ctx context.Context, token, appID, id, digest string) (*Deployment, error) { + return c.waitDeployment(ctx, token, appID, id, func(d *Deployment, live bool) error { + if !live { + return nil + } + var spec AppSpec + if err := json.Unmarshal(d.Spec, &spec); err != nil { + return fmt.Errorf("read app platform deployment %s's spec: %w", id, err) + } + comps := append(append([]Component{}, spec.Services...), spec.Workers...) + if len(comps) == 0 || len(spec.StaticSites) > 0 { + return fmt.Errorf("app platform deployment %s isn't the image Loomplane built", id) + } + for _, comp := range comps { + if comp.Image == nil || comp.Image.Digest != digest { + return fmt.Errorf("app platform deployment %s runs %s from something other than the image Loomplane built, %s", id, comp.Name, digest) + } + } + return nil + }) +} + +// waitDeployment polls a deployment until it's live, calling check on each +// reading, with live set once it is. An error from check stops the wait. +func (c *Client) waitDeployment(ctx context.Context, token, appID, id string, check func(d *Deployment, live bool) error) (*Deployment, error) { if appID == "" || id == "" { return nil, errors.New("app platform deployment polling requires app and deployment IDs") } @@ -578,18 +638,11 @@ func (c *Client) WaitDeployment(ctx context.Context, token, appID, id, commit st if err != nil { return nil, err } - for _, comp := range d.components() { - if comp.SourceCommitHash != "" && !sameCommit(comp.SourceCommitHash, commit) { - return d, &CommitMismatchError{Deployment: d, Component: comp.Name, Built: comp.SourceCommitHash, Want: commit} - } + if err := check(d, d.Phase == PhaseActive); err != nil { + return d, err } switch d.Phase { case PhaseActive: - for _, comp := range d.components() { - if !sameCommit(comp.SourceCommitHash, commit) { - return d, &CommitMismatchError{Deployment: d, Component: comp.Name, Built: comp.SourceCommitHash, Want: commit} - } - } return d, nil case PhaseError, PhaseCanceled, PhaseSuperseded: return d, fmt.Errorf("app platform deployment %s: %s. Its build and deploy logs are on the app's Activity tab in DigitalOcean", id, strings.ToLower(d.Phase)) diff --git a/internal/deployments/digitalocean.go b/internal/deployments/digitalocean.go index d7b991cd..13a1b36f 100644 --- a/internal/deployments/digitalocean.go +++ b/internal/deployments/digitalocean.go @@ -30,18 +30,28 @@ import ( // PostgreSQL, MySQL and Valkey, which speaks the Redis protocol. // // Each service and environment is an App Platform app of its own, named -// the way a Render service is, built by App Platform from the repository -// through DigitalOcean's GitHub connection, with deploy on push off. +// the way a Render service is. // -// App Platform builds the newest commit of a branch and can't be told -// which one to build. So Loomplane points it at the branch the project -// reads, starts the deployment itself, and checks the commit App Platform -// reports for every component against the one the plan approved. A -// different commit is cancelled before it goes live. If it somehow went -// live, the app is rolled back to what ran before, or deleted when -// nothing approved ever ran there. +// A service the plan gives a build target is built by Loomplane's builder +// from the approved commit and pushed to the account's container registry, +// and the app runs that image by digest. DigitalOcean never reads the +// repository, so it needs no GitHub or GitLab connection. +// +// The rest, static sites and services App Platform builds with its own +// buildpacks, App Platform builds from the repository through +// DigitalOcean's GitHub or GitLab connection, with deploy on push off. It +// builds the newest commit of a branch and can't be told which one to +// build. So Loomplane points it at the branch the project reads, starts +// the deployment itself, and checks the commit App Platform reports for +// every component against the one the plan approved. A different commit +// is cancelled before it goes live. If it somehow went live, the app is +// rolled back to what ran before, or deleted when nothing approved ever +// ran there. type DigitalOcean struct { Client *digitalocean.Client + // Builder builds the image of a service with a build target. Nil + // refuses those services. + Builder *ImageBuilder // Resolve looks a host up in public DNS, past this machine's own // cache. Nil asks Cloudflare's and Google's resolvers. Resolve func(ctx context.Context, host string) error @@ -83,8 +93,11 @@ const ( ) type doState struct { - AppID string `json:"app_id,omitempty"` - DeploymentID string `json:"deployment_id,omitempty"` + // Image is the build of a service that runs an image, kept so a retry + // picks the build up where it stopped. + Image ImageArtifact `json:"image,omitzero"` + AppID string `json:"app_id,omitempty"` + DeploymentID string `json:"deployment_id,omitempty"` // Previous is the deployment that was live before this one, to roll // back to. Previous string `json:"previous,omitempty"` @@ -164,6 +177,15 @@ func (d *DigitalOcean) Apply(ctx context.Context, job *Job) (_ *Outcome, err err save() }) + if job.CommitSHA == "" { + return nil, errors.New("app platform deploys a commit, and the deployment has none for this service") + } + if cfg.Artifact != nil && cfg.Artifact.Revision != "" && job.Binding != nil && job.Binding.ExternalID != "" { + return d.rollBack(ctx, token, job, cfg, &state, save) + } + if cfg.BuildTarget != nil { + return d.applyImage(ctx, token, job, cfg, &state, save) + } repo, err := repositoryFor(job) if err != nil { return nil, err @@ -171,14 +193,8 @@ func (d *DigitalOcean) Apply(ctx context.Context, job *Job) (_ *Outcome, err err if hostErr := planning.GitBuildable("digitalocean", repo); hostErr != nil { return nil, hostErr } - if job.CommitSHA == "" { - return nil, errors.New("app platform deploys a commit, and the deployment has none for this service") - } - if cfg.Artifact != nil && cfg.Artifact.Revision != "" && job.Binding != nil && job.Binding.ExternalID != "" { - return d.rollBack(ctx, token, job, cfg, &state, save) - } branch := doBranchFor(job) - spec := doAppSpec(job, cfg, repo, branch) + spec := doAppSpec(job, cfg, doSource{repo: repo, branch: branch}) if state.DeploymentID == "" { job.Progress(StepDeploying, "Setting up the App Platform app") @@ -234,6 +250,144 @@ func (d *DigitalOcean) Apply(ctx context.Context, job *Job) (_ *Outcome, err err return &Outcome{ExternalID: app.ID, URL: url, Revision: dep.ID}, nil } +// applyImage builds the service's image from the approved commit with +// Loomplane's builder, pushes it to the account's container registry, and +// deploys the app on it by digest. A retry resumes the build, or waits on +// the deployment it already started. +func (d *DigitalOcean) applyImage(ctx context.Context, token string, job *Job, cfg *planning.ServiceConfig, state *doState, save func()) (*Outcome, error) { + if d.Builder == nil { + return nil, errors.New("this server can't build images for App Platform") + } + // App Platform pulls only from its own account's registries. The + // reviewed registry is checked before anything builds, and the image's + // own registry once it has one. + names, err := d.Client.RegistryNames(ctx, token) + if err != nil { + return nil, fmt.Errorf("list the DigitalOcean account's container registries: %w", err) + } + inAccount := func(name string) error { + if !slices.Contains(names, name) { + return fmt.Errorf("app platform pulls images only from its own account's container registry, and %s isn't in the account %s runs in. Choose the registry connection made from that account", name, job.Action.Name) + } + return nil + } + if reviewed := cfg.BuildTarget.RegistrySettings["repository"]; reviewed != "" { + if accountErr := inAccount(reviewed); accountErr != nil { + return nil, accountErr + } + } + if state.DeploymentID == "" || state.Image.Digest == "" { + state.DeploymentID = "" + checkpoint := func() error { + data, marshalErr := json.Marshal(state) + if marshalErr != nil { + return marshalErr + } + return job.Checkpoint(data) + } + if _, err = d.Builder.Build(ctx, job, &state.Image, checkpoint); err != nil { + return nil, err + } + } + src, registryName, err := doImageSource(state.Image.Reference, state.Image.Digest) + if err != nil { + return nil, err + } + if accountErr := inAccount(registryName); accountErr != nil { + return nil, accountErr + } + if len(names) > 1 { + src.Registry = registryName + } + spec := doAppSpec(job, cfg, doSource{image: src}) + + if state.DeploymentID == "" { + job.Progress(StepDeploying, "Setting up the App Platform app") + aerr := d.ensureApp(ctx, token, spec, func(ctx context.Context, app *digitalocean.App) error { + state.AppID = app.ID + if checkpointErr := checkpointCloudIdentity(job, *state); checkpointErr != nil { + return checkpointErr + } + if app.ActiveDeployment != nil { + state.Previous = app.ActiveDeployment.ID + } + if proofErr := prepareDORollbackProof(ctx, job, spec, app); proofErr != nil { + return proofErr + } + dep, derr := d.Client.CreateDeployment(ctx, token, app.ID) + if derr != nil { + return fmt.Errorf("deploy %s on app platform: %w", spec.Name, derr) + } + state.DeploymentID = dep.ID + save() + return nil + }) + if aerr != nil { + return nil, aerr + } + } + job.Progress(StepDeploying, "Deploying "+state.Image.Reference+" on App Platform") + job.Collector(state.DeploymentID, job.LogAttempt()).RecordState(ctx, "", "unavailable", "App Platform's deploy logs are on the app's Activity tab in DigitalOcean. Progress remains available.") + dep, err := d.Client.WaitImageDeployment(ctx, token, state.AppID, state.DeploymentID, src.Digest) + if err != nil { + return nil, err + } + app, err := d.Client.GetApp(ctx, token, state.AppID) + if err != nil { + return nil, err + } + url := doAddress(cfg, app) + if dnsErr := d.waitForDNS(ctx, job, url); dnsErr != nil { + return nil, dnsErr + } + if err := d.keepRollbackProof(ctx, token, job, spec, app.ID, dep.ID); err != nil { + return nil, err + } + return &Outcome{ExternalID: app.ID, URL: url, Image: state.Image.Reference, Revision: dep.ID}, nil +} + +// doSource is where App Platform gets a component's code: a branch of a +// repository it builds, or an image Loomplane built. +type doSource struct { + repo, branch string + image *digitalocean.ImageSource +} + +// doSourceFor is the source of a service already deployed: the image its +// release ran, image, when the plan builds it, else its branch. +func doSourceFor(job *Job, cfg *planning.ServiceConfig, image string) (doSource, error) { + if cfg.BuildTarget != nil { + _, digest, _ := strings.Cut(image, "@") + src, _, err := doImageSource(image, digest) + return doSource{image: src}, err + } + repo, err := repositoryFor(job) + return doSource{repo: repo, branch: doBranchFor(job)}, err +} + +// doImageSource is the App Platform image source of reference, an image +// in DigitalOcean's container registry as the builder names it, by tag or +// digest, and the name of the registry it's in. Registry stays empty: App +// Platform wants it only when the account has more than one. +func doImageSource(reference, digest string) (*digitalocean.ImageSource, string, error) { + if !imageDigest.MatchString(digest) { + return nil, "", errNoDigest + } + rest, ok := strings.CutPrefix(reference, digitalocean.RegistryHost+"/") + if !ok { + return nil, "", fmt.Errorf("app platform pulls images only from DigitalOcean's container registry, not %s", reference) + } + rest, _, _ = strings.Cut(rest, "@") + if i := strings.LastIndex(rest, ":"); i > strings.LastIndex(rest, "/") { + rest = rest[:i] + } + registryName, repository, ok := strings.Cut(rest, "/") + if !ok || registryName == "" || repository == "" { + return nil, "", fmt.Errorf("%s doesn't name a registry and a repository", reference) + } + return &digitalocean.ImageSource{RegistryType: digitalocean.RegistryDOCR, Repository: repository, Digest: digest}, registryName, nil +} + // rollBack puts the app back on the deployment a rollback plan restores, // which App Platform still holds, so nothing builds. The rollback is a // deployment of its own, waited on and checked against the restored @@ -262,7 +416,16 @@ func (d *DigitalOcean) rollBack(ctx context.Context, token string, job *Job, cfg return nil, fmt.Errorf("roll %s back on app platform: %w", job.Action.Name, err) } } - dep, err := d.Client.WaitDeployment(ctx, token, app, state.DeploymentID, job.CommitSHA) + src, err := doSourceFor(job, cfg, cfg.Artifact.Reference) + if err != nil { + return nil, fmt.Errorf("roll %s back on app platform: %w", job.Action.Name, err) + } + var dep *digitalocean.Deployment + if src.image != nil { + dep, err = d.Client.WaitImageDeployment(ctx, token, app, state.DeploymentID, src.image.Digest) + } else { + dep, err = d.Client.WaitDeployment(ctx, token, app, state.DeploymentID, job.CommitSHA) + } if err != nil { return nil, fmt.Errorf("roll %s back on app platform: %w", job.Action.Name, err) } @@ -274,14 +437,14 @@ func (d *DigitalOcean) rollBack(ctx context.Context, token string, job *Job, cfg if dnsErr := d.waitForDNS(ctx, job, url); dnsErr != nil { return nil, dnsErr } - repo, err := repositoryFor(job) - if err != nil { + if err := d.keepRollbackProof(ctx, token, job, doAppSpec(job, cfg, src), app, dep.ID); err != nil { return nil, err } - if err := d.keepRollbackProof(ctx, token, job, doAppSpec(job, cfg, repo, doBranchFor(job)), app, dep.ID); err != nil { - return nil, err + out := &Outcome{ExternalID: live.ID, URL: url, Revision: dep.ID} + if src.image != nil { + out.Image = cfg.Artifact.Reference } - return &Outcome{ExternalID: live.ID, URL: url, Revision: dep.ID}, nil + return out, nil } // doPublicResolvers are asked directly, so a name looked up too early @@ -452,17 +615,21 @@ func doAddress(cfg *planning.ServiceConfig, app *digitalocean.App) string { } // doAppSpec is the App Platform app a planned service runs as. -func doAppSpec(job *Job, cfg *planning.ServiceConfig, repo, branch string) digitalocean.AppSpec { +func doAppSpec(job *Job, cfg *planning.ServiceConfig, src doSource) digitalocean.AppSpec { region := job.Action.Region if region == "" { region = doRegion } spec := digitalocean.AppSpec{Name: DigitalOceanName(job), Region: region} comp := digitalocean.Component{Name: doName(job.Action.Name)} - if r, err := repositories.ParseKey(repo); err == nil && r.Host == "gitlab.com" { - comp.GitLab = &digitalocean.GitLabSource{Repo: r.FullName(), Branch: branch} - } else { - comp.GitHub = &digitalocean.GitHubSource{Repo: repo, Branch: branch} + switch r, err := repositories.ParseKey(src.repo); { + case src.image != nil: + image := *src.image + comp.Image = &image + case err == nil && r.Host == "gitlab.com": + comp.GitLab = &digitalocean.GitLabSource{Repo: r.FullName(), Branch: src.branch} + default: + comp.GitHub = &digitalocean.GitHubSource{Repo: src.repo, Branch: src.branch} } root := strings.Trim(cfg.Source, "/") if root == "." { @@ -487,9 +654,12 @@ func doAppSpec(job *Job, cfg *planning.ServiceConfig, repo, branch string) digit if cfg.Scale != nil { comp.InstanceCount = max(1, cfg.Scale.Min) } - if cfg.Image != "" { + switch { + case comp.Image != nil: + // The image was built with its own start command. + case cfg.Image != "": comp.DockerfilePath, comp.SourceDir = cfg.Image, path.Clean("/"+cfg.ContextDir()) - } else { + default: // App Platform's buildpacks build Node, Go, Python, Ruby, PHP and // more from the source directory; a start command overrides theirs. comp.SourceDir, comp.RunCommand = "/"+root, cfg.Start diff --git a/internal/deployments/digitalocean_image_test.go b/internal/deployments/digitalocean_image_test.go new file mode 100644 index 00000000..c1dab3f7 --- /dev/null +++ b/internal/deployments/digitalocean_image_test.go @@ -0,0 +1,168 @@ +package deployments + +import ( + "slices" + "strings" + "testing" + + "github.com/xraph/loomplane/internal/planning" +) + +const doImageDigest = "sha256:" + "ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12" + +// doImageConfig is a service the plan builds as an image. It pins one, +// which Build takes as it is, so these tests need no builder. +func doImageConfig() *planning.ServiceConfig { + cfg := apiConfig() + cfg.BuildTarget = &planning.BuildTarget{Image: "registry.digitalocean.com/acme/loomplane/api@" + doImageDigest} + return cfg +} + +func doImageExecutor(d *DigitalOcean) *DigitalOcean { + d.Builder = &ImageBuilder{} + return d +} + +func TestDigitalOcean_runsTheImageNotTheRepository(t *testing.T) { + f, client := newFakeAppPlatform(t) + f.registries = []string{"acme"} + cfg := doImageConfig() + out, err := doImageExecutor(newDO(client)).Apply(t.Context(), doJob(cfg, "release")) + if err != nil { + t.Fatal(err) + } + if out.Image != cfg.BuildTarget.Image || out.Revision != "dep-app-api-production-23456789" { + t.Fatalf("outcome %+v", out) + } + svc := f.specs[0]["services"].([]any)[0].(map[string]any) + for _, key := range []string{"github", "gitlab", "dockerfile_path", "source_dir", "run_command"} { + if _, set := svc[key]; set { + t.Fatalf("an image service has %s: %v", key, svc) + } + } + image := svc["image"].(map[string]any) + if image["registry_type"] != "DOCR" || image["repository"] != "loomplane/api" || image["digest"] != doImageDigest { + t.Fatalf("image %v", image) + } + // App Platform wants the registry's name only when there are several. + if _, set := image["registry"]; set { + t.Fatalf("one registry, but the spec names it: %v", image) + } + if svc["http_port"] != float64(8080) || svc["instance_count"] != float64(2) { + t.Fatalf("service %v", svc) + } +} + +func TestDigitalOcean_namesTheRegistryWhenTheAccountHasSeveral(t *testing.T) { + f, client := newFakeAppPlatform(t) + f.registries = []string{"other", "acme"} + if _, err := doImageExecutor(newDO(client)).Apply(t.Context(), doJob(doImageConfig(), "")); err != nil { + t.Fatal(err) + } + image := f.specs[0]["services"].([]any)[0].(map[string]any)["image"].(map[string]any) + if image["registry"] != "acme" { + t.Fatalf("image %v", image) + } +} + +func TestDigitalOcean_refusesARegistryOutsideTheAccount(t *testing.T) { + f, client := newFakeAppPlatform(t) + f.registries = []string{"other"} + _, err := doImageExecutor(newDO(client)).Apply(t.Context(), doJob(doImageConfig(), "")) + if err == nil || !strings.Contains(err.Error(), "acme isn't in the account") { + t.Fatalf("err %v", err) + } + if len(f.specs) != 0 || len(f.created) != 0 { + t.Fatalf("set up an app it can't pull for: specs %v, created %v", f.specs, f.created) + } +} + +// The reviewed registry is checked before anything builds: this build +// would fail in the builder, with no build credentials, if it started. +func TestDigitalOcean_checksTheRegistryBeforeBuilding(t *testing.T) { + f, client := newFakeAppPlatform(t) + f.registries = []string{"other"} + cfg := apiConfig() + cfg.BuildTarget = &planning.BuildTarget{Builder: "conn_pool", Registry: "conn_docr", RegistrySettings: map[string]string{"endpoint": "https://registry.digitalocean.com", "repository": "acme"}} + _, err := doImageExecutor(newDO(client)).Apply(t.Context(), doJob(cfg, "")) + if err == nil || !strings.Contains(err.Error(), "acme isn't in the account") { + t.Fatalf("err %v", err) + } +} + +func TestDigitalOcean_refusesADeploymentOfAnotherImage(t *testing.T) { + f, client := newFakeAppPlatform(t) + f.registries = []string{"acme"} + f.alterBuild = func(spec map[string]any) { + image := spec["services"].([]any)[0].(map[string]any)["image"].(map[string]any) + image["digest"] = "sha256:" + strings.Repeat("cd", 32) + } + _, err := doImageExecutor(newDO(client)).Apply(t.Context(), doJob(doImageConfig(), "")) + if err == nil || !strings.Contains(err.Error(), "other than the image Loomplane built") { + t.Fatalf("err %v", err) + } +} + +// A rollback goes back to the recorded deployment and checks it runs the +// release's image, with no commit to compare: nothing was built from one. +func TestDigitalOcean_rollsAnImageBackToItsDeployment(t *testing.T) { + f, client := newFakeAppPlatform(t) + f.registries = []string{"acme"} + d := doImageExecutor(newDO(client)) + job := doJob(doImageConfig(), "") + first, err := d.Apply(t.Context(), job) + if err != nil { + t.Fatal(err) + } + // App Platform reports no commit for an image, and the deployment + // goes live. + f.tip, f.liveAt = "", "ACTIVE" + cfg := doImageConfig() + cfg.Artifact = &planning.ReusedArtifact{Revision: first.Revision, Reference: first.Image, CommitSHA: doApproved} + job = doJob(cfg, "") + job.Binding = &planning.Binding{ExternalID: first.ExternalID} + out, err := d.Apply(t.Context(), job) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(f.rollbacks, []string{first.Revision}) || len(f.created) != 1 || out.Revision != "rb" || out.Image != first.Image { + t.Fatalf("rollbacks %v, created %v, outcome %+v", f.rollbacks, f.created, out) + } + + // The recorded deployment ran another image: the rollback fails. + cfg.Artifact.Reference = "registry.digitalocean.com/acme/loomplane/api@sha256:" + strings.Repeat("cd", 32) + job = doJob(cfg, "") + job.Binding = &planning.Binding{ExternalID: first.ExternalID} + if _, err := d.Apply(t.Context(), job); err == nil || !strings.Contains(err.Error(), "other than the image Loomplane built") { + t.Fatalf("err %v", err) + } +} + +func TestDigitalOcean_refusesAnImageWithoutABuilder(t *testing.T) { + f, client := newFakeAppPlatform(t) + f.registries = []string{"acme"} + if _, err := newDO(client).Apply(t.Context(), doJob(doImageConfig(), "")); err == nil { + t.Fatal("deployed an image with no builder") + } +} + +func TestDOImageSource(t *testing.T) { + for _, ref := range []string{ + "registry.digitalocean.com/acme/loomplane/api@" + doImageDigest, + "registry.digitalocean.com/acme/loomplane/api:4f2a9c", + } { + src, registry, err := doImageSource(ref, doImageDigest) + if err != nil || registry != "acme" || src.Repository != "loomplane/api" || src.Digest != doImageDigest || src.RegistryType != "DOCR" || src.Registry != "" { + t.Fatalf("%s: %+v %q %v", ref, src, registry, err) + } + } + for _, bad := range []struct{ ref, digest string }{ + {"ghcr.io/acme/api@" + doImageDigest, doImageDigest}, + {"registry.digitalocean.com/acme@" + doImageDigest, doImageDigest}, + {"registry.digitalocean.com/acme/api:latest", ""}, + } { + if _, _, err := doImageSource(bad.ref, bad.digest); err == nil { + t.Fatalf("accepted %s", bad.ref) + } + } +} diff --git a/internal/deployments/digitalocean_rollback_proof.go b/internal/deployments/digitalocean_rollback_proof.go index 7db4035d..3df2f681 100644 --- a/internal/deployments/digitalocean_rollback_proof.go +++ b/internal/deployments/digitalocean_rollback_proof.go @@ -107,6 +107,7 @@ func doSpecMAC(key []byte, spec digitalocean.AppSpec) []byte { // Domains are managed independently. The provider preflight below checks // them against the current app before restoring a historical spec. spec.Domains = nil + spec = doWithoutRegistryNames(spec) data, _ := json.Marshal(spec) //nolint:errcheck // this struct contains only JSON values mac := hmac.New(sha256.New, key) _, _ = mac.Write(data) @@ -136,7 +137,40 @@ func doActualSpec(raw json.RawMessage) (digitalocean.AppSpec, string, error) { return spec, hex.EncodeToString(digest[:]), nil } +// doWithoutRegistryNames is spec with its images' registry names left +// out. App Platform wants the name only while the account has more than +// one registry, so it can come and go without the image changing; the +// image's repository and digest still have to match. +func doWithoutRegistryNames(spec digitalocean.AppSpec) digitalocean.AppSpec { + strip := func(components []digitalocean.Component) []digitalocean.Component { + components = slices.Clone(components) + for i := range components { + if image := components[i].Image; image != nil { + copied := *image + copied.Registry = "" + components[i].Image = &copied + } + } + return components + } + spec.Services, spec.Workers = strip(spec.Services), strip(spec.Workers) + return spec +} + +// doBuiltAsReviewed reports whether dep ran what desired says: the +// approved commit when App Platform built it from a repository. An image's +// digest is in the spec, which the caller matches against desired. +func doBuiltAsReviewed(dep *digitalocean.Deployment, desired digitalocean.AppSpec, commit string) bool { + for _, comp := range append(slices.Clone(desired.Services), desired.Workers...) { + if comp.Image != nil { + return true + } + } + return dep.Built(commit) +} + func doReviewedSpecMatches(actual, desired digitalocean.AppSpec) bool { + actual, desired = doWithoutRegistryNames(actual), doWithoutRegistryNames(desired) // The provider encrypts SECRET values. Match their names, scope and // classification here; the MAC separately binds their submitted values. clearSecrets := func(spec *digitalocean.AppSpec) { @@ -168,7 +202,7 @@ func (d *DigitalOcean) keepRollbackProof(ctx context.Context, token string, job return nil } dep, err := d.Client.GetDeployment(ctx, token, app, revision) - if err != nil || dep.ID != revision || dep.Phase != digitalocean.PhaseActive || !dep.Built(job.CommitSHA) || len(dep.Services)+len(dep.Workers)+len(dep.StaticSites) != 1 { + if err != nil || dep.ID != revision || dep.Phase != digitalocean.PhaseActive || !doBuiltAsReviewed(dep, desired, job.CommitSHA) || len(dep.Services)+len(dep.Workers)+len(dep.StaticSites) != 1 { return doRollbackProofError() } actual, digest, err := doActualSpec(dep.Spec) @@ -228,16 +262,20 @@ func (d *DigitalOcean) checkRollbackProof(ctx context.Context, token string, job if json.Unmarshal(data, &proof) != nil || proof.Version != 1 || len(proof.Key) != 32 || !reflect.DeepEqual(proof.Scope, doProofScope(job, app, revision)) { return doRollbackProofError() } - repo, err := repositoryFor(job) + image := "" + if artifact := job.Action.Service.Artifact; artifact != nil { + image = artifact.Reference + } + src, err := doSourceFor(job, job.Action.Service, image) if err != nil { return doRollbackProofError() } - desired := doAppSpec(job, job.Action.Service, repo, doBranchFor(job)) + desired := doAppSpec(job, job.Action.Service, src) if !hmac.Equal(proof.Desired, doSpecMAC(proof.Key, desired)) { return doRollbackProofError() } dep, err := d.Client.GetDeployment(ctx, token, app, revision) - if err != nil || dep.ID != revision || !dep.Built(job.CommitSHA) || len(dep.Services)+len(dep.Workers)+len(dep.StaticSites) != 1 { + if err != nil || dep.ID != revision || !doBuiltAsReviewed(dep, desired, job.CommitSHA) || len(dep.Services)+len(dep.Workers)+len(dep.StaticSites) != 1 { return doRollbackProofError() } actual, digest, err := doActualSpec(dep.Spec) diff --git a/internal/deployments/digitalocean_test.go b/internal/deployments/digitalocean_test.go index adc0382b..f0af3ad6 100644 --- a/internal/deployments/digitalocean_test.go +++ b/internal/deployments/digitalocean_test.go @@ -43,6 +43,8 @@ type fakeAppPlatform struct { deployments map[string]map[string]any // immutable specs keyed by deployment ID alterBuild func(map[string]any) // provider-side edits before the first readback encryptSecrets bool + // registries are the account's container registries' names. + registries []string // held reports whether the client's lock is held, and locked records // it for the first call of each method and path. held func() bool @@ -150,6 +152,12 @@ func (f *fakeAppPlatform) serve(w http.ResponseWriter, r *http.Request) { f.apps[parts[2]], f.deployments["rb"] = spec, spec } reply(200, map[string]any{"deployment": map[string]any{"id": "rb"}}) + case r.Method == http.MethodGet && r.URL.Path == "/v2/registries": + out := []any{} + for _, name := range f.registries { + out = append(out, map[string]any{"name": name}) + } + reply(200, map[string]any{"registries": out}) case r.Method == http.MethodGet && r.URL.Path == "/v2/databases": out := make([]any, 0, len(f.databases)) for _, d := range f.databases { @@ -444,12 +452,12 @@ func TestDigitalOcean_rollbackHoldsTheAppUntilItStarts(t *testing.T) { func TestDigitalOcean_workersPrivateServicesAndStaticSites(t *testing.T) { job := doJob(&planning.ServiceConfig{Source: "worker", Ecosystem: "node", Start: "node worker.js", Workload: provider.Worker, Execution: provider.Container}, "") - spec := doAppSpec(job, job.Action.Service, "acme/mono", "main") + spec := doAppSpec(job, job.Action.Service, doSource{repo: "acme/mono", branch: "main"}) if len(spec.Workers) != 1 || spec.Workers[0].RunCommand != "node worker.js" || spec.Workers[0].SourceDir != "/worker" || len(spec.Services) != 0 { t.Fatalf("worker %+v", spec) } job.Action.Service = &planning.ServiceConfig{Source: "api", Ecosystem: "go", Port: 9000, Workload: provider.HTTPService, Execution: provider.Container} - spec = doAppSpec(job, job.Action.Service, "acme/mono", "main") + spec = doAppSpec(job, job.Action.Service, doSource{repo: "acme/mono", branch: "main"}) if svc := spec.Services[0]; svc.HTTPPort != 0 || len(svc.InternalPorts) != 1 || svc.InternalPorts[0] != 9000 { t.Fatalf("private service %+v", svc) } @@ -457,7 +465,7 @@ func TestDigitalOcean_workersPrivateServicesAndStaticSites(t *testing.T) { t.Fatal("a private service got a public address") } job.Action.Service = &planning.ServiceConfig{Source: "web", Framework: "next", Workload: provider.StaticSite, Execution: provider.Static} - spec = doAppSpec(job, job.Action.Service, "acme/mono", "main") + spec = doAppSpec(job, job.Action.Service, doSource{repo: "acme/mono", branch: "main"}) if len(spec.StaticSites) != 1 || spec.StaticSites[0].OutputDir != "out" || spec.StaticSites[0].InstanceSizeSlug != "" { t.Fatalf("static site %+v", spec) } @@ -467,7 +475,7 @@ func TestDigitalOcean_aDockerfileThatBuildsFromTheRoot(t *testing.T) { // Loomplane's own: deployments/docker/Dockerfile, built from the root. cfg := &planning.ServiceConfig{Source: ".", Image: "deployments/docker/Dockerfile", Context: ".", Port: 8780, Public: true, Workload: provider.HTTPService, Execution: provider.Container} - svc := doAppSpec(doJob(cfg, ""), cfg, "xraph/loomplane", "main").Services[0] + svc := doAppSpec(doJob(cfg, ""), cfg, doSource{repo: "xraph/loomplane", branch: "main"}).Services[0] if svc.SourceDir != "/" || svc.DockerfilePath != "deployments/docker/Dockerfile" || svc.HTTPPort != 8780 { t.Fatalf("service %+v", svc) } diff --git a/internal/deployments/git_source_test.go b/internal/deployments/git_source_test.go index 9e50413c..e50615e0 100644 --- a/internal/deployments/git_source_test.go +++ b/internal/deployments/git_source_test.go @@ -31,7 +31,7 @@ func TestRenderSpec_gitLabRepoURL(t *testing.T) { func TestDOAppSpec_gitLabSource(t *testing.T) { cfg := &planning.ServiceConfig{Source: "api", Ecosystem: "go", Port: 8080, Public: true, Workload: provider.HTTPService, Execution: provider.Container} job := doJob(cfg, "") - comp := doAppSpec(job, cfg, "gitlab.com/grp/sub/api", "main").Services[0] + comp := doAppSpec(job, cfg, doSource{repo: "gitlab.com/grp/sub/api", branch: "main"}).Services[0] if comp.GitHub != nil { t.Fatalf("a GitLab key got a GitHub source: %+v", comp.GitHub) } @@ -50,7 +50,7 @@ func TestDOAppSpec_gitLabSource(t *testing.T) { func TestDOAppSpec_gitHubSourceUnchanged(t *testing.T) { cfg := &planning.ServiceConfig{Source: "api", Ecosystem: "go", Port: 8080, Public: true, Workload: provider.HTTPService, Execution: provider.Container} - comp := doAppSpec(doJob(cfg, ""), cfg, "acme/mono", "main").Services[0] + comp := doAppSpec(doJob(cfg, ""), cfg, doSource{repo: "acme/mono", branch: "main"}).Services[0] if comp.GitLab != nil || comp.GitHub == nil || *comp.GitHub != (digitalocean.GitHubSource{Repo: "acme/mono", Branch: "main"}) { t.Fatalf("github %+v, gitlab %+v", comp.GitHub, comp.GitLab) } diff --git a/internal/deployments/native_external_delivery_test.go b/internal/deployments/native_external_delivery_test.go index 310fff2d..7ba78c2b 100644 --- a/internal/deployments/native_external_delivery_test.go +++ b/internal/deployments/native_external_delivery_test.go @@ -28,7 +28,7 @@ func TestDigitalOceanExternalCredentialsAreRuntimeOnly(t *testing.T) { job := doJob(cfg, "main") job.Env = map[string]string{"DATABASE_URL": "postgres://app:secret@db/app", "CACHE_URL": "rediss://:secret@cache:6380", "AWS_SECRET_ACCESS_KEY": "application-key", "NPM_TOKEN": "build-token"} job.Secrets = map[string]bool{"DATABASE_URL": true, "CACHE_URL": true, "AWS_SECRET_ACCESS_KEY": true, "NPM_TOKEN": true} - envs := doAppSpec(job, cfg, "acme/mono", "main").Services[0].Envs + envs := doAppSpec(job, cfg, doSource{repo: "acme/mono", branch: "main"}).Services[0].Envs for _, env := range envs { if env.Key == "PORT" { continue @@ -51,7 +51,7 @@ func TestNativeBucketLongTermKeysOmitEmptyOptionalToken(t *testing.T) { job := doJob(cfg, "main") job.Env = map[string]string{"FILES_AWS_SESSION_TOKEN": "", "FILES_AWS_SECRET_ACCESS_KEY": "application-secret"} job.Secrets = map[string]bool{"FILES_AWS_SESSION_TOKEN": true, "FILES_AWS_SECRET_ACCESS_KEY": true} - for _, env := range doAppSpec(job, cfg, "acme/mono", "main").Services[0].Envs { + for _, env := range doAppSpec(job, cfg, doSource{repo: "acme/mono", branch: "main"}).Services[0].Envs { if env.Key == "FILES_AWS_SESSION_TOKEN" { t.Fatal("App Platform emitted an empty optional token secret") } diff --git a/internal/deployments/vite_rsc_test.go b/internal/deployments/vite_rsc_test.go index eec1ceef..5903a7e9 100644 --- a/internal/deployments/vite_rsc_test.go +++ b/internal/deployments/vite_rsc_test.go @@ -94,7 +94,7 @@ func TestViteRSCNativeTargetsRunServer(t *testing.T) { if err != nil || spec.Runtime != "node" || spec.Start != "npm start" || !strings.Contains(spec.Build, "npm run build") || spec.PublishPath != "" { t.Fatalf("native server lost: %+v, %v", spec, err) } - app := doAppSpec(job, cfg, "example/rsc", "main") + app := doAppSpec(job, cfg, doSource{repo: "example/rsc", branch: "main"}) if len(app.Services) != 1 || len(app.StaticSites) != 0 || app.Services[0].RunCommand != "node server.mjs" { t.Fatalf("RSC static deployment: %+v", app) } diff --git a/internal/planning/app_platform.go b/internal/planning/app_platform.go new file mode 100644 index 00000000..788de404 --- /dev/null +++ b/internal/planning/app_platform.go @@ -0,0 +1,147 @@ +package planning + +import ( + "slices" + + "github.com/xraph/loomplane/internal/buildpolicy" + "github.com/xraph/loomplane/pkg/manifest" + "github.com/xraph/loomplane/pkg/provider" +) + +// appPlatformRegistryEndpoint is DigitalOcean's container registry, the +// only one App Platform pulls from without a credential of its own. +const appPlatformRegistryEndpoint = "https://registry.digitalocean.com" + +// registryMissing says how to give App Platform a registry to pull from. +const registryMissing = "the DigitalOcean account's container registry, added under Integrations as a registry (named in build.registry when there are several)" + +// appPlatformGitHubNote is what a plan says about a service App Platform +// builds from its repository itself. +const appPlatformGitHubNote = " App Platform builds it from the repository through DigitalOcean's own GitHub or GitLab connection, which only someone signed in to DigitalOcean can set up, and DigitalOcean's API can't. Before deploying, connect the repository's account in DigitalOcean's control panel." + +// configureAppPlatform decides how DigitalOcean App Platform gets a +// service's code. +// +// A service or worker Loomplane can build, one with a Dockerfile or a Go +// module, is built by Loomplane's builder and pushed to the DigitalOcean +// account's container registry, and App Platform runs that image. Nothing +// at DigitalOcean needs access to the repository, and the image is the +// approved commit by construction. +// +// App Platform builds the rest itself from the repository: static sites, +// which it can't run from an image, and services it builds with its own +// buildpacks. So do services where no builder or DigitalOcean registry is +// set up yet, as every service did before, with a warning that says what +// to add. Those need DigitalOcean's GitHub or GitLab connection. +func (p *planner) configureAppPlatform(name, base string, prov *provider.Provider, set manifest.Settings, cfg *ServiceConfig) { + b := set.Build + if b == nil { + b = &manifest.Build{} + } + named := b.Builder != "" || b.Registry != "" || b.Image != "" + if set.Target != "" || set.Endpoint != nil { + p.problem(Finding{Code: "target-unsupported", Subject: ServiceSubject, Name: name, Path: base, + Message: "Target and endpoint settings need a server or Kubernetes provider."}) + } + p.serviceGPU(name, base, prov, set, cfg, nil) + + if cfg.Execution == provider.Static || (cfg.Image == "" && cfg.Ecosystem != "go") { + what := "This static site can't run from an image." + if cfg.Execution != provider.Static { + what = "Loomplane builds a container image from a Dockerfile or a Go module, and this service has neither." + } + if named { + p.problem(Finding{Code: "app-platform-build", Subject: ServiceSubject, Name: name, Path: base + ".build", + Message: what + " App Platform builds it from the repository, so remove the build settings, or add a Dockerfile to build it with Loomplane."}) + return + } + p.warn(Finding{Code: "app-platform-repository", Subject: ServiceSubject, Name: name, Path: base, + Message: what + appPlatformGitHubNote}) + return + } + + build := &BuildTarget{Builder: b.Builder, Registry: b.Registry, Image: b.Image} + if build.Image == "" { + if build.Builder == "" { + if d := p.in.BuildDefault; d != nil && d.Builder != "" { + if d.Connection != nil && !slices.ContainsFunc(p.in.Connections, func(o ConnectionOption) bool { return o.ID == d.Connection.ID }) { + p.in.Connections = append(p.in.Connections, *d.Connection) + } + build.Builder = d.Builder + } + } + if build.Registry == "" { + build.Registry = p.appPlatformRegistry() + } + if !named && (build.Builder == "" || build.Registry == "") { + missing := "a runner pool to build on" + switch { + case build.Builder != "": + missing = registryMissing + case build.Registry == "": + missing = "a runner pool to build on and " + registryMissing + } + p.warn(Finding{Code: "app-platform-repository", Subject: ServiceSubject, Name: name, Path: base + ".build", + Message: "Loomplane can build this service itself, and App Platform would run the image without access to the repository, once there is " + missing + "." + appPlatformGitHubNote}) + return + } + builderCloud := p.builderCloud(build.Builder) + if builderCloud != "server" { + build.BuilderCloud = builderCloud + } + if builder := p.targetConnection(name, base+".build.builder", "builder", builderCloud, build.Builder); builder != nil { + build.BuilderSettings = ReviewedBuildSettings(builder.Cloud, builder.Details) + if err := buildpolicy.CheckBackend(builder.Details, builder.Cloud, builder.Pooled); err != nil { + p.problem(Finding{Code: "build-isolation-required", Subject: ServiceSubject, Name: name, Path: base + ".build.builder", Message: err.Error()}) + } + if arch := builder.Details["architecture"]; arch != "" && arch != "amd64" { + p.problem(Finding{Code: "build-architecture", Subject: ServiceSubject, Name: name, Path: base + ".build.builder", + Message: "App Platform runs amd64 images. Choose a builder with the amd64 architecture."}) + } + } + if builderCloud == "aws" { + p.problem(Finding{Code: "app-platform-registry", Subject: ServiceSubject, Name: name, Path: base + ".build.builder", + Message: "CodeBuild pushes only to Amazon ECR, and App Platform pulls from DigitalOcean's container registry. Choose a runner pool or a server to build on."}) + } + } + role := "registry" + if build.Image != "" { + role = "registry-pull" + } + if build.Registry == "" { + p.problem(Finding{Code: "app-platform-registry", Subject: ServiceSubject, Name: name, Path: base + ".build.registry", + Message: "App Platform pulls images only from the DigitalOcean account's container registry. Add it under Integrations as a registry, from the DigitalOcean account, and choose it here."}) + } else if registry := p.targetConnection(name, base+".build.registry", role, "registry", build.Registry); registry != nil { + build.RegistrySettings = ReviewedConnectionSettings(registry.Cloud, registry.Details) + if registry.Details["endpoint"] != appPlatformRegistryEndpoint { + p.problem(Finding{Code: "app-platform-registry", Subject: ServiceSubject, Name: name, Path: base + ".build.registry", + Message: "App Platform pulls images only from DigitalOcean's container registry. Choose a registry connection made from the DigitalOcean account the service runs in."}) + } + } + cfg.BuildTarget = build + if cfg.Image == "" && b.Context != "" { + cfg.Context = b.Context + } +} + +// appPlatformImage reports whether a deploys on App Platform from an image +// Loomplane builds, rather than App Platform building the repository. +func appPlatformImage(a Action) bool { + return a.Provider == "digitalocean" && a.Service != nil && a.Service.BuildTarget != nil +} + +// appPlatformRegistry is the one ready DigitalOcean registry connection, +// or "" when there are none or several to choose between. +func (p *planner) appPlatformRegistry() string { + found := "" + for _, c := range p.in.Connections { + if c.Cloud != "registry" || !c.Ready || c.Details["endpoint"] != appPlatformRegistryEndpoint || c.Details["push"] != "ready" { + continue + } + if found != "" { + return "" + } + found = c.ID + } + return found +} diff --git a/internal/planning/app_platform_test.go b/internal/planning/app_platform_test.go new file mode 100644 index 00000000..21ade25b --- /dev/null +++ b/internal/planning/app_platform_test.go @@ -0,0 +1,191 @@ +package planning + +import ( + "context" + "slices" + "strings" + "testing" + "testing/fstest" + + "github.com/xraph/loomplane/internal/discovery" + "github.com/xraph/loomplane/internal/graph" + "github.com/xraph/loomplane/internal/providers" +) + +var ( + doAccount = ConnectionOption{ID: "conn_00000000000000000000000001", Name: "DigitalOcean", Cloud: "digitalocean", Ready: true} + doRegistry = ConnectionOption{ID: "conn_00000000000000000000000003", Name: "DOCR", Cloud: "registry", Ready: true, + Details: map[string]string{"endpoint": "https://registry.digitalocean.com", "repository": "acme", "push": "ready"}} + doGHCR = ConnectionOption{ID: "conn_00000000000000000000000004", Name: "GHCR", Cloud: "registry", Ready: true, + Details: map[string]string{"endpoint": "https://ghcr.io", "repository": "acme", "push": "ready"}} + doRunners = ConnectionOption{ID: "conn_00000000000000000000000002", Name: "Pool", Cloud: "runner", Ready: true, + Details: doRunnerDetails("amd64")} +) + +// doRunnerDetails are a runner pool's whose runners passed the microVM +// check, as a pool must before it builds. +func doRunnerDetails(arch string) map[string]string { + return map[string]string{"architecture": arch, "isolation": "firecracker", "build_isolation": "ready", + "runtime_identity": strings.Repeat("a", 64), "host_id": "host-1"} +} + +// planAppPlatform plans one service on App Platform: a Go module, which +// Loomplane can build, or the same module made a static site, which it +// can't. +func planAppPlatform(t *testing.T, static bool, settings string, def *BuildDefault, conns ...ConnectionOption) *Result { + t.Helper() + fs := fstest.MapFS{ + "go.mod": {Data: []byte("module example.com/api\n\ngo 1.24\n")}, + "main.go": {Data: []byte("package main\n\nimport \"net/http\"\n\nfunc main() { http.ListenAndServe(\":8080\", nil) }\n")}, + } + if static { + settings = " kind: static-site\n" + settings + } + report, err := discovery.Analyze(context.Background(), fs) + if err != nil { + t.Fatal(err) + } + g := graph.Build(report) + if len(g.Services) != 1 { + t.Fatalf("services %+v", g.Services) + } + name := g.Services[0].Name + m := parse(t, "version: 1\nservices:\n "+name+":\n source: .\n provider: digitalocean\n"+settings) + r := Compute(Input{Environment: "production", Graph: g, Providers: providers.Registry(), Connections: append([]ConnectionOption{doAccount}, conns...), Manifest: m, BuildDefault: def}) + r.Actions = slices.DeleteFunc(r.Actions, func(a Action) bool { return a.Service == nil }) + if len(r.Actions) != 1 { + t.Fatalf("actions %+v, problems %+v", r.Actions, r.Problems) + } + return r +} + +func TestAppPlatform_buildsTheImageWithTheDefaultPool(t *testing.T) { + r := planAppPlatform(t, false, "", &BuildDefault{Builder: doRunners.ID, Source: "the project's runner pool"}, doRunners, doRegistry) + if !r.Executable { + t.Fatalf("problems %+v", r.Problems) + } + build := r.Actions[0].Service.BuildTarget + if build == nil || build.Builder != doRunners.ID || build.BuilderCloud != "runner" || build.Registry != doRegistry.ID || build.RegistrySettings["endpoint"] != "https://registry.digitalocean.com" { + t.Fatalf("build target %+v", build) + } + if hasCode(r.Warnings, "app-platform-repository") { + t.Fatalf("warned about the repository for an image build: %+v", r.Warnings) + } +} + +// A service that deployed through DigitalOcean's GitHub connection keeps +// doing so until there's somewhere to build and push, and the plan says +// what's missing. +func TestAppPlatform_fallsBackToTheRepositoryUntilItCanBuild(t *testing.T) { + for name, conns := range map[string][]ConnectionOption{ + "no registry": {doRunners}, + "no builder": {doRegistry}, + "two registries": {doRunners, doRegistry, {ID: "conn_00000000000000000000000005", Name: "DOCR 2", Cloud: "registry", Ready: true, Details: doRegistry.Details}}, + "nothing set up": nil, + "another registry": {doRunners, doGHCR}, + } { + t.Run(name, func(t *testing.T) { + var def *BuildDefault + if slices.ContainsFunc(conns, func(c ConnectionOption) bool { return c.ID == doRunners.ID }) { + def = &BuildDefault{Builder: doRunners.ID, Source: "the project's runner pool"} + } + r := planAppPlatform(t, false, "", def, conns...) + if !r.Executable { + t.Fatalf("problems %+v", r.Problems) + } + if r.Actions[0].Service.BuildTarget != nil { + t.Fatalf("build target %+v", r.Actions[0].Service.BuildTarget) + } + if !hasCode(r.Warnings, "app-platform-repository") { + t.Fatalf("warnings %+v", r.Warnings) + } + }) + } +} + +func TestAppPlatform_staticSitesBuildFromTheRepository(t *testing.T) { + r := planAppPlatform(t, true, "", &BuildDefault{Builder: doRunners.ID}, doRunners, doRegistry) + if !r.Executable || r.Actions[0].Service.BuildTarget != nil || !hasCode(r.Warnings, "app-platform-repository") { + t.Fatalf("executable %v, build %+v, warnings %+v, problems %+v", r.Executable, r.Actions[0].Service.BuildTarget, r.Warnings, r.Problems) + } + r = planAppPlatform(t, true, " build:\n registry: conn_00000000000000000000000003\n", nil, doRegistry) + if r.Executable || !hasCode(r.Problems, "app-platform-build") { + t.Fatalf("a static site took build settings: %+v", r.Problems) + } +} + +func TestAppPlatform_refusesARegistryItCantPullFrom(t *testing.T) { + r := planAppPlatform(t, false, " build:\n builder: conn_00000000000000000000000002\n registry: conn_00000000000000000000000004\n", nil, doRunners, doGHCR) + if r.Executable || !hasCode(r.Problems, "app-platform-registry") { + t.Fatalf("problems %+v", r.Problems) + } +} + +func TestAppPlatform_refusesAnArmBuilder(t *testing.T) { + arm := doRunners + arm.Details = doRunnerDetails("arm64") + r := planAppPlatform(t, false, " build:\n builder: conn_00000000000000000000000002\n registry: conn_00000000000000000000000003\n", nil, arm, doRegistry) + if r.Executable || !hasCode(r.Problems, "build-architecture") { + t.Fatalf("problems %+v", r.Problems) + } +} + +// appPlatformImageAction is api on App Platform, built as an image pushed +// to conn_reg. +func appPlatformImageAction() Action { + a := productionAPI() + a.Provider, a.Service.Provider, a.Region, a.Service.Region = "digitalocean", "digitalocean", "ams", "ams" + a.Service.BuildTarget = &BuildTarget{Builder: "conn_builder", Registry: "conn_reg", BuilderSettings: map[string]string{"architecture": "amd64"}} + return a +} + +func TestAppPlatform_promotionReusesTheImageInTheSameRegistry(t *testing.T) { + img := stagingAPI() + img.Provider, img.Registry, img.Architecture = "digitalocean", "conn_reg", "amd64" + result := &Result{Actions: []Action{appPlatformImageAction()}} + artifactService().applyArtifacts(promotionPlan(), result, map[string]ReleasedImage{"api": img}, "staging") + if len(result.Artifacts) != 1 || !result.Artifacts[0].Reused || result.Actions[0].Service.Artifact.Reference != img.Image { + t.Fatalf("artifacts %+v", result.Artifacts) + } + + img.Registry = "conn_reg_other" + result = &Result{Actions: []Action{appPlatformImageAction()}} + artifactService().applyArtifacts(promotionPlan(), result, map[string]ReleasedImage{"api": img}, "staging") + if result.Artifacts[0].Reused || result.Artifacts[0].Reason != "production pushes to another registry; production builds aaa1234 again" { + t.Fatalf("artifacts %+v", result.Artifacts) + } +} + +// Loomplane builds the image from the code it fetched, so App Platform +// never needs to read the repository's host. +func TestAppPlatform_imageBuildsTakeAnyRepositoryHost(t *testing.T) { + plan := &Plan{Sources: []PlanSource{{Alias: "api", Repository: "gitlab.example.com/team/api"}}} + a := appPlatformImageAction() + a.Op, a.Service.Repo = Create, "api" + result := &Result{Executable: true, Actions: []Action{a}} + checkGitBuilds(plan, result) + if !result.Executable || len(result.Problems) != 0 { + t.Fatalf("problems %+v", result.Problems) + } +} + +func TestAppPlatform_rollbackRunsTheRecordedImage(t *testing.T) { + img := ReleasedImage{Service: "api", Provider: "digitalocean", Revision: "historical", CommitSHA: artifactCommit, Image: artifactImage, Architecture: "amd64"} + a := appPlatformImageAction() + choice, artifact, finding := appPlatformRollback(a, img, "previous") + if finding != nil || artifact.Revision != "historical" || artifact.Reference != artifactImage || artifact.Digest != artifactDigest || choice.Reference != artifactImage { + t.Fatalf("choice %+v, artifact %+v, finding %+v", choice, artifact, finding) + } + + // Across the switch between App Platform's builds and Loomplane's, + // there's no matching deployment to go back to. + built := img + built.Image = "" + if _, _, finding := appPlatformRollback(a, built, "previous"); finding == nil || !strings.Contains(finding.Message, "from the repository") { + t.Fatalf("finding %+v", finding) + } + a.Service.BuildTarget = nil + if _, _, finding := appPlatformRollback(a, img, "previous"); finding == nil || !strings.Contains(finding.Message, "ran an image Loomplane built") { + t.Fatalf("finding %+v", finding) + } +} diff --git a/internal/planning/artifacts.go b/internal/planning/artifacts.go index ca13ec16..68a927a7 100644 --- a/internal/planning/artifacts.go +++ b/internal/planning/artifacts.go @@ -69,7 +69,7 @@ func checkGitBuilds(plan *Plan, result *Result) { if !deploysBuiltCode(a) { continue } - if _, builds := gitBuildHosts[a.Provider]; !builds { + if _, builds := gitBuildHosts[a.Provider]; !builds || appPlatformImage(a) { continue } for _, src := range plan.Sources { @@ -238,7 +238,7 @@ func (s *Service) reusable(to string, connections map[string]string, a Action, i choice.Reason = reason return choice, nil } - if a.Provider == "digitalocean" { + if a.Provider == "digitalocean" && !appPlatformImage(a) { choice.Reason = "App Platform builds the newest commit of its branch; this promotion works only while that is still " + short return choice, nil } @@ -261,7 +261,9 @@ func (s *Service) reusable(to string, connections map[string]string, a Action, i return choice, nil } pull, pulls := pullAccounts[a.Provider] - ownsRegistry := a.Provider == "server" || a.Provider == "kubernetes" + // App Platform pulls an image Loomplane built from the registry it was + // pushed to, as a server does. + ownsRegistry := a.Provider == "server" || a.Provider == "kubernetes" || appPlatformImage(a) if !pulls && !ownsRegistry { choice.Reason = s.providerTitle(a.Provider) + " builds each deployment itself" + again return choice, nil diff --git a/internal/planning/rollback.go b/internal/planning/rollback.go index 08d5a032..09eb500b 100644 --- a/internal/planning/rollback.go +++ b/internal/planning/rollback.go @@ -556,10 +556,23 @@ func appPlatformRollback(a Action, img ReleasedImage, from string) (ArtifactChoi return refuse(recorded + "this release predates that") case img.CommitSHA != a.Service.CommitSHA: return refuse(recorded + "the deployment it recorded ran " + shortCommit(img.CommitSHA) + ", not " + shortCommit(a.Service.CommitSHA)) + // The rollback is checked against the app spec this plan would deploy, + // which runs an image or builds from the repository; the recorded + // deployment has to have done the same. + case a.Service.BuildTarget != nil && !digestReference.MatchString(img.Image): + return refuse("App Platform built that release of " + a.Name + " from the repository, and this plan has Loomplane build its image. Deploy the commit instead of rolling back") + case a.Service.BuildTarget == nil && img.Image != "": + return refuse("That release of " + a.Name + " ran an image Loomplane built, and this plan has App Platform build from the repository. Deploy the commit instead of rolling back") } choice.Reused, choice.Revision, choice.From = true, img.Revision, from if a.Service.TargetAccountIdentity != "" || img.ExternalResources { choice.Reason = "The recorded App Platform configuration and resource credentials are verified against this review before rollback. Changed credentials require a source deployment." } - return choice, &ReusedArtifact{Revision: img.Revision, CommitSHA: img.CommitSHA, FromEnvironment: from, FromDeploymentID: img.DeploymentID}, nil + artifact := &ReusedArtifact{Revision: img.Revision, CommitSHA: img.CommitSHA, FromEnvironment: from, FromDeploymentID: img.DeploymentID} + if a.Service.BuildTarget != nil { + _, artifact.Digest, _ = strings.Cut(img.Image, "@") + artifact.Reference, artifact.Architecture = img.Image, img.Architecture + choice.Reference = img.Image + } + return choice, artifact, nil } diff --git a/internal/planning/targets.go b/internal/planning/targets.go index 0d10d6fd..c2c5ad86 100644 --- a/internal/planning/targets.go +++ b/internal/planning/targets.go @@ -183,6 +183,10 @@ func (p *planner) configureTarget(name, base string, prov *provider.Provider, se } return } + if prov.Cloud == "digitalocean" { + p.configureAppPlatform(name, base, prov, set, cfg) + return + } if !OwnedCloud(prov.Cloud) { if set.Target != "" || set.Endpoint != nil || (set.Build != nil && (set.Build.Builder != "" || set.Build.Registry != "" || set.Build.Image != "")) { p.problem(Finding{Code: "target-unsupported", Subject: ServiceSubject, Name: name, Path: base,