Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
# Shuttle: active changes

## Une application sans build peut être déployée (DEV-DEPL-65)

- Un stack fait uniquement d'images publiées, par exemple Redis et RabbitMQ,
se déploie sous `deploy.strategy: swarm` si chaque service fixe son image
par digest. Le déploiement ne lance ni builder, ni tunnel vers le registre,
ni push. Un service sans digest reste refusé, avec son nom dans le message.
- Le service principal d'une application `expose: internal` peut utiliser
`update_order: stop-first`. Rien n'est publié derrière Caddy, et un RabbitMQ
ou un Redis seul sur un volume ne doit jamais tourner à côté de sa
relève. Le service publié d'une application publique reste refusé.
- Les `networks` d'un service peuvent s'écrire sous forme de map, avec
`aliases`. Cette forme faisait échouer la lecture du fichier compose.
- Un service compose nommé `redis` ou `rabbitmq` est vérifié avant toute
opération : compte du volume de données et volume `<app>_<service>_data`.
Seul le helper le refusait, après la réservation de l'opération, ce qui
laissait `recovery_required`, ou après la destruction de l'invité pour
`infra recreate`.
- Une application `expose: internal` refuse un label `dev.shuttle.domain`
écrit dans son fichier compose : il la publierait derrière Caddy.
- `deploy.pre_deploy` sur un service non construit utilise l'image que le
fichier compose fixe par digest.

## L'export public omettait le point d'entrée de Shuttle

- L'export ajoute tous les fichiers suivis qui ont passé son filtrage. La règle
Expand Down
26 changes: 25 additions & 1 deletion app/go-cli/internal/cli/compose_deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"os/exec"
"path/filepath"
"sort"
"strings"

"github.com/dev-toolings/shuttle/app/go-cli/internal/config"
Expand Down Expand Up @@ -82,6 +83,29 @@ type composeFile struct {
Raw map[string]any `yaml:"-"`
}

// serviceNetworks is the list of network keys a service joins. Compose writes
// it either as a list or as a map whose values carry per-network settings such
// as aliases; only the keys matter here, and the raw document keeps the rest.
type serviceNetworks []string

func (networks *serviceNetworks) UnmarshalYAML(node *yaml.Node) error {
if node.Kind == yaml.MappingNode {
keys := make([]string, 0, len(node.Content)/2)
for i := 0; i < len(node.Content); i += 2 {
keys = append(keys, node.Content[i].Value)
}
sort.Strings(keys)
*networks = keys
return nil
}
var list []string
if err := node.Decode(&list); err != nil {
return err
}
*networks = list
return nil
}

type composeService struct {
Build any `yaml:"build,omitempty"`
Image string `yaml:"image,omitempty"`
Expand All @@ -92,7 +116,7 @@ type composeService struct {
Ports []any `yaml:"ports,omitempty"`
DependsOn any `yaml:"depends_on,omitempty"`
Restart string `yaml:"restart,omitempty"`
Networks []string `yaml:"networks,omitempty"`
Networks serviceNetworks `yaml:"networks,omitempty"`
EnvFile any `yaml:"env_file,omitempty"`
Labels map[string]string `yaml:"labels,omitempty"`
Command any `yaml:"command,omitempty"`
Expand Down
5 changes: 4 additions & 1 deletion app/go-cli/internal/cli/infra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,10 @@ func TestRecreateRefusesWhatTheDeployWouldRefuseBeforeDestruction(t *testing.T)
{"global section", web + "volumes:\n data: {driver_opts: {type: nfs}}\n", "volume data"},
{"profile", web + " profiles: [debug]\n", "profiles"},
{"legacy secrets file", web + " env_file: .env.secrets\n", ".env.secrets"},
{"nothing to build", "services:\n web:\n image: demo\n healthcheck:\n test: [\"CMD\", \"true\"]\n", "no services with build"},
{"nothing to build, image not pinned", "services:\n web:\n image: demo\n healthcheck:\n test: [\"CMD\", \"true\"]\n", "service web has no image pinned by digest"},
{"nothing to build, images pinned", "services:\n redis:\n image: redis:7-alpine@sha256:57e4255cc971b1c8d6f8a6ca283ac01bc3ecdd914273ef6bfaede87aaecd6541\n user: \"999:1000\"\n volumes: [\"demo_redis_data:/data\"]\n healthcheck:\n test: [\"CMD\", \"redis-cli\", \"ping\"]\n", ""},
{"redis without its data account", "services:\n redis:\n image: redis:7-alpine@sha256:57e4255cc971b1c8d6f8a6ca283ac01bc3ecdd914273ef6bfaede87aaecd6541\n volumes: [\"demo_redis_data:/data\"]\n healthcheck:\n test: [\"CMD\", \"redis-cli\", \"ping\"]\n", "service redis must run as \"999:1000\""},
{"redis without its data volume key", "services:\n redis:\n image: redis:7-alpine@sha256:57e4255cc971b1c8d6f8a6ca283ac01bc3ecdd914273ef6bfaede87aaecd6541\n user: \"999:1000\"\n volumes: [\"redis_data:/data\"]\n healthcheck:\n test: [\"CMD\", \"redis-cli\", \"ping\"]\nvolumes:\n redis_data:\n name: demo_redis_data\n", "must mount the volume keyed demo_redis_data at /data"},
{"no healthcheck", "services:\n web:\n build: .\n", "healthcheck"},
{"privileged", web + " privileged: true\n", "privileged"},
{"bind mount", web + " volumes: [\"./data:/data\"]\n", "volume"},
Expand Down
9 changes: 8 additions & 1 deletion app/go-cli/internal/cli/promotion_hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,14 @@ func runPreDeployHook(cfg *config.Config, client *ssh.Client, identity trustedHo
return nil
}
image := strings.TrimSpace(images[hook.Service])
if !strings.Contains(image, "@sha256:") {
// A service Shuttle does not build runs the image its compose file pins,
// unless production.redis or production.rabbitmq replaces that service with
// the generated one, whose image is not the compose file's.
generated := hook.Service == "redis" && cfg.Production.Redis || hook.Service == "rabbitmq" && cfg.Production.RabbitMQ
if image == "" && parsed != nil && !generated {
image = strings.TrimSpace(parsed.Services[hook.Service].Image)
}
if !digestImage.MatchString(image) {
return fmt.Errorf("deploy.pre_deploy.service %s has no pushed image digest", hook.Service)
}
var sources []string
Expand Down
72 changes: 72 additions & 0 deletions app/go-cli/internal/cli/promotion_hooks_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package cli

import (
"os"
"path/filepath"
"strings"
"testing"

"github.com/dev-toolings/shuttle/app/go-cli/internal/config"
"github.com/dev-toolings/shuttle/app/go-cli/internal/rootplan"
)

Expand Down Expand Up @@ -43,6 +46,75 @@ func TestPreDeployAttachesEveryServiceNetwork(t *testing.T) {
}
}

// Compose also writes a service's networks as a map, which is the only way to
// give it aliases. That form used to fail the parse of the whole compose file.
func TestComposeServiceNetworksAcceptTheMapFormWithAliases(t *testing.T) {
parsed := parseComposeString(t, "services:\n redis:\n image: redis\n networks:\n caddy_network:\n aliases: [redis, cache]\n default: {}\nnetworks:\n caddy_network:\n external: true\n name: caddy_network\n")
got := strings.Join(preDeployNetworks("shared", "redis", parsed), " ")
if got != "caddy_network shared_default" {
t.Fatalf("map-form networks resolved to %q", got)
}
}

// A pre-deploy on a service Shuttle does not build used to fail with "no pushed
// image digest" although the compose file pins its image.
func TestPreDeployUsesThePinnedImageOfAServiceThatIsNotBuilt(t *testing.T) {
const pinned = "services:\n redis:\n image: redis:7-alpine@sha256:57e4255cc971b1c8d6f8a6ca283ac01bc3ecdd914273ef6bfaede87aaecd6541\n"
cfg := &config.Config{App: "shared", Deploy: config.Deploy{PreDeploy: &config.PreDeploy{Service: "redis", Command: []string{"true"}}}}
// No signing key: the hook stops at Sign, after the image was chosen.
err := runPreDeployHook(cfg, nil, trustedHostIdentity{}, nil, "", map[string]string{}, secretManifest{}, parseComposeString(t, pinned))
if err == nil || strings.Contains(err.Error(), "no pushed image digest") {
t.Fatalf("the pinned compose image was not used: %v", err)
}
err = runPreDeployHook(cfg, nil, trustedHostIdentity{}, nil, "", map[string]string{}, secretManifest{}, parseComposeString(t, "services:\n redis:\n image: redis:7-alpine\n"))
if err == nil || !strings.Contains(err.Error(), "no pushed image digest") {
t.Fatalf("an image without a digest must still be refused, got %v", err)
}
// production.redis replaces the compose service with the generated one:
// its image is not the compose file's, so the hook must not run that one.
cfg.Production.Redis = true
err = runPreDeployHook(cfg, nil, trustedHostIdentity{}, nil, "", map[string]string{}, secretManifest{}, parseComposeString(t, pinned))
if err == nil || !strings.Contains(err.Error(), "no pushed image digest") {
t.Fatalf("the compose image of a generated service was used: %v", err)
}
rabbit := &config.Config{App: "shared", Production: config.ProductionConfig{RabbitMQ: true}, Deploy: config.Deploy{PreDeploy: &config.PreDeploy{Service: "rabbitmq", Command: []string{"true"}}}}
err = runPreDeployHook(rabbit, nil, trustedHostIdentity{}, nil, "", map[string]string{}, secretManifest{}, parseComposeString(t, "services:\n rabbitmq:\n image: rabbitmq:4-management-alpine@sha256:0452ee3fd3b9a74160b251e693338616b464f22df4d4ba43304c101bebdca292\n"))
if err == nil || !strings.Contains(err.Error(), "no pushed image digest") {
t.Fatalf("the compose image of the generated RabbitMQ was used: %v", err)
}
}

// The root helper builds a Caddy route from a dev.shuttle.domain deploy label
// alone; written in an internal application's compose file, it would publish
// the application its configuration declares unreachable. Checked through the
// preparation infra recreate runs, which shares checkDeployInputs with deploy.
func TestInternalStackRefusesARouteLabel(t *testing.T) {
const service = "services:\n web:\n build: .\n healthcheck:\n test: [\"CMD\", \"true\"]\n deploy:\n labels: "
for _, test := range []struct{ labels, want string }{
{"{dev.shuttle.domain: shared.example.com}", "dev.shuttle.domain"},
{"[\"dev.shuttle.domain=shared.example.com\"]", "dev.shuttle.domain"},
{"{team: infra}", ""},
} {
project := infraProject{cfg: adoptionApplyConfig(t)}
project.cfg.Expose = config.ExposeInternal
project.cfg.Infrastructure.PublicKey = writeOperatorPublicKey(t)
project.cfg.Setup.OperatorUser = "ops"
project.cfg.Setup.OperatorPublicKey = writeOperatorPublicKey(t)
compose := filepath.Join(t.TempDir(), "docker-compose.yml")
project.cfg.Deploy.ComposeFiles = []string{compose}
if err := os.WriteFile(compose, []byte(service+test.labels+"\n"), 0o600); err != nil {
t.Fatal(err)
}
_, err := prepareInfraRecreate(project)
if test.want == "" && err != nil {
t.Fatalf("labels %s were refused: %v", test.labels, err)
}
if test.want != "" && (err == nil || !strings.Contains(err.Error(), test.want)) {
t.Fatalf("labels %s were not refused: %v", test.labels, err)
}
}
}

func TestPreDeployServiceCreateUsesAOneShotJob(t *testing.T) {
args, err := preDeployServiceCreateArgs(rootplan.PreDeployOperation{
App: "api-core",
Expand Down
109 changes: 103 additions & 6 deletions app/go-cli/internal/cli/swarm_deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,16 @@ func deploySwarm(cfg *config.Config, skipBuild bool, dryRun bool, memoryPolicy m
return err
}
parsed, secretNames, secretPayload, buildServices := inputs.parsed, inputs.secretNames, inputs.secretPayload, inputs.buildServices

output.Header("Found %d services to build: %s", len(buildServices), strings.Join(buildServices, ", "))
// Nothing to build means nothing to push either: no builder, no build
// runner and no registry tunnel. The deploy goes straight to the signed
// stack, whose images are the digests the compose file names.
imageOnly := len(buildServices) == 0
if imageOnly {
skipBuild = true
output.Header("No services to build: every image is pinned by digest")
} else {
output.Header("Found %d services to build: %s", len(buildServices), strings.Join(buildServices, ", "))
}
output.Detail("Strategy: swarm (docker stack deploy with rolling updates)")
// Advice, never a refusal: a budget the project wrote itself that is too short
// for this stack's own healthchecks. The shipped defaults never trigger it.
Expand All @@ -225,7 +233,7 @@ func deploySwarm(cfg *config.Config, skipBuild bool, dryRun bool, memoryPolicy m
return err
}
var remoteBuild *ssh.BuildRunner
if cfg.Build.UsesSSH() {
if cfg.Build.UsesSSH() && !imageOnly {
remoteBuild, err = newSSHBuildRunner(cfg, group, host)
if err != nil {
return err
Expand Down Expand Up @@ -339,7 +347,7 @@ func deploySwarm(cfg *config.Config, skipBuild bool, dryRun bool, memoryPolicy m
}
}
registryAddr := "127.0.0.1:5000"
if !dryRun {
if !dryRun && !imageOnly {
localRegistryPort, err := allocateLoopbackPort()
if err != nil {
return fmt.Errorf("allocate registry tunnel port: %w", err)
Expand Down Expand Up @@ -412,7 +420,11 @@ func deploySwarm(cfg *config.Config, skipBuild bool, dryRun bool, memoryPolicy m
return err
}
}
fmt.Println("\n[dry-run] Would build, push through a verified SSH tunnel, and deploy via Swarm")
if imageOnly {
fmt.Println("\n[dry-run] Would deploy the pinned images via Swarm (nothing to build or push)")
} else {
fmt.Println("\n[dry-run] Would build, push through a verified SSH tunnel, and deploy via Swarm")
}
fmt.Printf("[dry-run] Version: %s\n", version)
// The printed stack is the stack a real deploy would apply: the derived
// secret names are in it, and no value ever is.
Expand Down Expand Up @@ -1059,6 +1071,72 @@ type deployInputs struct {
// `infra recreate` calls it before destroying the guest, so a refusal added
// here protects both paths; one added after it in deploySwarm leaves recreate
// with no retained stack to roll back to.
// validateDeclaredInfrastructureServices runs, before anything is reserved or
// destroyed, the account and data volume rules the root helper applies to a
// compose service named redis or rabbitmq (infrastructureVolumes). Refused only
// by the helper, such a stack left the operation in recovery_required, and
// `infra recreate` refused it after the guest was already destroyed. A service
// generated by production.redis or production.rabbitmq replaces the declared
// one and is skipped.
func validateDeclaredInfrastructureServices(parsed *composeFile, cfg *config.Config) error {
services, _ := parsed.Raw["services"].(map[string]any)
for _, runtime := range infrastructureRuntimes {
if runtime.service == "redis" && cfg.Production.Redis || runtime.service == "rabbitmq" && cfg.Production.RabbitMQ {
continue
}
raw, declared := services[runtime.service]
if !declared {
continue
}
service, _ := raw.(map[string]any)
if strings.TrimSpace(fmt.Sprint(service["user"])) != runtime.user() {
return fmt.Errorf("service %s must run as %q, the account that owns its data volume", runtime.service, runtime.user())
}
volume := cfg.App + "_" + runtime.service + "_data"
volumes, _ := service["volumes"].([]any)
mounted := false
for _, entry := range volumes {
if source, target, valid := rootVolumeSourceTarget(entry); valid && source == volume && target == runtime.target {
mounted = true
break
}
}
if !mounted {
return fmt.Errorf("service %s must mount the volume keyed %s at %s", runtime.service, volume, runtime.target)
}
}
return nil
}

// validateInternalStackHasNoRoute keeps "publishes nothing" true for an
// internal application: the root helper builds a Caddy route from a
// dev.shuttle.domain deploy label alone, so one written in the compose file
// would publish the service the configuration says is unreachable, and which
// may update stop-first for that reason.
func validateInternalStackHasNoRoute(parsed *composeFile, cfg *config.Config) error {
if !cfg.IsInternal() {
return nil
}
services, _ := parsed.Raw["services"].(map[string]any)
for name, raw := range services {
service, _ := raw.(map[string]any)
deploy, _ := service["deploy"].(map[string]any)
switch labels := deploy["labels"].(type) {
case map[string]any:
if _, present := labels["dev.shuttle.domain"]; present {
return fmt.Errorf("service %s declares dev.shuttle.domain, which would publish an internal application", name)
}
case []any:
for _, label := range labels {
if key, _, _ := strings.Cut(fmt.Sprint(label), "="); strings.TrimSpace(key) == "dev.shuttle.domain" {
return fmt.Errorf("service %s declares dev.shuttle.domain, which would publish an internal application", name)
}
}
}
}
return nil
}

func checkDeployInputs(cfg *config.Config) (deployInputs, error) {
if err := validateDeployEnvironment(cfg); err != nil {
return deployInputs{}, err
Expand All @@ -1075,6 +1153,12 @@ func checkDeployInputs(cfg *config.Config) (deployInputs, error) {
if err := validateConfiguredSecretServices(parsed, cfg); err != nil {
return deployInputs{}, err
}
if err := validateDeclaredInfrastructureServices(parsed, cfg); err != nil {
return deployInputs{}, err
}
if err := validateInternalStackHasNoRoute(parsed, cfg); err != nil {
return deployInputs{}, err
}
// Swarm mounts files; it does not export them. Custom images used to fail
// at startup without any explanation here. Neither a preset name nor a
// Dockerfile proves the runtime image's behaviour (including --skip-build),
Expand Down Expand Up @@ -1109,8 +1193,21 @@ func checkDeployInputs(cfg *config.Config) (deployInputs, error) {
if len(cfg.Build.Services) > 0 {
buildServices = configuredBuildServices(cfg.Build)
}
// An application made only of published images (an infrastructure stack
// such as Redis plus RabbitMQ) has nothing to build. It is deployable when
// every service names its image by digest: that digest is then the release
// identity a build would otherwise produce.
if len(buildServices) == 0 {
return deployInputs{}, fmt.Errorf("no services with build: found in %s", deployComposeFiles(cfg)[0])
names := make([]string, 0, len(parsed.Services))
for name := range parsed.Services {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
if !digestImage.MatchString(strings.TrimSpace(parsed.Services[name].Image)) {
return deployInputs{}, fmt.Errorf("no services with build: found in %s, and service %s has no image pinned by digest (image@sha256:...)", deployComposeFiles(cfg)[0], name)
}
}
}
return deployInputs{parsed: parsed, secretNames: secretNames, secretPayload: secretPayload, buildServices: buildServices}, nil
}
Expand Down
10 changes: 9 additions & 1 deletion app/go-cli/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -1554,11 +1554,19 @@ func validate(cfg *Config) error {
if web.Healthcheck.Path == "" || !strings.HasPrefix(web.Healthcheck.Path, "/") || strings.ContainsAny(web.Healthcheck.Path, "\r\n") {
return fmt.Errorf("services.%s.healthcheck.path must be an absolute HTTP path", primary)
}
// An internal application publishes nothing: its primary service is not
// behind Caddy, so stop-first there leaves no route without an answer. It
// is what a single-instance stateful service (Redis, RabbitMQ) needs to
// never run two tasks on one data volume.
published := primary
if cfg.IsInternal() {
published = ""
}
for _, name := range sortedServiceNames(cfg.Services) {
if err := validateServiceResources(name, cfg.Services[name]); err != nil {
return err
}
if err := validateServiceUpdateOrder(name, cfg.Services[name], primary); err != nil {
if err := validateServiceUpdateOrder(name, cfg.Services[name], published); err != nil {
return err
}
if err := validateServiceUpdateParallelism(name, cfg.Services[name]); err != nil {
Expand Down
Loading
Loading