mirror of
https://github.com/psviderski/uncloud.git
synced 2026-08-26 19:13:34 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5a1e61ccff | ||
|
|
db60a81b2d | ||
|
|
7c19323ea1 | ||
|
|
290e6db98e | ||
|
|
df29d9ba43 | ||
|
|
64769081d9 | ||
|
|
0107363d41 | ||
|
|
48dc1dd624 | ||
|
|
3a6eef410a | ||
|
|
9f5ca9a33d | ||
|
|
b046b78398 | ||
|
|
ff213e71d3 | ||
|
|
3cda5cc564 | ||
|
|
75fdbaf2f4 | ||
|
|
81f4e3a67a | ||
|
|
e99e769455 | ||
|
|
11949eeb3b | ||
|
|
b437659678 | ||
|
|
c01365b416 | ||
|
|
813c397644 | ||
|
|
5cc005a423 | ||
|
|
066d411367 | ||
|
|
03970862ab | ||
|
|
8bf9fc0c9c | ||
|
|
93fef88fac | ||
|
|
455174ccb0 |
@@ -1,3 +1,11 @@
|
||||
[tools."aqua:vektra/mockery"]
|
||||
version = "3.5.3"
|
||||
backend = "aqua:vektra/mockery"
|
||||
|
||||
[tools."aqua:vektra/mockery".checksums]
|
||||
"mockery_3.5.3_Darwin_arm64.tar.gz" = "sha256:a3a94b14c7414e148f2252199ffc4a0108d311358f3d336cbe05bb73cb203704"
|
||||
"mockery_3.5.3_Linux_x86_64.tar.gz" = "sha256:ebce416b0175338525246c376885a1579ca6cd4d4015140ba0c70e6b5339a39c"
|
||||
|
||||
[tools.go]
|
||||
version = "1.23.10"
|
||||
backend = "core:go"
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
experimental = true
|
||||
|
||||
[tools]
|
||||
"aqua:vektra/mockery" = "3.5.3"
|
||||
go = "1.23"
|
||||
golangci-lint = "2.2.2"
|
||||
protoc = "27.3"
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
packages:
|
||||
github.com/psviderski/uncloud/internal/machine/caddyconfig:
|
||||
interfaces:
|
||||
CaddyfileValidator:
|
||||
@@ -66,6 +66,10 @@ ucind-image:
|
||||
ucind-multiarch-image-push:
|
||||
docker buildx build --push --platform linux/amd64,linux/arm64 -t "$(UCIND_IMAGE)" --target ucind .
|
||||
|
||||
.PHONY: mocks
|
||||
mocks:
|
||||
@mockery
|
||||
|
||||
.PHONY: test
|
||||
test:
|
||||
ifeq ($(TEST_NAME),)
|
||||
@@ -111,3 +115,6 @@ _lint:
|
||||
# Uncloud daemon won't likely support OS other than Linux anytime soon, so for now we can rely on that.
|
||||
GOOS=linux golangci-lint run $(ARGS)
|
||||
|
||||
.PHONY: cli-docs
|
||||
cli-docs:
|
||||
go run ./cmd/uncloud docs
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package caddy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/alecthomas/chroma/v2/quick"
|
||||
"github.com/psviderski/uncloud/internal/cli"
|
||||
"github.com/psviderski/uncloud/pkg/api"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
type configOptions struct {
|
||||
machine string
|
||||
noColor bool
|
||||
context string
|
||||
}
|
||||
|
||||
func NewConfigCommand() *cobra.Command {
|
||||
opts := configOptions{}
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "config",
|
||||
Short: "Show the current Caddy configuration (Caddyfile).",
|
||||
Long: "Display the current Caddy configuration (Caddyfile) from the connected machine or a specified one.",
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
uncli := cmd.Context().Value("cli").(*cli.CLI)
|
||||
return runConfig(cmd.Context(), uncli, opts)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&opts.machine, "machine", "m", "",
|
||||
"Name or ID of the machine to get the configuration from. (default is connected machine)")
|
||||
cmd.Flags().BoolVar(&opts.noColor, "no-color", false,
|
||||
"Disable syntax highlighting for the output.")
|
||||
cmd.Flags().StringVarP(
|
||||
&opts.context, "context", "c", "",
|
||||
"Name of the cluster context. (default is the current context)",
|
||||
)
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runConfig(ctx context.Context, uncli *cli.CLI, opts configOptions) error {
|
||||
clusterClient, err := uncli.ConnectCluster(ctx, opts.context)
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect to cluster: %w", err)
|
||||
}
|
||||
defer clusterClient.Close()
|
||||
|
||||
if opts.machine != "" {
|
||||
// If a specific machine is requested, use it to get the Caddy configuration.
|
||||
ctx, _, err = api.ProxyMachinesContext(ctx, clusterClient, []string{opts.machine})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
config, err := clusterClient.Caddy.GetConfig(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get Caddy config: %w", err)
|
||||
}
|
||||
|
||||
// Print the Caddyfile with syntax highlighting.
|
||||
if opts.noColor {
|
||||
fmt.Print(config.Caddyfile)
|
||||
} else {
|
||||
if err = quick.Highlight(os.Stdout, config.Caddyfile, "caddy", "terminal256", "monokai"); err != nil {
|
||||
// If highlighting fails, fall back to plain output.
|
||||
fmt.Print(config.Caddyfile)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
@@ -18,9 +19,10 @@ import (
|
||||
)
|
||||
|
||||
type deployOptions struct {
|
||||
image string
|
||||
machines []string
|
||||
context string
|
||||
caddyfile string
|
||||
image string
|
||||
machines []string
|
||||
context string
|
||||
}
|
||||
|
||||
func NewDeployCommand() *cobra.Command {
|
||||
@@ -37,6 +39,8 @@ func NewDeployCommand() *cobra.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVar(&opts.caddyfile, "caddyfile", "",
|
||||
"Path to a custom global Caddy config (Caddyfile) that will be prepended to the auto-generated Caddy config.")
|
||||
cmd.Flags().StringVar(&opts.image, "image", "",
|
||||
"Caddy Docker image to deploy. (default caddy:LATEST_VERSION)")
|
||||
cmd.Flags().StringSliceVarP(&opts.machines, "machine", "m", nil,
|
||||
@@ -51,6 +55,15 @@ func NewDeployCommand() *cobra.Command {
|
||||
}
|
||||
|
||||
func runDeploy(ctx context.Context, uncli *cli.CLI, opts deployOptions) error {
|
||||
caddyfile := ""
|
||||
if opts.caddyfile != "" {
|
||||
data, err := os.ReadFile(opts.caddyfile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read Caddyfile: %w", err)
|
||||
}
|
||||
caddyfile = strings.TrimSpace(string(data))
|
||||
}
|
||||
|
||||
clusterClient, err := uncli.ConnectCluster(ctx, opts.context)
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect to cluster: %w", err)
|
||||
@@ -91,7 +104,7 @@ func runDeploy(ctx context.Context, uncli *cli.CLI, opts deployOptions) error {
|
||||
placement := api.Placement{
|
||||
Machines: cli.ExpandCommaSeparatedValues(opts.machines),
|
||||
}
|
||||
d, err := clusterClient.NewCaddyDeployment(opts.image, placement)
|
||||
d, err := clusterClient.NewCaddyDeployment(opts.image, caddyfile, placement)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create caddy deployment: %w", err)
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ func NewRootCommand() *cobra.Command {
|
||||
Short: "Manage Caddy reverse proxy service.",
|
||||
}
|
||||
cmd.AddCommand(
|
||||
NewConfigCommand(),
|
||||
NewDeployCommand(),
|
||||
)
|
||||
return cmd
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
const docsDir = "website/docs/9-cli-reference"
|
||||
|
||||
type cmdWrapper struct {
|
||||
cmd *cobra.Command
|
||||
}
|
||||
|
||||
// NewDocsCommand creates a new hidden command to generate CLI reference docs.
|
||||
func NewDocsCommand() *cobra.Command {
|
||||
wrapper := &cmdWrapper{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "docs",
|
||||
Short: "Generate Uncloud CLI reference docs",
|
||||
SilenceUsage: true,
|
||||
DisableFlagsInUseLine: true,
|
||||
Hidden: true,
|
||||
Args: cobra.NoArgs,
|
||||
ValidArgsFunction: cobra.NoFileCompletions,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
// Remove existing markdown files.
|
||||
mdFiles, err := filepath.Glob(filepath.Join(docsDir, "*.md"))
|
||||
if err != nil {
|
||||
return fmt.Errorf("list existing CLI docs: %w", err)
|
||||
}
|
||||
for _, f := range mdFiles {
|
||||
if err = os.Remove(f); err != nil {
|
||||
return fmt.Errorf("remove '%s': %w", f, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Generate new CLI reference docs.
|
||||
wrapper.cmd.Root().DisableAutoGenTag = true
|
||||
if err := doc.GenMarkdownTree(cmd.Root(), docsDir); err != nil {
|
||||
return fmt.Errorf("generate CLI docs: %w", err)
|
||||
}
|
||||
|
||||
// Remove *completion*.md files that contain malformatted code blocks that break Docusaurus.
|
||||
mdFiles, err = filepath.Glob(filepath.Join(docsDir, "*completion*.md"))
|
||||
if err != nil {
|
||||
return fmt.Errorf("list generated CLI docs: %w", err)
|
||||
}
|
||||
for _, f := range mdFiles {
|
||||
if err = os.Remove(f); err != nil {
|
||||
return fmt.Errorf("remove '%s': %w", f, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Post-process generated markdown files.
|
||||
mdFiles, err = filepath.Glob(filepath.Join(docsDir, "*.md"))
|
||||
if err != nil {
|
||||
return fmt.Errorf("list generated CLI docs: %w", err)
|
||||
}
|
||||
|
||||
for _, f := range mdFiles {
|
||||
if err = postProcessMarkdown(f); err != nil {
|
||||
return fmt.Errorf("post-process '%s': %w", f, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
wrapper.cmd = cmd
|
||||
return cmd
|
||||
}
|
||||
|
||||
// postProcessMarkdown applies transformations to generated markdown files.
|
||||
func postProcessMarkdown(filename string) error {
|
||||
data, err := os.ReadFile(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
content := string(data)
|
||||
|
||||
// Replace "SEE ALSO" with "See also".
|
||||
content = strings.ReplaceAll(content, "SEE ALSO", "See also")
|
||||
// Escape <id> to avoid Docusaurus treating it as an HTML tag.
|
||||
content = strings.ReplaceAll(content, "<id>", "\\<id>")
|
||||
|
||||
// Remove broken links to completion docs.
|
||||
if strings.Contains(content, "[uc completion") {
|
||||
lines := strings.Split(content, "\n")
|
||||
var filteredLines []string
|
||||
for _, line := range lines {
|
||||
if !strings.Contains(line, "[uc completion") {
|
||||
filteredLines = append(filteredLines, line)
|
||||
}
|
||||
}
|
||||
content = strings.Join(filteredLines, "\n")
|
||||
}
|
||||
|
||||
// Adjust heading levels. Process from shortest to longest to avoid double replacements.
|
||||
replacements := []struct {
|
||||
old, new string
|
||||
}{
|
||||
{`(?m)^## `, `# `},
|
||||
{`(?m)^### `, `## `},
|
||||
{`(?m)^#### `, `### `},
|
||||
{`(?m)^##### `, `#### `},
|
||||
}
|
||||
|
||||
for _, r := range replacements {
|
||||
re := regexp.MustCompile(r.old)
|
||||
content = re.ReplaceAllString(content, r.new)
|
||||
}
|
||||
|
||||
return os.WriteFile(filename, []byte(content), 0o644)
|
||||
}
|
||||
@@ -146,7 +146,7 @@ func add(ctx context.Context, uncli *cli.CLI, remoteMachine *cli.RemoteMachine,
|
||||
|
||||
// TODO: scale the existing Caddy service to the new machine instead of running a new deployment
|
||||
// that may cause a small downtime.
|
||||
d, err := clusterClient.NewCaddyDeployment(caddyImage, api.Placement{})
|
||||
d, err := clusterClient.NewCaddyDeployment(caddyImage, "", api.Placement{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("create caddy deployment: %w", err)
|
||||
}
|
||||
|
||||
@@ -147,7 +147,7 @@ func initCluster(ctx context.Context, uncli *cli.CLI, remoteMachine *cli.RemoteM
|
||||
}
|
||||
|
||||
if !opts.noCaddy {
|
||||
d, err := client.NewCaddyDeployment("", api.Placement{})
|
||||
d, err := client.NewCaddyDeployment("", "", api.Placement{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("create caddy deployment: %w", err)
|
||||
}
|
||||
|
||||
+2
-1
@@ -27,7 +27,7 @@ type globalOptions struct {
|
||||
func main() {
|
||||
opts := globalOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "uncloud",
|
||||
Use: "uc",
|
||||
Short: "A CLI tool for managing Uncloud resources such as clusters, machines, and services.",
|
||||
Version: version.String(),
|
||||
SilenceUsage: true,
|
||||
@@ -75,6 +75,7 @@ func main() {
|
||||
|
||||
cmd.AddCommand(
|
||||
NewDeployCommand(),
|
||||
NewDocsCommand(),
|
||||
NewBuildCommand(),
|
||||
caddy.NewRootCommand(),
|
||||
cmdcontext.NewRootCommand(),
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
)
|
||||
|
||||
type runOptions struct {
|
||||
caddyfile string
|
||||
command []string
|
||||
cpu dockeropts.NanoCPUs
|
||||
entrypoint string
|
||||
@@ -57,6 +58,9 @@ func NewRunCommand() *cobra.Command {
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVar(&opts.caddyfile, "caddyfile", "",
|
||||
"Path to a custom Caddy config (Caddyfile) for the service. "+
|
||||
"Cannot be used together with non-@host published ports.")
|
||||
cmd.Flags().VarP(&opts.cpu, "cpu", "",
|
||||
"Maximum number of CPU cores a service container can use. Fractional values are allowed: "+
|
||||
"0.5 for half a core or 2.25 for two and a quarter cores.")
|
||||
@@ -82,7 +86,7 @@ func NewRunCommand() *cobra.Command {
|
||||
"Give extended privileges to service containers. This is a security risk and should be used with caution.")
|
||||
cmd.Flags().StringSliceVarP(&opts.publish, "publish", "p", nil,
|
||||
"Publish a service port to make it accessible outside the cluster. Can be specified multiple times.\n"+
|
||||
"Format: [hostname:][load_balancer_port:]container_port[/protocol] or [host_ip:]:host_port:container_port[/protocol]@host\n"+
|
||||
"Format: [hostname:]container_port[/protocol] or [host_ip:]host_port:container_port[/protocol]@host\n"+
|
||||
"Supported protocols: tcp, udp, http, https (default is tcp). If a hostname for http(s) port is not specified\n"+
|
||||
"and a cluster domain is reserved, service-name.cluster-domain will be used as the hostname.\n"+
|
||||
"Examples:\n"+
|
||||
@@ -161,6 +165,15 @@ func run(ctx context.Context, uncli *cli.CLI, opts runOptions) error {
|
||||
func prepareServiceSpec(opts runOptions) (api.ServiceSpec, error) {
|
||||
var spec api.ServiceSpec
|
||||
|
||||
caddyfile := ""
|
||||
if opts.caddyfile != "" {
|
||||
data, err := os.ReadFile(opts.caddyfile)
|
||||
if err != nil {
|
||||
return spec, fmt.Errorf("read Caddyfile: %w", err)
|
||||
}
|
||||
caddyfile = strings.TrimSpace(string(data))
|
||||
}
|
||||
|
||||
env, err := parseEnv(opts.env)
|
||||
if err != nil {
|
||||
return spec, err
|
||||
@@ -218,6 +231,12 @@ func prepareServiceSpec(opts runOptions) (api.ServiceSpec, error) {
|
||||
Volumes: volumes,
|
||||
}
|
||||
|
||||
if caddyfile != "" {
|
||||
spec.Caddy = &api.CaddySpec{
|
||||
Config: caddyfile,
|
||||
}
|
||||
}
|
||||
|
||||
// Overwrite the default ENTRYPOINT of the image or reset it if an empty string is passed.
|
||||
if opts.entrypoint != "" {
|
||||
spec.Container.Entrypoint = []string{opts.entrypoint}
|
||||
|
||||
@@ -6,6 +6,7 @@ require (
|
||||
github.com/BurntSushi/toml v1.4.0
|
||||
github.com/Masterminds/semver v1.5.0
|
||||
github.com/Masterminds/squirrel v1.5.4
|
||||
github.com/alecthomas/chroma/v2 v2.20.0
|
||||
github.com/caddyserver/caddy/v2 v2.8.4
|
||||
github.com/cenkalti/backoff/v4 v4.3.0
|
||||
github.com/charmbracelet/huh v0.6.0
|
||||
@@ -108,6 +109,7 @@ require (
|
||||
github.com/dgraph-io/badger/v2 v2.2007.4 // indirect
|
||||
github.com/dgraph-io/ristretto v0.1.1 // indirect
|
||||
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
|
||||
github.com/dlclark/regexp2 v1.11.5 // indirect
|
||||
github.com/docker/buildx v0.18.0 // indirect
|
||||
github.com/docker/distribution v2.8.3+incompatible // indirect
|
||||
github.com/docker/docker-credential-helpers v0.8.2 // indirect
|
||||
@@ -265,6 +267,7 @@ require (
|
||||
github.com/spf13/cast v1.7.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/stoewer/go-strcase v1.2.0 // indirect
|
||||
github.com/stretchr/objx v0.5.2 // indirect
|
||||
github.com/tailscale/tscert v0.0.0-20240517230440-bbccfbf48933 // indirect
|
||||
github.com/theupdateframework/notary v0.7.0 // indirect
|
||||
github.com/tonistiigi/dchapes-mode v0.0.0-20241001053921-ca0759fec205 // indirect
|
||||
|
||||
@@ -53,6 +53,12 @@ github.com/OneOfOne/xxhash v1.2.8/go.mod h1:eZbhyaAYD41SGSSsnmcpxVoRiQ/MPUTjUdII
|
||||
github.com/Shopify/logrus-bugsnag v0.0.0-20170309145241-6dbc35f2c30d/go.mod h1:HI8ITrYtUY+O+ZhtlqUnD8+KwNPOyugEhfP9fdUIaEQ=
|
||||
github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d h1:UrqY+r/OJnIp5u0s1SbQ8dVfLCZJsnvazdBP5hS4iRs=
|
||||
github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d/go.mod h1:HI8ITrYtUY+O+ZhtlqUnD8+KwNPOyugEhfP9fdUIaEQ=
|
||||
github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=
|
||||
github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
|
||||
github.com/alecthomas/chroma/v2 v2.20.0 h1:sfIHpxPyR07/Oylvmcai3X/exDlE8+FA820NTz+9sGw=
|
||||
github.com/alecthomas/chroma/v2 v2.20.0/go.mod h1:e7tViK0xh/Nf4BYHl00ycY6rV7b8iXBksI9E359yNmA=
|
||||
github.com/alecthomas/repr v0.5.1 h1:E3G4t2QbHTSNpPKBgMTln5KLkZHLOcU7r37J4pXBuIg=
|
||||
github.com/alecthomas/repr v0.5.1/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
|
||||
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||
@@ -259,6 +265,8 @@ github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WA
|
||||
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
|
||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
|
||||
github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/docker/buildx v0.18.0 h1:rSauXHeJt90NvtXrLK5J992Eb0UPJZs2vV3u1zTf1nE=
|
||||
github.com/docker/buildx v0.18.0/go.mod h1:JGNSshOhHs5FhG3u51jXUf4lLOeD2QBIlJ2vaRB67p4=
|
||||
github.com/docker/cli v27.5.0+incompatible h1:aMphQkcGtpHixwwhAXJT1rrK/detk2JIvDaFkLctbGM=
|
||||
@@ -487,6 +495,8 @@ github.com/hashicorp/memberlist v0.5.1 h1:mk5dRuzeDNis2bi6LLoQIXfMH7JQvAzt3mQD0v
|
||||
github.com/hashicorp/memberlist v0.5.1/go.mod h1:zGDXV6AqbDTKTM6yxW0I4+JtFzZAJVoIPvss4hV8F24=
|
||||
github.com/hashicorp/serf v0.10.1 h1:Z1H2J60yRKvfDYAOZLd2MU0ND4AH/WDz7xYHDWQsIPY=
|
||||
github.com/hashicorp/serf v0.10.1/go.mod h1:yL2t6BqATOLGc5HF7qbFkTfXoPIY0WZdWHfEvMqbG+4=
|
||||
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
|
||||
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/huandu/xstrings v1.3.1/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
|
||||
github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
|
||||
@@ -1039,6 +1049,7 @@ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
|
||||
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.34.2
|
||||
// protoc v5.27.3
|
||||
// source: internal/machine/api/pb/caddy.proto
|
||||
|
||||
package pb
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
emptypb "google.golang.org/protobuf/types/known/emptypb"
|
||||
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type GetCaddyConfigResponse struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
// The generated Caddyfile content.
|
||||
Caddyfile string `protobuf:"bytes,1,opt,name=caddyfile,proto3" json:"caddyfile,omitempty"`
|
||||
// Timestamp when the config was last modified.
|
||||
ModifiedAt *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=modified_at,json=modifiedAt,proto3" json:"modified_at,omitempty"`
|
||||
}
|
||||
|
||||
func (x *GetCaddyConfigResponse) Reset() {
|
||||
*x = GetCaddyConfigResponse{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_internal_machine_api_pb_caddy_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *GetCaddyConfigResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*GetCaddyConfigResponse) ProtoMessage() {}
|
||||
|
||||
func (x *GetCaddyConfigResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_internal_machine_api_pb_caddy_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use GetCaddyConfigResponse.ProtoReflect.Descriptor instead.
|
||||
func (*GetCaddyConfigResponse) Descriptor() ([]byte, []int) {
|
||||
return file_internal_machine_api_pb_caddy_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *GetCaddyConfigResponse) GetCaddyfile() string {
|
||||
if x != nil {
|
||||
return x.Caddyfile
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *GetCaddyConfigResponse) GetModifiedAt() *timestamppb.Timestamp {
|
||||
if x != nil {
|
||||
return x.ModifiedAt
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var File_internal_machine_api_pb_caddy_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_internal_machine_api_pb_caddy_proto_rawDesc = []byte{
|
||||
0x0a, 0x23, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x6d, 0x61, 0x63, 0x68, 0x69,
|
||||
0x6e, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x70, 0x62, 0x2f, 0x63, 0x61, 0x64, 0x64, 0x79, 0x2e,
|
||||
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x03, 0x61, 0x70, 0x69, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67,
|
||||
0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74,
|
||||
0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f,
|
||||
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61,
|
||||
0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x73, 0x0a, 0x16, 0x47, 0x65, 0x74, 0x43,
|
||||
0x61, 0x64, 0x64, 0x79, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
|
||||
0x73, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x63, 0x61, 0x64, 0x64, 0x79, 0x66, 0x69, 0x6c, 0x65, 0x18,
|
||||
0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x63, 0x61, 0x64, 0x64, 0x79, 0x66, 0x69, 0x6c, 0x65,
|
||||
0x12, 0x3b, 0x0a, 0x0b, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18,
|
||||
0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70,
|
||||
0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d,
|
||||
0x70, 0x52, 0x0a, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x41, 0x74, 0x32, 0x49, 0x0a,
|
||||
0x05, 0x43, 0x61, 0x64, 0x64, 0x79, 0x12, 0x40, 0x0a, 0x09, 0x47, 0x65, 0x74, 0x43, 0x6f, 0x6e,
|
||||
0x66, 0x69, 0x67, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f,
|
||||
0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1b, 0x2e, 0x61, 0x70,
|
||||
0x69, 0x2e, 0x47, 0x65, 0x74, 0x43, 0x61, 0x64, 0x64, 0x79, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67,
|
||||
0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x37, 0x5a, 0x35, 0x67, 0x69, 0x74, 0x68,
|
||||
0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x70, 0x73, 0x76, 0x69, 0x64, 0x65, 0x72, 0x73, 0x6b,
|
||||
0x69, 0x2f, 0x75, 0x6e, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e,
|
||||
0x61, 0x6c, 0x2f, 0x6d, 0x61, 0x63, 0x68, 0x69, 0x6e, 0x65, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x70,
|
||||
0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_internal_machine_api_pb_caddy_proto_rawDescOnce sync.Once
|
||||
file_internal_machine_api_pb_caddy_proto_rawDescData = file_internal_machine_api_pb_caddy_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_internal_machine_api_pb_caddy_proto_rawDescGZIP() []byte {
|
||||
file_internal_machine_api_pb_caddy_proto_rawDescOnce.Do(func() {
|
||||
file_internal_machine_api_pb_caddy_proto_rawDescData = protoimpl.X.CompressGZIP(file_internal_machine_api_pb_caddy_proto_rawDescData)
|
||||
})
|
||||
return file_internal_machine_api_pb_caddy_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_internal_machine_api_pb_caddy_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
|
||||
var file_internal_machine_api_pb_caddy_proto_goTypes = []any{
|
||||
(*GetCaddyConfigResponse)(nil), // 0: api.GetCaddyConfigResponse
|
||||
(*timestamppb.Timestamp)(nil), // 1: google.protobuf.Timestamp
|
||||
(*emptypb.Empty)(nil), // 2: google.protobuf.Empty
|
||||
}
|
||||
var file_internal_machine_api_pb_caddy_proto_depIdxs = []int32{
|
||||
1, // 0: api.GetCaddyConfigResponse.modified_at:type_name -> google.protobuf.Timestamp
|
||||
2, // 1: api.Caddy.GetConfig:input_type -> google.protobuf.Empty
|
||||
0, // 2: api.Caddy.GetConfig:output_type -> api.GetCaddyConfigResponse
|
||||
2, // [2:3] is the sub-list for method output_type
|
||||
1, // [1:2] is the sub-list for method input_type
|
||||
1, // [1:1] is the sub-list for extension type_name
|
||||
1, // [1:1] is the sub-list for extension extendee
|
||||
0, // [0:1] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_internal_machine_api_pb_caddy_proto_init() }
|
||||
func file_internal_machine_api_pb_caddy_proto_init() {
|
||||
if File_internal_machine_api_pb_caddy_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_internal_machine_api_pb_caddy_proto_msgTypes[0].Exporter = func(v any, i int) any {
|
||||
switch v := v.(*GetCaddyConfigResponse); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_internal_machine_api_pb_caddy_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 1,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_internal_machine_api_pb_caddy_proto_goTypes,
|
||||
DependencyIndexes: file_internal_machine_api_pb_caddy_proto_depIdxs,
|
||||
MessageInfos: file_internal_machine_api_pb_caddy_proto_msgTypes,
|
||||
}.Build()
|
||||
File_internal_machine_api_pb_caddy_proto = out.File
|
||||
file_internal_machine_api_pb_caddy_proto_rawDesc = nil
|
||||
file_internal_machine_api_pb_caddy_proto_goTypes = nil
|
||||
file_internal_machine_api_pb_caddy_proto_depIdxs = nil
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package api;
|
||||
|
||||
option go_package = "github.com/psviderski/uncloud/internal/machine/api/pb";
|
||||
|
||||
import "google/protobuf/empty.proto";
|
||||
import "google/protobuf/timestamp.proto";
|
||||
|
||||
service Caddy {
|
||||
// GetConfig retrieves the current Caddy configuration from the machine.
|
||||
rpc GetConfig(google.protobuf.Empty) returns (GetCaddyConfigResponse);
|
||||
}
|
||||
|
||||
message GetCaddyConfigResponse {
|
||||
// The generated Caddyfile content.
|
||||
string caddyfile = 1;
|
||||
// Timestamp when the config was last modified.
|
||||
google.protobuf.Timestamp modified_at = 2;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.5.1
|
||||
// - protoc v5.27.3
|
||||
// source: internal/machine/api/pb/caddy.proto
|
||||
|
||||
package pb
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
emptypb "google.golang.org/protobuf/types/known/emptypb"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.64.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
Caddy_GetConfig_FullMethodName = "/api.Caddy/GetConfig"
|
||||
)
|
||||
|
||||
// CaddyClient is the client API for Caddy service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type CaddyClient interface {
|
||||
// GetConfig retrieves the current Caddy configuration from the machine.
|
||||
GetConfig(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*GetCaddyConfigResponse, error)
|
||||
}
|
||||
|
||||
type caddyClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewCaddyClient(cc grpc.ClientConnInterface) CaddyClient {
|
||||
return &caddyClient{cc}
|
||||
}
|
||||
|
||||
func (c *caddyClient) GetConfig(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*GetCaddyConfigResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetCaddyConfigResponse)
|
||||
err := c.cc.Invoke(ctx, Caddy_GetConfig_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CaddyServer is the server API for Caddy service.
|
||||
// All implementations must embed UnimplementedCaddyServer
|
||||
// for forward compatibility.
|
||||
type CaddyServer interface {
|
||||
// GetConfig retrieves the current Caddy configuration from the machine.
|
||||
GetConfig(context.Context, *emptypb.Empty) (*GetCaddyConfigResponse, error)
|
||||
mustEmbedUnimplementedCaddyServer()
|
||||
}
|
||||
|
||||
// UnimplementedCaddyServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedCaddyServer struct{}
|
||||
|
||||
func (UnimplementedCaddyServer) GetConfig(context.Context, *emptypb.Empty) (*GetCaddyConfigResponse, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetConfig not implemented")
|
||||
}
|
||||
func (UnimplementedCaddyServer) mustEmbedUnimplementedCaddyServer() {}
|
||||
func (UnimplementedCaddyServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeCaddyServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to CaddyServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeCaddyServer interface {
|
||||
mustEmbedUnimplementedCaddyServer()
|
||||
}
|
||||
|
||||
func RegisterCaddyServer(s grpc.ServiceRegistrar, srv CaddyServer) {
|
||||
// If the following call pancis, it indicates UnimplementedCaddyServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&Caddy_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _Caddy_GetConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(emptypb.Empty)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(CaddyServer).GetConfig(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: Caddy_GetConfig_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(CaddyServer).GetConfig(ctx, req.(*emptypb.Empty))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// Caddy_ServiceDesc is the grpc.ServiceDesc for Caddy service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var Caddy_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "api.Caddy",
|
||||
HandlerType: (*CaddyServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "GetConfig",
|
||||
Handler: _Caddy_GetConfig_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{},
|
||||
Metadata: "internal/machine/api/pb/caddy.proto",
|
||||
}
|
||||
@@ -1,17 +1,331 @@
|
||||
package caddyconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"github.com/psviderski/uncloud/internal/machine/store"
|
||||
"github.com/psviderski/uncloud/pkg/api"
|
||||
)
|
||||
|
||||
func GenerateCaddyfile(containers []api.ServiceContainer, verifyResponse string) (string, error) {
|
||||
return fmt.Sprintf(`http:// {
|
||||
handle %s {
|
||||
respond "%s" 200
|
||||
const (
|
||||
caddyfileHeader = `# This file is autogenerated by Uncloud based on the configuration of running services.
|
||||
# Do not edit manually. Any manual changes will be overwritten on the next update.
|
||||
`
|
||||
caddyfileTemplate = `# Health check endpoint to verify Caddy reachability on this machine.
|
||||
http:// {
|
||||
handle {{.VerifyPath}} {
|
||||
respond "{{.VerifyResponse}}" 200
|
||||
}
|
||||
log
|
||||
}
|
||||
`, VerifyPath, verifyResponse), nil
|
||||
|
||||
(common_proxy) {
|
||||
# Retry failed requests up to lb_retries times against other available upstreams.
|
||||
lb_retries 3
|
||||
# Upstreams are marked unhealthy for fail_duration after a failed request (passive health checking).
|
||||
fail_duration 30s
|
||||
}
|
||||
{{- if or .HTTPHostUpstreams .HTTPSHostUpstreams }}
|
||||
|
||||
# Sites generated from service ports.{{end}}
|
||||
{{- range $hostname, $upstreams := .HTTPHostUpstreams}}
|
||||
|
||||
http://{{$hostname}} {
|
||||
reverse_proxy {{join $upstreams " "}} {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}{{end}}
|
||||
{{- range $hostname, $upstreams := .HTTPSHostUpstreams}}
|
||||
|
||||
https://{{$hostname}} {
|
||||
reverse_proxy {{join $upstreams " "}} {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}{{end}}
|
||||
`
|
||||
)
|
||||
|
||||
// CaddyfileGenerator generates a Caddyfile configuration for the Caddy reverse proxy.
|
||||
type CaddyfileGenerator struct {
|
||||
// machineID is the unique identifier of the machine where the controller is running.
|
||||
machineID string
|
||||
validator CaddyfileValidator
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// CaddyfileValidator is an interface for validating Caddyfile configurations.
|
||||
type CaddyfileValidator interface {
|
||||
Validate(ctx context.Context, caddyfile string) error
|
||||
}
|
||||
|
||||
func NewCaddyfileGenerator(machineID string, validator CaddyfileValidator, log *slog.Logger) *CaddyfileGenerator {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
return &CaddyfileGenerator{
|
||||
machineID: machineID,
|
||||
validator: validator,
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
// Generate creates a Caddyfile configuration based on the provided service containers.
|
||||
// The Caddyfile is generated from the service ports of the healthy containers.
|
||||
// If a 'caddy' service container is running on this machine and defines a custom Caddy config (x-caddy) in its service
|
||||
// spec, it will be validated and prepended to the generated Caddyfile. Custom Caddy configs (x-caddy) defined in other
|
||||
// service specs are validated and appended to the generated Caddyfile. Invalid configs are logged and skipped to ensure
|
||||
// the generated Caddyfile remains valid.
|
||||
//
|
||||
// The final Caddyfile structure includes:
|
||||
//
|
||||
// [caddy x-caddy (global config)]
|
||||
// [generated Caddyfile from all service ports]
|
||||
// [service-a x-caddy]
|
||||
// ...
|
||||
// [service-z x-caddy]
|
||||
func (g *CaddyfileGenerator) Generate(ctx context.Context, records []store.ContainerRecord) (string, error) {
|
||||
containers := make([]api.ServiceContainer, len(records))
|
||||
for i, cr := range records {
|
||||
containers[i] = cr.Container
|
||||
}
|
||||
// Sort containers by service name and creation time to generate a stable Caddyfile.
|
||||
slices.SortStableFunc(containers, func(a, b api.ServiceContainer) int {
|
||||
return cmp.Or(
|
||||
strings.Compare(a.ServiceName(), b.ServiceName()),
|
||||
a.CreatedTime().Compare(b.CreatedTime()),
|
||||
)
|
||||
})
|
||||
|
||||
caddyfile, err := g.generateBaseFromPorts(containers)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("generate base Caddyfile from service ports: %w", err)
|
||||
}
|
||||
|
||||
upstreams := serviceUpstreams(containers)
|
||||
// Track validation errors for reporting.
|
||||
var configErrors []string
|
||||
|
||||
// Find the 'caddy' service container on this machine. Use the most recent one if multiple exist.
|
||||
var caddyCtr *api.ServiceContainer
|
||||
for _, cr := range records {
|
||||
if cr.MachineID == g.machineID && cr.Container.ServiceName() == CaddyServiceName &&
|
||||
(caddyCtr == nil || cr.Container.CreatedTime().Compare(caddyCtr.CreatedTime()) > 0) {
|
||||
caddyCtr = &cr.Container
|
||||
}
|
||||
}
|
||||
|
||||
// If the caddy container is running on this machine and has a custom Caddy config (global),
|
||||
// prepend it to the generated Caddyfile and validate it.
|
||||
if caddyCtr != nil && caddyCtr.ServiceSpec.CaddyConfig() != "" {
|
||||
// Render the custom global Caddy config as a Go template with the upstreams.
|
||||
tmplCtx := templateContext{
|
||||
Name: caddyCtr.ServiceName(),
|
||||
Upstreams: upstreams,
|
||||
}
|
||||
renderedConfig, err := renderCaddyfile(tmplCtx, caddyCtr.ServiceSpec.CaddyConfig())
|
||||
if err != nil {
|
||||
g.log.Error("Failed to render template directives in user-defined global Caddy config, skipping it.",
|
||||
"service", caddyCtr.ServiceName(), "container", caddyCtr.ID, "err", err)
|
||||
configErrors = append(configErrors,
|
||||
fmt.Sprintf("service '%s': failed to render template: %v", caddyCtr.ServiceName(), err))
|
||||
} else {
|
||||
caddyfileCandidate := fmt.Sprintf("# User-defined global config from service '%s'.\n%s\n\n%s",
|
||||
caddyCtr.ServiceName(), renderedConfig, caddyfile)
|
||||
|
||||
if err = g.validator.Validate(ctx, caddyfileCandidate); err != nil {
|
||||
g.log.Error("User-defined global Caddy config is invalid, skipping it.",
|
||||
"service", caddyCtr.ServiceName(), "container", caddyCtr.ID, "err", err)
|
||||
configErrors = append(configErrors,
|
||||
fmt.Sprintf("service '%s': validation failed: %v", caddyCtr.ServiceName(), err))
|
||||
} else {
|
||||
caddyfile = caddyfileCandidate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// There could be multiple service containers for the same service with different custom Caddy configs, for example,
|
||||
// if the service has been partially updated. The most recent container for each service defines the current custom
|
||||
// Caddy config for that service.
|
||||
latestServiceContainers := make(map[string]api.ServiceContainer, len(containers))
|
||||
for _, ctr := range containers {
|
||||
if latest, ok := latestServiceContainers[ctr.ServiceName()]; ok {
|
||||
if ctr.CreatedTime().Compare(latest.CreatedTime()) > 0 {
|
||||
latestServiceContainers[ctr.ServiceName()] = ctr
|
||||
}
|
||||
} else {
|
||||
latestServiceContainers[ctr.ServiceName()] = ctr
|
||||
}
|
||||
}
|
||||
sortedServiceNames := slices.Sorted(maps.Keys(latestServiceContainers))
|
||||
|
||||
// Append a custom Caddy config for each service to the Caddyfile and validate it. If the config for a service
|
||||
// is invalid, skip it but continue processing other services to ensure the Caddyfile remains valid.
|
||||
for _, serviceName := range sortedServiceNames {
|
||||
// Skip the caddy container as we already processed it.
|
||||
if serviceName == CaddyServiceName {
|
||||
continue
|
||||
}
|
||||
|
||||
ctr := latestServiceContainers[serviceName]
|
||||
if ctr.ServiceSpec.CaddyConfig() == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Render the template actions in the service's Caddy config.
|
||||
tmplCtx := templateContext{
|
||||
Name: serviceName,
|
||||
Upstreams: upstreams,
|
||||
}
|
||||
renderedConfig, err := renderCaddyfile(tmplCtx, ctr.ServiceSpec.CaddyConfig())
|
||||
if err != nil {
|
||||
g.log.Error("Failed to render template directives in user-defined Caddy config for service, skipping it.",
|
||||
"service", serviceName, "err", err)
|
||||
configErrors = append(configErrors,
|
||||
fmt.Sprintf("service '%s': failed to render template: %v", serviceName, err))
|
||||
continue
|
||||
}
|
||||
|
||||
caddyfileCandidate := fmt.Sprintf("%s\n# User-defined config for service '%s'.\n%s\n",
|
||||
caddyfile, serviceName, renderedConfig)
|
||||
if err = g.validator.Validate(ctx, caddyfileCandidate); err != nil {
|
||||
g.log.Error("User-defined Caddy config for service is invalid, skipping it.",
|
||||
"service", serviceName, "err", err)
|
||||
configErrors = append(configErrors, fmt.Sprintf("service '%s': validation failed: %v", serviceName, err))
|
||||
} else {
|
||||
caddyfile = caddyfileCandidate
|
||||
}
|
||||
}
|
||||
|
||||
// Append error summary as comment if there were any invalid configs.
|
||||
if len(configErrors) > 0 {
|
||||
errorsComment := "# Skipped invalid user-defined configs:\n"
|
||||
for _, e := range configErrors {
|
||||
errorsComment += fmt.Sprintf("# - %s\n", e)
|
||||
}
|
||||
|
||||
caddyfile += "\n" + errorsComment
|
||||
}
|
||||
|
||||
return caddyfileHeader + "\n" + caddyfile, nil
|
||||
}
|
||||
|
||||
func (g *CaddyfileGenerator) generateBaseFromPorts(containers []api.ServiceContainer) (string, error) {
|
||||
httpHostUpstreams, httpsHostUpstreams := httpUpstreamsFromPorts(containers)
|
||||
|
||||
funcs := template.FuncMap{"join": strings.Join}
|
||||
tmpl, err := template.New("Caddyfile").Funcs(funcs).Parse(caddyfileTemplate)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("parse Caddyfile template: %w", err)
|
||||
}
|
||||
|
||||
data := struct {
|
||||
VerifyPath string
|
||||
VerifyResponse string
|
||||
HTTPHostUpstreams map[string][]string
|
||||
HTTPSHostUpstreams map[string][]string
|
||||
}{
|
||||
VerifyPath: VerifyPath,
|
||||
VerifyResponse: g.machineID,
|
||||
HTTPHostUpstreams: httpHostUpstreams,
|
||||
HTTPSHostUpstreams: httpsHostUpstreams,
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err = tmpl.Execute(&buf, data); err != nil {
|
||||
return "", fmt.Errorf("execute Caddyfile template: %w", err)
|
||||
}
|
||||
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
// httpUpstreamsFromPorts extracts upstreams for HTTP and HTTPS protocols from the published ports of the provided
|
||||
// service containers. It's expected that all containers are healthy.
|
||||
func httpUpstreamsFromPorts(containers []api.ServiceContainer) (map[string][]string, map[string][]string) {
|
||||
// Maps hostnames to lists of upstreams (container IP:port pairs).
|
||||
httpHostUpstreams := make(map[string][]string)
|
||||
httpsHostUpstreams := make(map[string][]string)
|
||||
for _, ctr := range containers {
|
||||
ip := ctr.UncloudNetworkIP()
|
||||
if !ip.IsValid() {
|
||||
// Container is not connected to the uncloud Docker network (could be host network).
|
||||
continue
|
||||
}
|
||||
log := slog.With("container", ctr.ID)
|
||||
|
||||
ports, err := ctr.ServicePorts()
|
||||
if err != nil {
|
||||
log.Error("Failed to parse service ports for container.", "err", err)
|
||||
continue
|
||||
}
|
||||
|
||||
for _, port := range ports {
|
||||
if port.Mode != api.PortModeIngress {
|
||||
continue
|
||||
}
|
||||
|
||||
switch port.Protocol {
|
||||
case api.ProtocolHTTP:
|
||||
upstream := net.JoinHostPort(ip.String(), strconv.Itoa(int(port.ContainerPort)))
|
||||
httpHostUpstreams[port.Hostname] = append(httpHostUpstreams[port.Hostname], upstream)
|
||||
case api.ProtocolHTTPS:
|
||||
upstream := net.JoinHostPort(ip.String(), strconv.Itoa(int(port.ContainerPort)))
|
||||
httpsHostUpstreams[port.Hostname] = append(httpsHostUpstreams[port.Hostname], upstream)
|
||||
default:
|
||||
// TODO: implement L4 ingress routing for TCP and UDP.
|
||||
log.Error("Unsupported protocol for ingress port.", "port", port)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return httpHostUpstreams, httpsHostUpstreams
|
||||
}
|
||||
|
||||
// serviceUpstreams creates a map of service names to their container IPs.
|
||||
// Only includes containers connected to the uncloud Docker network.
|
||||
func serviceUpstreams(containers []api.ServiceContainer) map[string][]string {
|
||||
upstreams := make(map[string][]string)
|
||||
for _, ctr := range containers {
|
||||
ip := ctr.UncloudNetworkIP()
|
||||
if !ip.IsValid() {
|
||||
// Container is not connected to the uncloud Docker network (could be host network).
|
||||
continue
|
||||
}
|
||||
|
||||
serviceName := ctr.ServiceName()
|
||||
upstreams[serviceName] = append(upstreams[serviceName], ip.String())
|
||||
}
|
||||
|
||||
return upstreams
|
||||
}
|
||||
|
||||
// renderCaddyfile renders a Caddyfile template with the upstreams function and data.
|
||||
func renderCaddyfile(tmplCtx templateContext, caddyfile string) (string, error) {
|
||||
funcs := template.FuncMap{
|
||||
"upstreams": upstreamsTemplateFn(tmplCtx),
|
||||
}
|
||||
|
||||
tmpl, err := template.New("Caddyfile").Funcs(funcs).Parse(caddyfile)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("parse config as Go template: %w", err)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err = tmpl.Execute(&buf, tmplCtx); err != nil {
|
||||
return "", fmt.Errorf("execute template: %w", err)
|
||||
}
|
||||
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,933 @@
|
||||
package caddyconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/docker/docker/api/types"
|
||||
"github.com/docker/docker/api/types/container"
|
||||
"github.com/docker/docker/api/types/network"
|
||||
"github.com/psviderski/uncloud/internal/machine/docker"
|
||||
"github.com/psviderski/uncloud/internal/machine/store"
|
||||
"github.com/psviderski/uncloud/pkg/api"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCaddyfileGenerator(t *testing.T) {
|
||||
caddyfileHeader := `# This file is autogenerated by Uncloud based on the configuration of running services.
|
||||
# Do not edit manually. Any manual changes will be overwritten on the next update.
|
||||
|
||||
# Health check endpoint to verify Caddy reachability on this machine.
|
||||
http:// {
|
||||
handle /.uncloud-verify {
|
||||
respond "test-machine-id" 200
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
(common_proxy) {
|
||||
# Retry failed requests up to lb_retries times against other available upstreams.
|
||||
lb_retries 3
|
||||
# Upstreams are marked unhealthy for fail_duration after a failed request (passive health checking).
|
||||
fail_duration 30s
|
||||
}
|
||||
`
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
containers []store.ContainerRecord
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "empty containers",
|
||||
containers: []store.ContainerRecord{},
|
||||
want: caddyfileHeader,
|
||||
},
|
||||
{
|
||||
name: "HTTP container",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecord(newContainer("10.210.0.2", "app.example.com:8080/http"), "mach1"),
|
||||
},
|
||||
want: caddyfileHeader + `
|
||||
# Sites generated from service ports.
|
||||
|
||||
http://app.example.com {
|
||||
reverse_proxy 10.210.0.2:8080 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "load balancing multiple containers",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecord(newContainer("10.210.0.2", "app.example.com:8080/http"), "mach1"),
|
||||
newContainerRecord(newContainer("10.210.0.3", "app.example.com:8080/http"), "mach1"),
|
||||
},
|
||||
want: caddyfileHeader + `
|
||||
# Sites generated from service ports.
|
||||
|
||||
http://app.example.com {
|
||||
reverse_proxy 10.210.0.2:8080 10.210.0.3:8080 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "HTTPS container",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecord(newContainer("10.210.0.2", "secure.example.com:8000/https"), "mach1"),
|
||||
},
|
||||
want: caddyfileHeader + `
|
||||
# Sites generated from service ports.
|
||||
|
||||
https://secure.example.com {
|
||||
reverse_proxy 10.210.0.2:8000 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "mixed HTTP and HTTPS",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecord(
|
||||
newContainer("10.210.0.2",
|
||||
"app.example.com:8080/http",
|
||||
"web.example.com:8000/http"),
|
||||
"mach1",
|
||||
),
|
||||
newContainerRecord(
|
||||
newContainer("10.210.0.3",
|
||||
"app.example.com:8080/http",
|
||||
"secure.example.com:8888/https"),
|
||||
"mach1",
|
||||
),
|
||||
newContainerRecord(
|
||||
newContainer("10.210.0.4",
|
||||
"web.example.com:8000/http",
|
||||
"secure.example.com:8888/https"),
|
||||
"mach1",
|
||||
),
|
||||
newContainerRecord(
|
||||
newContainer("10.210.0.5",
|
||||
"app.example.com:8080/http",
|
||||
"web.example.com:8000/http",
|
||||
"secure.example.com:8888/https"),
|
||||
"mach1",
|
||||
),
|
||||
},
|
||||
want: caddyfileHeader + `
|
||||
# Sites generated from service ports.
|
||||
|
||||
http://app.example.com {
|
||||
reverse_proxy 10.210.0.2:8080 10.210.0.3:8080 10.210.0.5:8080 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
http://web.example.com {
|
||||
reverse_proxy 10.210.0.2:8000 10.210.0.4:8000 10.210.0.5:8000 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
https://secure.example.com {
|
||||
reverse_proxy 10.210.0.3:8888 10.210.0.4:8888 10.210.0.5:8888 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "container without uncloud network ignored",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecord(newContainerWithoutNetwork("ignored.example.com:8080/http"), "mach1"),
|
||||
},
|
||||
want: caddyfileHeader,
|
||||
},
|
||||
{
|
||||
name: "container with invalid port ignored",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecord(newContainer("10.210.0.2", "invalid-port"), "mach1"),
|
||||
},
|
||||
want: caddyfileHeader,
|
||||
},
|
||||
{
|
||||
name: "containers with unsupported protocols and host mode ignored",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecord(newContainer("10.210.0.2", "5000/tcp"), "mach1"),
|
||||
newContainerRecord(newContainer("10.210.0.3", "5000/udp"), "mach1"),
|
||||
newContainerRecord(newContainer("10.210.0.4", "80:8080/tcp@host"), "mach1"),
|
||||
},
|
||||
want: caddyfileHeader,
|
||||
},
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Validator is not expected to be called in these tests.
|
||||
generator := NewCaddyfileGenerator("test-machine-id", nil, nil)
|
||||
|
||||
config, err := generator.Generate(ctx, tt.containers)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, tt.want, config, "Generated Caddyfile doesn't match")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaddyfileGeneratorWithCustomConfigs(t *testing.T) {
|
||||
caddyfileBase := `# This file is autogenerated by Uncloud based on the configuration of running services.
|
||||
# Do not edit manually. Any manual changes will be overwritten on the next update.
|
||||
|
||||
# Health check endpoint to verify Caddy reachability on this machine.
|
||||
http:// {
|
||||
handle /.uncloud-verify {
|
||||
respond "test-machine-id" 200
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
(common_proxy) {
|
||||
# Retry failed requests up to lb_retries times against other available upstreams.
|
||||
lb_retries 3
|
||||
# Upstreams are marked unhealthy for fail_duration after a failed request (passive health checking).
|
||||
fail_duration 30s
|
||||
}
|
||||
`
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
containers []store.ContainerRecord
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "caddy service with valid global config",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"caddy",
|
||||
"10.210.0.2",
|
||||
`# Global Caddy configuration
|
||||
{
|
||||
global directive
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
},
|
||||
want: `# This file is autogenerated by Uncloud based on the configuration of running services.
|
||||
# Do not edit manually. Any manual changes will be overwritten on the next update.
|
||||
|
||||
# User-defined global config from service 'caddy'.
|
||||
# Global Caddy configuration
|
||||
{
|
||||
global directive
|
||||
}
|
||||
|
||||
# Health check endpoint to verify Caddy reachability on this machine.
|
||||
http:// {
|
||||
handle /.uncloud-verify {
|
||||
respond "test-machine-id" 200
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
(common_proxy) {
|
||||
# Retry failed requests up to lb_retries times against other available upstreams.
|
||||
lb_retries 3
|
||||
# Upstreams are marked unhealthy for fail_duration after a failed request (passive health checking).
|
||||
fail_duration 30s
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "regular service with valid custom config",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"web",
|
||||
"10.210.0.2",
|
||||
`# Custom config for web service
|
||||
web.example.com {
|
||||
reverse_proxy web:3000
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
},
|
||||
want: caddyfileBase + `
|
||||
# User-defined config for service 'web'.
|
||||
# Custom config for web service
|
||||
web.example.com {
|
||||
reverse_proxy web:3000
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "service with invalid config is skipped",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"bad-service",
|
||||
"10.210.0.2",
|
||||
`# test:invalid
|
||||
bad.config.com {
|
||||
respond "This config is invalid"
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
},
|
||||
want: caddyfileBase + `
|
||||
# Skipped invalid user-defined configs:
|
||||
# - service 'bad-service': validation failed: invalid config detected
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "service with invalid config template is skipped",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"bad-template",
|
||||
"10.210.0.2",
|
||||
`
|
||||
bad.template.com {
|
||||
reverse_proxy {{upstreams
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
},
|
||||
want: caddyfileBase + `
|
||||
# Skipped invalid user-defined configs:
|
||||
# - service 'bad-template': failed to render template: parse config as Go template: template: Caddyfile:3: unexpected "}" in operand
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "caddy service with invalid global config is skipped",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"caddy",
|
||||
"10.210.0.2",
|
||||
`# test:invalid
|
||||
localhost {
|
||||
respond "Invalid global config"
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
},
|
||||
want: caddyfileBase + `
|
||||
# Skipped invalid user-defined configs:
|
||||
# - service 'caddy': validation failed: invalid config detected
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "caddy service on different machine is ignored",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"caddy",
|
||||
"10.210.0.2",
|
||||
`# Global config from other machine
|
||||
{
|
||||
global directive
|
||||
}`,
|
||||
"other-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
},
|
||||
want: caddyfileBase,
|
||||
},
|
||||
{
|
||||
name: "multiple services with mixed valid and invalid configs",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"api",
|
||||
"10.210.0.2",
|
||||
`api.example.com {
|
||||
reverse_proxy api:8080
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"invalid-svc",
|
||||
"10.210.0.3",
|
||||
`# test:invalid
|
||||
bad.example.com {
|
||||
respond "Invalid"
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"web",
|
||||
"10.210.0.4",
|
||||
`web.example.com {
|
||||
reverse_proxy web:3000
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
},
|
||||
want: caddyfileBase + `
|
||||
# User-defined config for service 'api'.
|
||||
api.example.com {
|
||||
reverse_proxy api:8080
|
||||
}
|
||||
|
||||
# User-defined config for service 'web'.
|
||||
web.example.com {
|
||||
reverse_proxy web:3000
|
||||
}
|
||||
|
||||
# Skipped invalid user-defined configs:
|
||||
# - service 'invalid-svc': validation failed: invalid config detected
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "combined: caddy global config + service configs + ports",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"caddy",
|
||||
"10.210.0.1",
|
||||
`# Global config
|
||||
{
|
||||
global directive
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
newContainerRecordWithPorts(
|
||||
"app",
|
||||
"10.210.0.2",
|
||||
[]string{"app.example.com:8080/http"},
|
||||
"test-machine-id",
|
||||
),
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"api",
|
||||
"10.210.0.3",
|
||||
`api.example.com {
|
||||
reverse_proxy api:8000
|
||||
}`,
|
||||
"other-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
},
|
||||
want: `# This file is autogenerated by Uncloud based on the configuration of running services.
|
||||
# Do not edit manually. Any manual changes will be overwritten on the next update.
|
||||
|
||||
# User-defined global config from service 'caddy'.
|
||||
# Global config
|
||||
{
|
||||
global directive
|
||||
}
|
||||
|
||||
# Health check endpoint to verify Caddy reachability on this machine.
|
||||
http:// {
|
||||
handle /.uncloud-verify {
|
||||
respond "test-machine-id" 200
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
(common_proxy) {
|
||||
# Retry failed requests up to lb_retries times against other available upstreams.
|
||||
lb_retries 3
|
||||
# Upstreams are marked unhealthy for fail_duration after a failed request (passive health checking).
|
||||
fail_duration 30s
|
||||
}
|
||||
|
||||
# Sites generated from service ports.
|
||||
|
||||
http://app.example.com {
|
||||
reverse_proxy 10.210.0.2:8080 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
# User-defined config for service 'api'.
|
||||
api.example.com {
|
||||
reverse_proxy api:8000
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "service with template directives using upstreams",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"web",
|
||||
"10.210.0.2",
|
||||
`web.example.com {
|
||||
reverse_proxy {{upstreams}}
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
newContainerRecordWithPorts(
|
||||
"api",
|
||||
"10.210.0.3",
|
||||
[]string{"api.example.com:8080/http"},
|
||||
"test-machine-id",
|
||||
),
|
||||
},
|
||||
want: caddyfileBase + `
|
||||
# Sites generated from service ports.
|
||||
|
||||
http://api.example.com {
|
||||
reverse_proxy 10.210.0.3:8080 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
# User-defined config for service 'web'.
|
||||
web.example.com {
|
||||
reverse_proxy 10.210.0.2
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "only most recent container config is used per service",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"web",
|
||||
"10.210.0.2",
|
||||
`# Old config
|
||||
old.example.com {
|
||||
respond "Old"
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now().Add(-1*time.Hour),
|
||||
),
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"web",
|
||||
"10.210.0.3",
|
||||
`# New config
|
||||
new.example.com {
|
||||
respond "New"
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
},
|
||||
want: caddyfileBase + `
|
||||
# User-defined config for service 'web'.
|
||||
# New config
|
||||
new.example.com {
|
||||
respond "New"
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "compound test: upstreams variants, global caddy, and multi-machine services",
|
||||
containers: []store.ContainerRecord{
|
||||
// Global Caddy service on test-machine-id
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"caddy",
|
||||
"10.210.1.1",
|
||||
`# Global config from test machine
|
||||
{
|
||||
admin off
|
||||
}
|
||||
|
||||
localhost:8080 {
|
||||
respond "Admin panel"
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
// Another caddy on different machine (should be ignored)
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"caddy",
|
||||
"10.210.2.1",
|
||||
`# Should be ignored
|
||||
{
|
||||
debug
|
||||
}`,
|
||||
"machine-2",
|
||||
time.Now(),
|
||||
),
|
||||
|
||||
// API service containers across different machines
|
||||
newContainerRecordWithPorts("api", "10.210.1.2", []string{"api.example.com:8080/http"},
|
||||
"test-machine-id"),
|
||||
newContainerRecordWithPorts("api", "10.210.2.2", []string{"api.example.com:8080/http"}, "machine-2"),
|
||||
newContainerRecordWithPorts("api", "10.210.3.2", []string{"api.example.com:8080/http"}, "machine-3"),
|
||||
|
||||
// Web service with different versions on different machines
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"web",
|
||||
"10.210.1.3",
|
||||
`# Web service config v1 (older)
|
||||
web-v1.example.com {
|
||||
reverse_proxy web:3000
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now().Add(-2*time.Hour),
|
||||
),
|
||||
newContainerRecordWithPorts("web", "10.210.3.3", []string{"web.example.com:3000/http"}, "machine-3"),
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"web",
|
||||
"10.210.2.3",
|
||||
`# Web service config v2 (most recent)
|
||||
web-v2.example.com {
|
||||
reverse_proxy {{upstreams 8080}}
|
||||
}`,
|
||||
"machine-2",
|
||||
time.Now().Add(1*time.Second),
|
||||
),
|
||||
|
||||
// DB service with custom config
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"db",
|
||||
"10.210.1.4",
|
||||
`# DB admin panel
|
||||
dbadmin.example.com {
|
||||
basicauth {
|
||||
admin $2a$14$Zkx19XLiW6VYouLHR5NmfOFU0z2GTNmpkT/5qqR7hx4IjWJPDhjvG
|
||||
}
|
||||
reverse_proxy {{upstreams 5432}}
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
|
||||
// Gateway service with various upstream template usages
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"gateway",
|
||||
"10.210.1.5",
|
||||
`# Testing different upstream template functions
|
||||
gateway.example.com {
|
||||
# Current service upstreams (gateway)
|
||||
handle /self {
|
||||
reverse_proxy {{upstreams}}
|
||||
}
|
||||
|
||||
# Named service upstreams without port
|
||||
handle /api {
|
||||
reverse_proxy {{upstreams "api"}}
|
||||
}
|
||||
|
||||
# Named service upstreams with port
|
||||
handle /api-custom {
|
||||
reverse_proxy {{upstreams "api" 9000}}
|
||||
}
|
||||
|
||||
# Current service with name and port
|
||||
handle /self-port {
|
||||
reverse_proxy {{upstreams .Name 8888}}
|
||||
}
|
||||
|
||||
# Service with mixed containers (web) and advanced template
|
||||
handle /web {
|
||||
reverse_proxy {{- range $ip := index .Upstreams "web"}} https://{{$ip}}{{end}}
|
||||
}
|
||||
|
||||
# Non-existent service
|
||||
handle /missing {
|
||||
reverse_proxy {{upstreams "nonexistent"}}
|
||||
}
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
|
||||
// App service with just ports (no custom config)
|
||||
newContainerRecordWithPorts("app", "10.210.1.6", []string{"app.example.com:3000/http"},
|
||||
"test-machine-id"),
|
||||
newContainerRecordWithPorts("app", "10.210.2.6", []string{"app.example.com:3000/http"}, "machine-2"),
|
||||
|
||||
// Service with invalid config (should be ignored)
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"invalid",
|
||||
"10.210.1.7",
|
||||
`# test:invalid
|
||||
badconfig.com {
|
||||
respond "This config is invalid"
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
},
|
||||
want: `# This file is autogenerated by Uncloud based on the configuration of running services.
|
||||
# Do not edit manually. Any manual changes will be overwritten on the next update.
|
||||
|
||||
# User-defined global config from service 'caddy'.
|
||||
# Global config from test machine
|
||||
{
|
||||
admin off
|
||||
}
|
||||
|
||||
localhost:8080 {
|
||||
respond "Admin panel"
|
||||
}
|
||||
|
||||
# Health check endpoint to verify Caddy reachability on this machine.
|
||||
http:// {
|
||||
handle /.uncloud-verify {
|
||||
respond "test-machine-id" 200
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
(common_proxy) {
|
||||
# Retry failed requests up to lb_retries times against other available upstreams.
|
||||
lb_retries 3
|
||||
# Upstreams are marked unhealthy for fail_duration after a failed request (passive health checking).
|
||||
fail_duration 30s
|
||||
}
|
||||
|
||||
# Sites generated from service ports.
|
||||
|
||||
http://api.example.com {
|
||||
reverse_proxy 10.210.1.2:8080 10.210.2.2:8080 10.210.3.2:8080 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
http://app.example.com {
|
||||
reverse_proxy 10.210.1.6:3000 10.210.2.6:3000 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
http://web.example.com {
|
||||
reverse_proxy 10.210.3.3:3000 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
# User-defined config for service 'db'.
|
||||
# DB admin panel
|
||||
dbadmin.example.com {
|
||||
basicauth {
|
||||
admin $2a$14$Zkx19XLiW6VYouLHR5NmfOFU0z2GTNmpkT/5qqR7hx4IjWJPDhjvG
|
||||
}
|
||||
reverse_proxy 10.210.1.4:5432
|
||||
}
|
||||
|
||||
# User-defined config for service 'gateway'.
|
||||
# Testing different upstream template functions
|
||||
gateway.example.com {
|
||||
# Current service upstreams (gateway)
|
||||
handle /self {
|
||||
reverse_proxy 10.210.1.5
|
||||
}
|
||||
|
||||
# Named service upstreams without port
|
||||
handle /api {
|
||||
reverse_proxy 10.210.1.2 10.210.2.2 10.210.3.2
|
||||
}
|
||||
|
||||
# Named service upstreams with port
|
||||
handle /api-custom {
|
||||
reverse_proxy 10.210.1.2:9000 10.210.2.2:9000 10.210.3.2:9000
|
||||
}
|
||||
|
||||
# Current service with name and port
|
||||
handle /self-port {
|
||||
reverse_proxy 10.210.1.5:8888
|
||||
}
|
||||
|
||||
# Service with mixed containers (web) and advanced template
|
||||
handle /web {
|
||||
reverse_proxy https://10.210.1.3 https://10.210.3.3 https://10.210.2.3
|
||||
}
|
||||
|
||||
# Non-existent service
|
||||
handle /missing {
|
||||
` + "\t\treverse_proxy " + `
|
||||
}
|
||||
}
|
||||
|
||||
# User-defined config for service 'web'.
|
||||
# Web service config v2 (most recent)
|
||||
web-v2.example.com {
|
||||
reverse_proxy 10.210.1.3:8080 10.210.3.3:8080 10.210.2.3:8080
|
||||
}
|
||||
|
||||
# Skipped invalid user-defined configs:
|
||||
# - service 'invalid': validation failed: invalid config detected
|
||||
`,
|
||||
},
|
||||
{
|
||||
name: "multiple errors: invalid global, template error, and validation error",
|
||||
containers: []store.ContainerRecord{
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"caddy",
|
||||
"10.210.0.1",
|
||||
`# test:invalid
|
||||
{
|
||||
invalid global
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"broken-template",
|
||||
"10.210.0.2",
|
||||
`broken.example.com {
|
||||
reverse_proxy {{upstreams "missing
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"invalid",
|
||||
"10.210.0.3",
|
||||
`# test:invalid
|
||||
invalid.example.com {
|
||||
respond "Invalid config"
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
newContainerRecordWithCaddyConfig(
|
||||
"valid",
|
||||
"10.210.0.4",
|
||||
`valid.example.com {
|
||||
respond "Valid config"
|
||||
}`,
|
||||
"test-machine-id",
|
||||
time.Now(),
|
||||
),
|
||||
},
|
||||
want: caddyfileBase + `
|
||||
# User-defined config for service 'valid'.
|
||||
valid.example.com {
|
||||
respond "Valid config"
|
||||
}
|
||||
|
||||
# Skipped invalid user-defined configs:
|
||||
# - service 'caddy': validation failed: invalid config detected
|
||||
# - service 'broken-template': failed to render template: parse config as Go template: template: Caddyfile:2: unterminated quoted string
|
||||
# - service 'invalid': validation failed: invalid config detected
|
||||
`,
|
||||
},
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
validator := NewMockCaddyfileValidator(t)
|
||||
validator.EXPECT().Validate(mock.Anything, mock.Anything).RunAndReturn(
|
||||
func(ctx context.Context, caddyfile string) error {
|
||||
if strings.Contains(caddyfile, "# test:invalid") {
|
||||
return errors.New("invalid config detected")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
generator := NewCaddyfileGenerator("test-machine-id", validator, nil)
|
||||
|
||||
config, err := generator.Generate(ctx, tt.containers)
|
||||
|
||||
if tt.wantErr {
|
||||
assert.Error(t, err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, tt.want, config, "Generated Caddyfile doesn't match")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newContainerRecord(ctr api.ServiceContainer, machineID string) store.ContainerRecord {
|
||||
return store.ContainerRecord{
|
||||
Container: ctr,
|
||||
MachineID: machineID,
|
||||
}
|
||||
}
|
||||
|
||||
func newContainerRecordWithCaddyConfig(serviceName, ip, caddyConfig, machineID string, created time.Time) store.ContainerRecord {
|
||||
return store.ContainerRecord{
|
||||
Container: api.ServiceContainer{
|
||||
Container: api.Container{
|
||||
ContainerJSON: types.ContainerJSON{
|
||||
ContainerJSONBase: &types.ContainerJSONBase{
|
||||
ID: serviceName + "-" + ip, // Add ID for stable sorting
|
||||
State: &types.ContainerState{
|
||||
Running: true,
|
||||
},
|
||||
Created: created.UTC().Format(time.RFC3339Nano),
|
||||
},
|
||||
NetworkSettings: &types.NetworkSettings{
|
||||
Networks: map[string]*network.EndpointSettings{
|
||||
docker.NetworkName: {
|
||||
IPAddress: ip,
|
||||
},
|
||||
},
|
||||
},
|
||||
Config: &container.Config{
|
||||
Labels: map[string]string{
|
||||
api.LabelServiceName: serviceName,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
ServiceSpec: api.ServiceSpec{
|
||||
Caddy: &api.CaddySpec{
|
||||
Config: caddyConfig,
|
||||
},
|
||||
},
|
||||
},
|
||||
MachineID: machineID,
|
||||
}
|
||||
}
|
||||
|
||||
func newContainerRecordWithPorts(serviceName, ip string, ports []string, machineID string) store.ContainerRecord {
|
||||
portsLabel := strings.Join(ports, ",")
|
||||
return store.ContainerRecord{
|
||||
Container: api.ServiceContainer{
|
||||
Container: api.Container{
|
||||
ContainerJSON: types.ContainerJSON{
|
||||
ContainerJSONBase: &types.ContainerJSONBase{
|
||||
ID: serviceName + "-" + ip, // Add ID for stable sorting
|
||||
State: &types.ContainerState{
|
||||
Running: true,
|
||||
},
|
||||
Created: time.Now().UTC().Format(time.RFC3339Nano),
|
||||
},
|
||||
NetworkSettings: &types.NetworkSettings{
|
||||
Networks: map[string]*network.EndpointSettings{
|
||||
docker.NetworkName: {
|
||||
IPAddress: ip,
|
||||
},
|
||||
},
|
||||
},
|
||||
Config: &container.Config{
|
||||
Labels: map[string]string{
|
||||
api.LabelServiceName: serviceName,
|
||||
api.LabelServicePorts: portsLabel,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
MachineID: machineID,
|
||||
}
|
||||
}
|
||||
@@ -14,21 +14,23 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
CaddyGroup = "uncloud"
|
||||
VerifyPath = "/.uncloud-verify"
|
||||
CaddyServiceName = "caddy"
|
||||
CaddyGroup = "uncloud"
|
||||
VerifyPath = "/.uncloud-verify"
|
||||
)
|
||||
|
||||
// Controller monitors container changes in the cluster store and generates a configuration file for Caddy reverse
|
||||
// proxy. The generated configuration allows Caddy to route external traffic to service containers across the internal
|
||||
// network.
|
||||
type Controller struct {
|
||||
store *store.Store
|
||||
configDir string
|
||||
verifyResponse string
|
||||
log *slog.Logger
|
||||
machineID string
|
||||
configDir string
|
||||
generator *CaddyfileGenerator
|
||||
store *store.Store
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewController(store *store.Store, configDir string, verifyResponse string) (*Controller, error) {
|
||||
func NewController(machineID, configDir, adminSock string, store *store.Store) (*Controller, error) {
|
||||
if err := os.MkdirAll(configDir, 0o750); err != nil {
|
||||
return nil, fmt.Errorf("create directory for Caddy configuration '%s': %w", configDir, err)
|
||||
}
|
||||
@@ -36,27 +38,28 @@ func NewController(store *store.Store, configDir string, verifyResponse string)
|
||||
return nil, fmt.Errorf("change owner of directory for Caddy configuration '%s': %w", configDir, err)
|
||||
}
|
||||
|
||||
log := slog.With("component", "caddy-controller")
|
||||
validator := NewCaddyAdminValidator(adminSock)
|
||||
generator := NewCaddyfileGenerator(machineID, validator, log)
|
||||
|
||||
return &Controller{
|
||||
store: store,
|
||||
configDir: configDir,
|
||||
verifyResponse: verifyResponse,
|
||||
log: slog.With("component", "caddy-controller"),
|
||||
machineID: machineID,
|
||||
configDir: configDir,
|
||||
generator: generator,
|
||||
store: store,
|
||||
log: log,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Controller) Run(ctx context.Context) error {
|
||||
containerRecords, changes, err := c.store.SubscribeContainers(ctx)
|
||||
containers, changes, err := c.store.SubscribeContainers(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("subscribe to container changes: %w", err)
|
||||
}
|
||||
c.log.Info("Subscribed to container changes in the cluster to generate Caddy configuration.")
|
||||
|
||||
containers, err := c.filterAvailableContainers(containerRecords)
|
||||
if err != nil {
|
||||
return fmt.Errorf("filter available containers: %w", err)
|
||||
}
|
||||
|
||||
if err = c.generateCaddyfile(containers); err != nil {
|
||||
containers = filterHealthyContainers(containers)
|
||||
if err = c.generateCaddyfile(ctx, containers); err != nil {
|
||||
return fmt.Errorf("generate Caddyfile configuration: %w", err)
|
||||
}
|
||||
if err = c.generateJSONConfig(containers); err != nil {
|
||||
@@ -71,22 +74,18 @@ func (c *Controller) Run(ctx context.Context) error {
|
||||
}
|
||||
c.log.Info("Cluster containers changed, updating Caddy configuration.")
|
||||
|
||||
containerRecords, err = c.store.ListContainers(ctx, store.ListOptions{})
|
||||
containers, err = c.store.ListContainers(ctx, store.ListOptions{})
|
||||
if err != nil {
|
||||
c.log.Info("Failed to list containers.", "err", err)
|
||||
continue
|
||||
}
|
||||
containers, err = c.filterAvailableContainers(containerRecords)
|
||||
if err != nil {
|
||||
c.log.Info("Failed to filter available containers.", "err", err)
|
||||
c.log.Error("Failed to list containers.", "err", err)
|
||||
continue
|
||||
}
|
||||
containers = filterHealthyContainers(containers)
|
||||
|
||||
if err = c.generateCaddyfile(containers); err != nil {
|
||||
c.log.Info("Failed to generate Caddyfile configuration.", "err", err)
|
||||
if err = c.generateCaddyfile(ctx, containers); err != nil {
|
||||
c.log.Error("Failed to generate Caddyfile configuration.", "err", err)
|
||||
}
|
||||
if err = c.generateJSONConfig(containers); err != nil {
|
||||
c.log.Info("Failed to generate Caddy JSON configuration.", "err", err)
|
||||
c.log.Error("Failed to generate Caddy JSON configuration.", "err", err)
|
||||
}
|
||||
|
||||
c.log.Info("Updated Caddy configuration.", "dir", c.configDir)
|
||||
@@ -96,26 +95,28 @@ func (c *Controller) Run(ctx context.Context) error {
|
||||
}
|
||||
}
|
||||
|
||||
// filterAvailableContainers filters out containers from this machine that are likely unavailable. The availability
|
||||
// is determined by the cluster membership state of the machine that the container is running on.
|
||||
// TODO: implement machine membership check using Corrossion Admin client.
|
||||
func (c *Controller) filterAvailableContainers(
|
||||
containerRecords []store.ContainerRecord,
|
||||
) ([]api.ServiceContainer, error) {
|
||||
containers := make([]api.ServiceContainer, len(containerRecords))
|
||||
for i, cr := range containerRecords {
|
||||
containers[i] = cr.Container
|
||||
// filterHealthyContainers filters out containers that are not healthy.
|
||||
// TODO: Filters out containers from this machine that are likely unavailable. The availability can be determined
|
||||
// by the cluster membership state of the machine that the container is running on. Implement machine membership
|
||||
// check using Corrossion Admin client.
|
||||
func filterHealthyContainers(containers []store.ContainerRecord) []store.ContainerRecord {
|
||||
healthy := make([]store.ContainerRecord, 0, len(containers))
|
||||
for _, cr := range containers {
|
||||
if cr.Container.Healthy() {
|
||||
healthy = append(healthy, cr)
|
||||
}
|
||||
}
|
||||
return containers, nil
|
||||
return healthy
|
||||
}
|
||||
|
||||
func (c *Controller) generateCaddyfile(containers []api.ServiceContainer) error {
|
||||
caddyfile, err := GenerateCaddyfile(containers, c.verifyResponse)
|
||||
func (c *Controller) generateCaddyfile(ctx context.Context, containers []store.ContainerRecord) error {
|
||||
caddyfile, err := c.generator.Generate(ctx, containers)
|
||||
if err != nil {
|
||||
return fmt.Errorf("generate Caddyfile: %w", err)
|
||||
}
|
||||
caddyfilePath := filepath.Join(c.configDir, "Caddyfile")
|
||||
|
||||
// TODO: use atomic file write to avoid partial loads on Caddy watch reload.
|
||||
if err = os.WriteFile(caddyfilePath, []byte(caddyfile), 0o640); err != nil {
|
||||
return fmt.Errorf("write Caddyfile to file '%s': %w", caddyfilePath, err)
|
||||
}
|
||||
@@ -126,8 +127,13 @@ func (c *Controller) generateCaddyfile(containers []api.ServiceContainer) error
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Controller) generateJSONConfig(containers []api.ServiceContainer) error {
|
||||
config, err := GenerateJSONConfig(containers, c.verifyResponse)
|
||||
func (c *Controller) generateJSONConfig(containers []store.ContainerRecord) error {
|
||||
serviceContainers := make([]api.ServiceContainer, len(containers))
|
||||
for i, cr := range containers {
|
||||
serviceContainers[i] = cr.Container
|
||||
}
|
||||
|
||||
config, err := GenerateJSONConfig(serviceContainers, c.machineID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -4,9 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
@@ -20,46 +18,7 @@ import (
|
||||
)
|
||||
|
||||
func GenerateJSONConfig(containers []api.ServiceContainer, verifyResponse string) (*caddy.Config, error) {
|
||||
// Maps hostnames to lists of upstreams (container IP:port pairs).
|
||||
httpHostUpstreams := make(map[string][]string)
|
||||
httpsHostUpstreams := make(map[string][]string)
|
||||
for _, ctr := range containers {
|
||||
if !ctr.Healthy() {
|
||||
continue
|
||||
}
|
||||
|
||||
ip := ctr.UncloudNetworkIP()
|
||||
if !ip.IsValid() {
|
||||
// Container is not connected to the uncloud Docker network (could be host network).
|
||||
continue
|
||||
}
|
||||
log := slog.With("container", ctr.ID)
|
||||
|
||||
ports, err := ctr.ServicePorts()
|
||||
if err != nil {
|
||||
log.Error("Failed to parse service ports for container.", "err", err)
|
||||
continue
|
||||
}
|
||||
|
||||
for _, port := range ports {
|
||||
if port.Mode != api.PortModeIngress {
|
||||
continue
|
||||
}
|
||||
|
||||
switch port.Protocol {
|
||||
case api.ProtocolHTTP:
|
||||
upstream := net.JoinHostPort(ip.String(), strconv.Itoa(int(port.ContainerPort)))
|
||||
httpHostUpstreams[port.Hostname] = append(httpHostUpstreams[port.Hostname], upstream)
|
||||
case api.ProtocolHTTPS:
|
||||
upstream := net.JoinHostPort(ip.String(), strconv.Itoa(int(port.ContainerPort)))
|
||||
httpsHostUpstreams[port.Hostname] = append(httpsHostUpstreams[port.Hostname], upstream)
|
||||
default:
|
||||
// TODO: implement L4 ingress routing for TCP and UDP.
|
||||
log.Error("Unsupported protocol for ingress port.", "port", port)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
httpHostUpstreams, httpsHostUpstreams := httpUpstreamsFromPorts(containers)
|
||||
|
||||
var warnings []caddyconfig.Warning
|
||||
servers := make(map[string]*caddyhttp.Server)
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGenerateConfig(t *testing.T) {
|
||||
func TestGenerateJSONConfig(t *testing.T) {
|
||||
configWithoutServices := `{
|
||||
"servers": {
|
||||
"http": {
|
||||
@@ -312,68 +312,6 @@ func TestGenerateConfig(t *testing.T) {
|
||||
want: configWithoutServices,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "restarting container ignored",
|
||||
containers: []api.ServiceContainer{
|
||||
newRestartingContainer("10.210.0.2", "app.example.com:8080/http"),
|
||||
},
|
||||
want: configWithoutServices,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "stopped container ignored",
|
||||
containers: []api.ServiceContainer{
|
||||
newStoppedContainer("10.210.0.2", "app.example.com:8080/http"),
|
||||
},
|
||||
want: configWithoutServices,
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "mix of running, restarting, and stopped containers",
|
||||
containers: []api.ServiceContainer{
|
||||
newContainer("10.210.0.2", "app.example.com:8080/http"),
|
||||
newRestartingContainer("10.210.0.3", "app.example.com:8080/http"),
|
||||
newStoppedContainer("10.210.0.4", "app.example.com:8080/http"),
|
||||
},
|
||||
want: `{
|
||||
"servers": {
|
||||
"http": {
|
||||
"listen": [":80"],
|
||||
"routes": [
|
||||
{
|
||||
"match": [{"host": ["app.example.com"]}],
|
||||
"handle": [{
|
||||
"handler": "reverse_proxy",
|
||||
"health_checks": {
|
||||
"passive": {
|
||||
"fail_duration": 30000000000
|
||||
}
|
||||
},
|
||||
"load_balancing": {
|
||||
"retries": 3
|
||||
},
|
||||
"upstreams": [{"dial": "10.210.0.2:8080"}]
|
||||
}]
|
||||
},
|
||||
{
|
||||
"match": [{"path": ["/.uncloud-verify"]}],
|
||||
"handle": [{
|
||||
"body": "verification-response-body",
|
||||
"handler": "static_response",
|
||||
"status_code": 200
|
||||
}]
|
||||
}
|
||||
],
|
||||
"logs": {}
|
||||
},
|
||||
"https": {
|
||||
"listen": [":443"],
|
||||
"logs": {}
|
||||
}
|
||||
}
|
||||
}`,
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -439,15 +377,3 @@ func newContainerWithoutNetwork(ports ...string) api.ServiceContainer {
|
||||
},
|
||||
}}}
|
||||
}
|
||||
|
||||
func newRestartingContainer(ip string, ports ...string) api.ServiceContainer {
|
||||
ctr := newContainer(ip, ports...)
|
||||
ctr.Container.State.Restarting = true
|
||||
return ctr
|
||||
}
|
||||
|
||||
func newStoppedContainer(ip string, ports ...string) api.ServiceContainer {
|
||||
ctr := newContainer(ip, ports...)
|
||||
ctr.Container.State.Running = false
|
||||
return ctr
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package caddyconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockCaddyfileValidator creates a new instance of MockCaddyfileValidator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockCaddyfileValidator(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockCaddyfileValidator {
|
||||
mock := &MockCaddyfileValidator{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() { mock.AssertExpectations(t) })
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockCaddyfileValidator is an autogenerated mock type for the CaddyfileValidator type
|
||||
type MockCaddyfileValidator struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockCaddyfileValidator_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockCaddyfileValidator) EXPECT() *MockCaddyfileValidator_Expecter {
|
||||
return &MockCaddyfileValidator_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Validate provides a mock function for the type MockCaddyfileValidator
|
||||
func (_mock *MockCaddyfileValidator) Validate(ctx context.Context, caddyfile string) error {
|
||||
ret := _mock.Called(ctx, caddyfile)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Validate")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) error); ok {
|
||||
r0 = returnFunc(ctx, caddyfile)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockCaddyfileValidator_Validate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Validate'
|
||||
type MockCaddyfileValidator_Validate_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Validate is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - caddyfile string
|
||||
func (_e *MockCaddyfileValidator_Expecter) Validate(ctx interface{}, caddyfile interface{}) *MockCaddyfileValidator_Validate_Call {
|
||||
return &MockCaddyfileValidator_Validate_Call{Call: _e.mock.On("Validate", ctx, caddyfile)}
|
||||
}
|
||||
|
||||
func (_c *MockCaddyfileValidator_Validate_Call) Run(run func(ctx context.Context, caddyfile string)) *MockCaddyfileValidator_Validate_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCaddyfileValidator_Validate_Call) Return(err error) *MockCaddyfileValidator_Validate_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCaddyfileValidator_Validate_Call) RunAndReturn(run func(ctx context.Context, caddyfile string) error) *MockCaddyfileValidator_Validate_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package caddyconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
"github.com/psviderski/uncloud/internal/machine/api/pb"
|
||||
)
|
||||
|
||||
// Server implements the gRPC Caddy service.
|
||||
type Server struct {
|
||||
pb.UnimplementedCaddyServer
|
||||
service *Service
|
||||
}
|
||||
|
||||
func NewServer(service *Service) *Server {
|
||||
return &Server{service: service}
|
||||
}
|
||||
|
||||
// GetConfig retrieves the current Caddy configuration from the machine.
|
||||
func (s *Server) GetConfig(ctx context.Context, _ *emptypb.Empty) (*pb.GetCaddyConfigResponse, error) {
|
||||
caddyfile, modifiedAt, err := s.service.Caddyfile()
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, status.Errorf(codes.NotFound, err.Error())
|
||||
}
|
||||
return nil, status.Errorf(codes.Internal, err.Error())
|
||||
}
|
||||
|
||||
return &pb.GetCaddyConfigResponse{
|
||||
Caddyfile: caddyfile,
|
||||
ModifiedAt: timestamppb.New(modifiedAt),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package caddyconfig
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Service provides methods to interact with the Caddy configuration on the machine.
|
||||
type Service struct {
|
||||
configDir string
|
||||
}
|
||||
|
||||
// NewService creates a new Service instance with the specified Caddy configuration directory.
|
||||
func NewService(configDir string) *Service {
|
||||
return &Service{configDir: configDir}
|
||||
}
|
||||
|
||||
// Caddyfile retrieves the current Caddy configuration (Caddyfile) from the machine's config directory.
|
||||
func (s *Service) Caddyfile() (string, time.Time, error) {
|
||||
path := filepath.Join(s.configDir, "Caddyfile")
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("read Caddyfile from file '%s': %w", path, err)
|
||||
}
|
||||
|
||||
// Get the file modification time.
|
||||
fileInfo, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("get Caddyfile file info '%s': %w", path, err)
|
||||
}
|
||||
|
||||
return string(content), fileInfo.ModTime(), nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package caddyconfig
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// templateContext holds the data available to Caddyfile templates.
|
||||
type templateContext struct {
|
||||
// Name is the current service name.
|
||||
Name string
|
||||
// Upstreams maps service names to their container IPs.
|
||||
Upstreams map[string][]string
|
||||
}
|
||||
|
||||
// upstreamsTemplateFn returns a template function that generates a space separated string of upstreams for the service.
|
||||
// It optionally accepts a service name and a port number: {{upstreams [service-name] [port]}}.
|
||||
func upstreamsTemplateFn(tmplCtx templateContext) func(args ...any) (string, error) {
|
||||
return func(args ...any) (string, error) {
|
||||
var serviceName string
|
||||
var port int
|
||||
|
||||
// Parse arguments.
|
||||
switch len(args) {
|
||||
case 0:
|
||||
// Current service, default port.
|
||||
serviceName = tmplCtx.Name
|
||||
case 1:
|
||||
// Either port (int) for current service or service name (string).
|
||||
switch arg := args[0].(type) {
|
||||
case int:
|
||||
serviceName = tmplCtx.Name
|
||||
port = arg
|
||||
case string:
|
||||
serviceName = arg
|
||||
port = 0
|
||||
default:
|
||||
return "", fmt.Errorf("upstreams function: invalid argument type: %T", arg)
|
||||
}
|
||||
case 2:
|
||||
// Service name and port.
|
||||
name, ok := args[0].(string)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("upstreams function: first argument must be service name (string)")
|
||||
}
|
||||
serviceName = name
|
||||
|
||||
p, ok := args[1].(int)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("upstreams function: second argument must be port (int)")
|
||||
}
|
||||
port = p
|
||||
default:
|
||||
return "", fmt.Errorf("upstreams function: too many arguments; expected 0-2, got %d", len(args))
|
||||
}
|
||||
|
||||
ips, ok := tmplCtx.Upstreams[serviceName]
|
||||
if !ok || len(ips) == 0 {
|
||||
// No upstreams available.
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// Build the space separated upstreams string.
|
||||
var upstreams []string
|
||||
for _, ip := range ips {
|
||||
if port > 0 {
|
||||
upstreams = append(upstreams, net.JoinHostPort(ip, strconv.Itoa(port)))
|
||||
} else {
|
||||
upstreams = append(upstreams, ip)
|
||||
}
|
||||
}
|
||||
|
||||
return strings.Join(upstreams, " "), nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package caddyconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/caddyserver/caddy/v2"
|
||||
)
|
||||
|
||||
// CaddyAdminValidator validates Caddyfile via the Caddy admin API.
|
||||
type CaddyAdminValidator struct {
|
||||
socketPath string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewCaddyAdminValidator(socketPath string) *CaddyAdminValidator {
|
||||
return &CaddyAdminValidator{
|
||||
socketPath: socketPath,
|
||||
client: &http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
|
||||
return net.Dial("unix", socketPath)
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Validate checks if the provided Caddyfile can be adapted to Caddy JSON config using the running Caddy instance via
|
||||
// its admin API. It doesn't guarantee that the Caddyfile is actually valid and can be loaded. For example, a tls
|
||||
// directive with a missing certificate will pass the adaptation but will fail when Caddy tries to load it.
|
||||
// But this is the best we can do over the admin API.
|
||||
// TODO: run 'docker exec caddy-container caddy validate' to do proper validation or implement a Caddy module that
|
||||
// exposes a validation endpoint.
|
||||
func (c *CaddyAdminValidator) Validate(ctx context.Context, caddyfile string) error {
|
||||
// Bogus host is used so that http.NewRequest is happy but it doesn't matter since we're using a Unix socket.
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", "http://localhost/adapt", strings.NewReader(caddyfile))
|
||||
if err != nil {
|
||||
return fmt.Errorf("create adapt request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/caddyfile")
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("send adapt request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
return nil
|
||||
}
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
// If the response is a 400 Bad Request, try to parse the error message from it.
|
||||
if resp.StatusCode == http.StatusBadRequest {
|
||||
var apiError caddy.APIError
|
||||
if err = json.Unmarshal(body, &apiError); err == nil {
|
||||
return errors.New(apiError.Message)
|
||||
}
|
||||
}
|
||||
|
||||
return errors.New(string(body))
|
||||
}
|
||||
@@ -42,6 +42,9 @@ const (
|
||||
DefaultMachineSockPath = "/run/uncloud/machine.sock"
|
||||
DefaultUncloudSockPath = "/run/uncloud/uncloud.sock"
|
||||
DefaultSockGroup = "uncloud"
|
||||
// DefaultCaddyAdminSockPath is the default path to the Caddy admin socket for validating the generated Caddy
|
||||
// reverse proxy configuration.
|
||||
DefaultCaddyAdminSockPath = "/run/uncloud/caddy/admin.sock"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
@@ -260,7 +263,8 @@ func NewMachine(config *Config) (*Machine, error) {
|
||||
m.dockerServer = machinedocker.NewServer(dockerService, db, internalDNSIP,
|
||||
machinedocker.WithNetworkReady(m.IsNetworkReady),
|
||||
machinedocker.WithWaitForNetworkReady(m.WaitForNetworkReady))
|
||||
m.localMachineServer = newGRPCServer(m, c, m.dockerServer)
|
||||
caddyServer := caddyconfig.NewServer(caddyconfig.NewService(config.CaddyConfigDir))
|
||||
m.localMachineServer = newGRPCServer(m, c, m.dockerServer, caddyServer)
|
||||
|
||||
if m.Initialised() {
|
||||
m.initialised <- struct{}{}
|
||||
@@ -269,11 +273,12 @@ func NewMachine(config *Config) (*Machine, error) {
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func newGRPCServer(m pb.MachineServer, c pb.ClusterServer, d pb.DockerServer) *grpc.Server {
|
||||
func newGRPCServer(m pb.MachineServer, c pb.ClusterServer, d pb.DockerServer, caddy pb.CaddyServer) *grpc.Server {
|
||||
s := grpc.NewServer()
|
||||
pb.RegisterMachineServer(s, m)
|
||||
pb.RegisterClusterServer(s, c)
|
||||
pb.RegisterDockerServer(s, d)
|
||||
pb.RegisterCaddyServer(s, caddy)
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -387,7 +392,12 @@ func (m *Machine) Run(ctx context.Context) error {
|
||||
|
||||
// Create a new caddyconfig controller for managing the Caddy reverse proxy configuration.
|
||||
// It will also serve the current machine ID at /.uncloud-verify to verify Caddy reachability.
|
||||
caddyconfigCtrl, err := caddyconfig.NewController(m.store, m.config.CaddyConfigDir, m.state.ID)
|
||||
caddyconfigCtrl, err := caddyconfig.NewController(
|
||||
m.state.ID,
|
||||
m.config.CaddyConfigDir,
|
||||
DefaultCaddyAdminSockPath,
|
||||
m.store,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create caddyconfig controller: %w", err)
|
||||
}
|
||||
|
||||
@@ -165,7 +165,7 @@ func (s *Store) DeleteContainers(ctx context.Context, opts DeleteOptions) error
|
||||
// SubscribeContainers returns a list of containers and a channel that signals changes to the list. The channel doesn't
|
||||
// receive any values, it just signals when a container(s) has been added, updated, or deleted in the database.
|
||||
func (s *Store) SubscribeContainers(ctx context.Context) ([]ContainerRecord, <-chan struct{}, error) {
|
||||
// TODO: figure out whether we need sync_status at all.
|
||||
// TODO: figure out whether we need sync_status at all (not used at the moment).
|
||||
q := sq.Select("container", "machine_id", "sync_status", "updated_at").From("containers").
|
||||
Where(sq.Eq{"sync_status": SyncStatusSynced})
|
||||
query, args, err := q.ToSql()
|
||||
|
||||
@@ -24,6 +24,20 @@ const (
|
||||
|
||||
type Container struct {
|
||||
types.ContainerJSON
|
||||
// created caches the parsed creation time by CreatedTime.
|
||||
created time.Time
|
||||
}
|
||||
|
||||
// CreatedTime returns the time when the container was created parsed from the Created field.
|
||||
func (c *Container) CreatedTime() time.Time {
|
||||
if c.created.IsZero() && c.Created != "" {
|
||||
created, err := time.Parse(time.RFC3339Nano, c.Created)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
c.created = created
|
||||
}
|
||||
return c.created
|
||||
}
|
||||
|
||||
// Healthy determines if the container is running and healthy.
|
||||
@@ -199,3 +213,24 @@ func (c *ServiceContainer) ConflictingServicePorts(ports []PortSpec) ([]PortSpec
|
||||
|
||||
return conflicting, nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements custom unmarshalling for ServiceContainer to override the custom unmarshaler
|
||||
// of the embedded Container field.
|
||||
func (c *ServiceContainer) UnmarshalJSON(data []byte) error {
|
||||
// Unmarshal everything except Container into a temporary struct. Keep this in sync with ServiceContainer.
|
||||
var temp struct {
|
||||
ServiceSpec ServiceSpec
|
||||
}
|
||||
if err := json.Unmarshal(data, &temp); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Let Container's UnmarshalJSON handle its part.
|
||||
if err := json.Unmarshal(data, &c.Container); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c.ServiceSpec = temp.ServiceSpec
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
+25
-6
@@ -62,6 +62,14 @@ type ServiceSpec struct {
|
||||
Volumes []VolumeSpec
|
||||
}
|
||||
|
||||
// CaddyConfig returns the Caddy reverse proxy configuration for the service or an empty string if it's not defined.
|
||||
func (s *ServiceSpec) CaddyConfig() string {
|
||||
if s.Caddy == nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(s.Caddy.Config)
|
||||
}
|
||||
|
||||
func (s *ServiceSpec) Volume(name string) (VolumeSpec, bool) {
|
||||
for _, v := range s.Volumes {
|
||||
if v.Name == name {
|
||||
@@ -123,12 +131,6 @@ func (s *ServiceSpec) Validate() error {
|
||||
}
|
||||
}
|
||||
|
||||
// Validate that Caddy and Ports are not used together.
|
||||
if s.Caddy != nil && strings.TrimSpace(s.Caddy.Config) != "" && len(s.Ports) > 0 {
|
||||
return fmt.Errorf("ports and Caddy configuration cannot be specified simultaneously: " +
|
||||
"Caddy config is auto-generated from ports, use only one of them")
|
||||
}
|
||||
|
||||
for _, p := range s.Ports {
|
||||
if (p.Mode == "" || p.Mode == PortModeIngress) &&
|
||||
p.Protocol != ProtocolHTTP && p.Protocol != ProtocolHTTPS {
|
||||
@@ -138,6 +140,23 @@ func (s *ServiceSpec) Validate() error {
|
||||
|
||||
// TODO: validate there is no conflict between ports.
|
||||
|
||||
// Validate that Caddy and Ports are not used together, unless all ports are host mode.
|
||||
if s.Caddy != nil && strings.TrimSpace(s.Caddy.Config) != "" && len(s.Ports) > 0 {
|
||||
// Check if all ports are in host mode.
|
||||
hasIngressPort := false
|
||||
for _, p := range s.Ports {
|
||||
if p.Mode == "" || p.Mode == PortModeIngress {
|
||||
hasIngressPort = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hasIngressPort {
|
||||
return fmt.Errorf("ingress ports and Caddy configuration cannot be specified simultaneously: " +
|
||||
"Caddy config is auto-generated from ingress ports, use only one of them. " +
|
||||
"Host mode ports can be used with Caddy config")
|
||||
}
|
||||
}
|
||||
|
||||
volumeNames := make(map[string]struct{})
|
||||
for _, v := range s.Volumes {
|
||||
if err := v.Validate(); err != nil {
|
||||
|
||||
+97
-2
@@ -71,7 +71,7 @@ func TestServiceSpec_Validate_CaddyAndPorts(t *testing.T) {
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "invalid with both Caddy and Ports",
|
||||
name: "invalid with Caddy and Ports (default mode is ingress)",
|
||||
spec: ServiceSpec{
|
||||
Name: "test",
|
||||
Container: ContainerSpec{
|
||||
@@ -84,10 +84,105 @@ func TestServiceSpec_Validate_CaddyAndPorts(t *testing.T) {
|
||||
{
|
||||
ContainerPort: 80,
|
||||
Protocol: ProtocolHTTP,
|
||||
// Mode is empty, defaults to ingress
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErr: "ports and Caddy configuration cannot be specified simultaneously",
|
||||
wantErr: "ingress ports and Caddy configuration cannot be specified simultaneously",
|
||||
},
|
||||
{
|
||||
name: "invalid with both Caddy and ingress Ports",
|
||||
spec: ServiceSpec{
|
||||
Name: "test",
|
||||
Container: ContainerSpec{
|
||||
Image: "nginx:latest",
|
||||
},
|
||||
Caddy: &CaddySpec{
|
||||
Config: "example.com {\n reverse_proxy :8080\n}",
|
||||
},
|
||||
Ports: []PortSpec{
|
||||
{
|
||||
ContainerPort: 80,
|
||||
Protocol: ProtocolHTTP,
|
||||
Mode: PortModeIngress,
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErr: "ingress ports and Caddy configuration cannot be specified simultaneously",
|
||||
},
|
||||
{
|
||||
name: "valid with Caddy and host mode Ports",
|
||||
spec: ServiceSpec{
|
||||
Name: "test",
|
||||
Container: ContainerSpec{
|
||||
Image: "nginx:latest",
|
||||
},
|
||||
Caddy: &CaddySpec{
|
||||
Config: "example.com {\n reverse_proxy :8080\n}",
|
||||
},
|
||||
Ports: []PortSpec{
|
||||
{
|
||||
ContainerPort: 3306,
|
||||
PublishedPort: 3306,
|
||||
Protocol: ProtocolTCP,
|
||||
Mode: PortModeHost,
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "invalid with Caddy and mixed mode Ports",
|
||||
spec: ServiceSpec{
|
||||
Name: "test",
|
||||
Container: ContainerSpec{
|
||||
Image: "nginx:latest",
|
||||
},
|
||||
Caddy: &CaddySpec{
|
||||
Config: "example.com {\n reverse_proxy :8080\n}",
|
||||
},
|
||||
Ports: []PortSpec{
|
||||
{
|
||||
ContainerPort: 3306,
|
||||
PublishedPort: 3306,
|
||||
Protocol: ProtocolTCP,
|
||||
Mode: PortModeHost,
|
||||
},
|
||||
{
|
||||
ContainerPort: 80,
|
||||
Protocol: ProtocolHTTP,
|
||||
Mode: PortModeIngress,
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErr: "ingress ports and Caddy configuration cannot be specified simultaneously",
|
||||
},
|
||||
{
|
||||
name: "valid with Caddy and multiple host mode Ports",
|
||||
spec: ServiceSpec{
|
||||
Name: "test",
|
||||
Container: ContainerSpec{
|
||||
Image: "nginx:latest",
|
||||
},
|
||||
Caddy: &CaddySpec{
|
||||
Config: "example.com {\n reverse_proxy :8080\n}",
|
||||
},
|
||||
Ports: []PortSpec{
|
||||
{
|
||||
ContainerPort: 3306,
|
||||
PublishedPort: 3306,
|
||||
Protocol: ProtocolTCP,
|
||||
Mode: PortModeHost,
|
||||
},
|
||||
{
|
||||
ContainerPort: 5432,
|
||||
PublishedPort: 5432,
|
||||
Protocol: ProtocolTCP,
|
||||
Mode: PortModeHost,
|
||||
},
|
||||
},
|
||||
},
|
||||
wantErr: "",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
+30
-5
@@ -23,7 +23,7 @@ var caddyImageTagRegex = regexp.MustCompile(`^2\.\d+\.\d+$`)
|
||||
// NewCaddyDeployment creates a new deployment for a Caddy reverse proxy service.
|
||||
// The service is deployed in global mode to all machines in the cluster. If the image is not provided, the latest
|
||||
// version of the official Caddy Docker image is used.
|
||||
func (cli *Client) NewCaddyDeployment(image string, placement api.Placement) (*deploy.Deployment, error) {
|
||||
func (cli *Client) NewCaddyDeployment(image, config string, placement api.Placement) (*deploy.Deployment, error) {
|
||||
if image == "" {
|
||||
latest, err := LatestCaddyImage()
|
||||
if err != nil {
|
||||
@@ -35,13 +35,24 @@ func (cli *Client) NewCaddyDeployment(image string, placement api.Placement) (*d
|
||||
|
||||
spec := api.ServiceSpec{
|
||||
Container: api.ContainerSpec{
|
||||
Command: []string{"caddy", "run", "-c", "/config/caddy.json", "--watch"},
|
||||
Image: image,
|
||||
Command: []string{"caddy", "run", "-c", "/config/Caddyfile", "--watch"},
|
||||
Env: map[string]string{
|
||||
"CADDY_ADMIN": "unix//run/caddy/admin.sock",
|
||||
},
|
||||
Image: image,
|
||||
VolumeMounts: []api.VolumeMount{
|
||||
{
|
||||
VolumeName: "config",
|
||||
VolumeName: "data",
|
||||
ContainerPath: "/config",
|
||||
},
|
||||
{
|
||||
VolumeName: "data",
|
||||
ContainerPath: "/data",
|
||||
},
|
||||
{
|
||||
VolumeName: "run",
|
||||
ContainerPath: "/run/caddy",
|
||||
},
|
||||
},
|
||||
},
|
||||
Mode: api.ServiceModeGlobal,
|
||||
@@ -63,15 +74,29 @@ func (cli *Client) NewCaddyDeployment(image string, placement api.Placement) (*d
|
||||
},
|
||||
Volumes: []api.VolumeSpec{
|
||||
{
|
||||
Name: "config",
|
||||
Name: "data",
|
||||
Type: api.VolumeTypeBind,
|
||||
BindOptions: &api.BindOptions{
|
||||
HostPath: "/var/lib/uncloud/caddy",
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "run",
|
||||
Type: api.VolumeTypeBind,
|
||||
BindOptions: &api.BindOptions{
|
||||
HostPath: "/run/uncloud/caddy",
|
||||
CreateHostPath: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if config != "" {
|
||||
spec.Caddy = &api.CaddySpec{
|
||||
Config: config,
|
||||
}
|
||||
}
|
||||
|
||||
return cli.NewDeployment(spec, nil), nil
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ type Client struct {
|
||||
// Methods such as Reset or Inspect are ambiguous in the context of a machine+cluster client.
|
||||
pb.MachineClient
|
||||
pb.ClusterClient
|
||||
Caddy pb.CaddyClient
|
||||
// Docker is a namespaced client for the Docker service to distinguish Uncloud-specific service container operations
|
||||
// from generic Docker operations.
|
||||
Docker *docker.Client
|
||||
@@ -50,6 +51,7 @@ func New(ctx context.Context, connector Connector) (*Client, error) {
|
||||
|
||||
c.MachineClient = pb.NewMachineClient(c.conn)
|
||||
c.ClusterClient = pb.NewClusterClient(c.conn)
|
||||
c.Caddy = pb.NewCaddyClient(c.conn)
|
||||
c.Docker = docker.NewClient(c.conn)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
@@ -141,7 +141,7 @@ services:
|
||||
wantErr: "expected type 'string'",
|
||||
},
|
||||
{
|
||||
name: "x-caddy with x-ports conflict",
|
||||
name: "x-caddy with ingress x-ports conflict",
|
||||
composeYAML: `
|
||||
services:
|
||||
web:
|
||||
@@ -153,7 +153,26 @@ services:
|
||||
x-ports:
|
||||
- example.com:80/http
|
||||
`,
|
||||
wantErr: "cannot specify both 'x-caddy' and 'x-ports'",
|
||||
wantErr: "ingress ports in 'x-ports' and 'x-caddy' cannot be specified simultaneously",
|
||||
},
|
||||
{
|
||||
name: "x-caddy with host-only x-ports allowed",
|
||||
composeYAML: `
|
||||
services:
|
||||
web:
|
||||
image: nginx
|
||||
x-caddy: |
|
||||
example.com {
|
||||
reverse_proxy web:80
|
||||
}
|
||||
x-ports:
|
||||
- 8080:80@host
|
||||
- 9090:90/tcp@host
|
||||
`,
|
||||
wantConfig: `example.com {
|
||||
reverse_proxy web:80
|
||||
}`,
|
||||
// Should not error - host ports are allowed with x-caddy
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -252,20 +252,26 @@ func tmpfsVolumeSpecFromCompose(serviceVolume types.ServiceVolumeConfig) api.Vol
|
||||
// validateServicesExtensions validates extension combinations across all services in the project.
|
||||
func validateServicesExtensions(project *types.Project) error {
|
||||
for _, service := range project.Services {
|
||||
// Check for x-caddy and x-ports conflict.
|
||||
// Check for x-caddy and x-ports conflict, unless all ports are host mode.
|
||||
hasCaddy := false
|
||||
if caddy, ok := service.Extensions[CaddyExtensionKey].(Caddy); ok && caddy.Config != "" {
|
||||
hasCaddy = true
|
||||
}
|
||||
|
||||
hasPorts := false
|
||||
if ports, ok := service.Extensions[PortsExtensionKey].([]api.PortSpec); ok && len(ports) > 0 {
|
||||
hasPorts = true
|
||||
}
|
||||
|
||||
if hasCaddy && hasPorts {
|
||||
return fmt.Errorf("service '%s' cannot specify both 'x-caddy' and 'x-ports': "+
|
||||
"Caddy config is auto-generated from ports, use only one of them", service.Name)
|
||||
if ports, ok := service.Extensions[PortsExtensionKey].([]api.PortSpec); ok && len(ports) > 0 && hasCaddy {
|
||||
// Check if all ports are in host mode.
|
||||
hasIngressPort := false
|
||||
for _, p := range ports {
|
||||
if p.Mode == "" || p.Mode == api.PortModeIngress {
|
||||
hasIngressPort = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hasIngressPort {
|
||||
return fmt.Errorf("service '%s': ingress ports in 'x-ports' and 'x-caddy' cannot be specified "+
|
||||
"simultaneously: Caddy config is auto-generated from ingress ports, use only one of them. "+
|
||||
"Host mode ports in 'x-caddy' can be used with 'x-caddy'", service.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,24 +1,17 @@
|
||||
package deploy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/distribution/reference"
|
||||
"github.com/docker/docker/api/types"
|
||||
"github.com/opencontainers/go-digest"
|
||||
"github.com/psviderski/uncloud/internal/secret"
|
||||
"github.com/psviderski/uncloud/pkg/api"
|
||||
"google.golang.org/grpc/codes"
|
||||
)
|
||||
|
||||
// ServiceSpecResolver transforms user-provided service specs into deployment-ready form.
|
||||
type ServiceSpecResolver struct {
|
||||
ClusterDomain string
|
||||
ImageResolver *ImageDigestResolver
|
||||
}
|
||||
|
||||
// Resolve transforms a service spec into its fully resolved form ready for deployment.
|
||||
@@ -33,7 +26,6 @@ func (r *ServiceSpecResolver) Resolve(spec api.ServiceSpec) (api.ServiceSpec, er
|
||||
r.applyDefaults,
|
||||
r.resolveServiceName,
|
||||
r.expandIngressPorts,
|
||||
r.resolveImageDigest,
|
||||
}
|
||||
|
||||
for _, step := range steps {
|
||||
@@ -111,21 +103,6 @@ func (r *ServiceSpecResolver) expandIngressPorts(spec *api.ServiceSpec) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *ServiceSpecResolver) resolveImageDigest(spec *api.ServiceSpec) error {
|
||||
if r.ImageResolver == nil {
|
||||
// Skip digest resolution when no resolver is provided.
|
||||
return nil
|
||||
}
|
||||
|
||||
image, err := r.ImageResolver.Resolve(spec.Container.Image, spec.Container.PullPolicy)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve image digest: %w", err)
|
||||
}
|
||||
spec.Container.Image = image
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func GenerateServiceName(image string) (string, error) {
|
||||
img, err := reference.ParseDockerRef(image)
|
||||
if err != nil {
|
||||
@@ -144,181 +121,3 @@ func GenerateServiceName(image string) (string, error) {
|
||||
}
|
||||
return fmt.Sprintf("%s-%s", imageName, suffix), nil
|
||||
}
|
||||
|
||||
type ImageResolverClient interface {
|
||||
api.ImageClient
|
||||
api.MachineClient
|
||||
}
|
||||
|
||||
// TODO(lhf): as of April 2025, ImageDigestResolver is not used in the codebase and considered more harmful
|
||||
// than helpful. It's safe to remove it.
|
||||
type ImageDigestResolver struct {
|
||||
Ctx context.Context
|
||||
Client ImageResolverClient
|
||||
}
|
||||
|
||||
// Resolve resolves the image to the image with the digest according to the pull policy:
|
||||
// - always: Fetch the latest digest for the image tag in the registry.
|
||||
// - missing: Find the latest image matching the tag on any machine and use its digest, if it exists.
|
||||
// When there is no matching image on any machine, it behaves like 'always'.
|
||||
// - never: !Not implemented! Similar to 'missing' but when there is no matching image on any machine,
|
||||
// it returns an error.
|
||||
//
|
||||
// If the image is already pinned to a digest, it is returned as is.
|
||||
func (r *ImageDigestResolver) Resolve(image, policy string) (string, error) {
|
||||
if r.Ctx == nil {
|
||||
r.Ctx = context.Background()
|
||||
}
|
||||
|
||||
ref, err := reference.ParseNormalizedNamed(image)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("parse image: %w", err)
|
||||
}
|
||||
if _, ok := ref.(reference.Canonical); ok {
|
||||
// The image is already pinned to a digest.
|
||||
return image, nil
|
||||
}
|
||||
|
||||
switch policy {
|
||||
case api.PullPolicyAlways:
|
||||
return r.resolveAlways(image)
|
||||
case api.PullPolicyMissing:
|
||||
return r.resolveMissing(image)
|
||||
case api.PullPolicyNever:
|
||||
return "", fmt.Errorf("pull policy '%s' is not supported yet", policy)
|
||||
}
|
||||
return image, nil
|
||||
}
|
||||
|
||||
// resolveAlways resolves the image to the image with the digest by querying the registry from all machines.
|
||||
func (r *ImageDigestResolver) resolveAlways(image string) (string, error) {
|
||||
// TODO: broadcast to a subset of machines in large clusters to avoid being rate-limited by the registry.
|
||||
ctx, _, err := api.ProxyMachinesContext(r.Ctx, r.Client, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create request context to broadcast to all machines: %w", err)
|
||||
}
|
||||
|
||||
remoteImages, err := r.Client.InspectRemoteImage(ctx, image)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("inspect image '%s' in registry from all machines: %w", image, err)
|
||||
}
|
||||
if len(remoteImages) == 0 {
|
||||
return "", fmt.Errorf("inspect image '%s' in registry from all machines: unexpected empty response", image)
|
||||
}
|
||||
|
||||
for _, ri := range remoteImages {
|
||||
if ri.Metadata != nil && ri.Metadata.Error != "" {
|
||||
// Save the last error to return it if all machines fail to inspect the image.
|
||||
err = fmt.Errorf("inspect image '%s' in registry on machine '%s': %s",
|
||||
image, ri.Metadata.Machine, ri.Metadata.Error)
|
||||
continue
|
||||
}
|
||||
|
||||
return reference.FamiliarString(ri.Image.Reference), nil
|
||||
}
|
||||
|
||||
return "", err
|
||||
}
|
||||
|
||||
func (r *ImageDigestResolver) resolveMissing(image string) (string, error) {
|
||||
ctx, _, err := api.ProxyMachinesContext(r.Ctx, r.Client, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create request context to broadcast to all machines: %w", err)
|
||||
}
|
||||
|
||||
machineImages, err := r.Client.InspectImage(ctx, image)
|
||||
if err != nil {
|
||||
if errors.Is(err, api.ErrNotFound) {
|
||||
// If the image is missing on all machines, the 'missing' policy is equivalent to 'always'.
|
||||
return r.resolveAlways(image)
|
||||
}
|
||||
return "", fmt.Errorf("inspect image '%s' on all machines: %w", image, err)
|
||||
}
|
||||
|
||||
var availableImages []types.ImageInspect
|
||||
for _, mi := range machineImages {
|
||||
// Metadata can be nil if the request was proxied to only one machine.
|
||||
if mi.Metadata != nil && mi.Metadata.Error != "" {
|
||||
if codes.Code(mi.Metadata.Status.Code) != codes.NotFound {
|
||||
fmt.Printf("WARNING: failed to inspect image '%s' on machine '%s': %s\n",
|
||||
image, mi.Metadata.Machine, mi.Metadata.Error)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
availableImages = append(availableImages, mi.Image)
|
||||
}
|
||||
|
||||
if len(availableImages) == 0 {
|
||||
// If the image is missing on all machines, the 'missing' policy is equivalent to 'always'.
|
||||
return r.resolveAlways(image)
|
||||
}
|
||||
|
||||
// Find the latest image with a RepoDigest.
|
||||
var latestDigest digest.Digest
|
||||
var latestCreated time.Time
|
||||
for _, img := range availableImages {
|
||||
if len(img.RepoDigests) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// TODO: handle multiple RepoDigests. This could happen for example if the same image was pulled twice using
|
||||
// both its index (multi-arch) digest and manifest (platform-specific) digest:
|
||||
// {
|
||||
// "Id": "sha256:6fee7566e4273ee6078f08e167e36434b35f72152232a5e6f1446288817dabe5",
|
||||
// "RepoTags": [
|
||||
// "traefik/whoami:latest"
|
||||
// ],
|
||||
// "RepoDigests": [
|
||||
// "traefik/whoami@sha256:200689790a0a0ea48ca45992e0450bc26ccab5307375b41c84dfc4f2475937ab",
|
||||
// "traefik/whoami@sha256:4f90b33ddca9c4d4f06527070d6e503b16d71016edea036842be2a84e60c91cb"
|
||||
// ],
|
||||
// ...
|
||||
// }
|
||||
// Should the registry be queried to find out which digest to use?
|
||||
repoDigest := img.RepoDigests[0]
|
||||
created, err := time.Parse(time.RFC3339Nano, img.Created)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if created.After(latestCreated) {
|
||||
ref, err := reference.ParseNormalizedNamed(repoDigest)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if c, ok := ref.(reference.Canonical); ok {
|
||||
latestDigest = c.Digest()
|
||||
latestCreated = created
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if latestDigest != "" {
|
||||
return imageWithDigest(image, latestDigest)
|
||||
}
|
||||
|
||||
// Don't pin the digest if no RepoDigests were found. This means the available images were not pulled from
|
||||
// a registry but built locally or loaded from an archive. In this case, the available images (could be multiple
|
||||
// for different platforms) should be copied to other machines to be able to run service containers on them.
|
||||
return image, nil
|
||||
}
|
||||
|
||||
// imageWithDigest adds a digest to an image string if it doesn't already contain one.
|
||||
func imageWithDigest(image string, dig digest.Digest) (string, error) {
|
||||
ref, err := reference.ParseNormalizedNamed(image)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("parse image: %w", err)
|
||||
}
|
||||
|
||||
if _, ok := ref.(reference.Canonical); !ok {
|
||||
// Preserves the original tag if present.
|
||||
img, err := reference.WithDigest(ref, dig)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("add digest to image: %w", err)
|
||||
}
|
||||
return reference.FamiliarString(img), nil
|
||||
}
|
||||
|
||||
return image, nil
|
||||
}
|
||||
|
||||
+114
-3
@@ -4,12 +4,15 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/docker/docker/api/types/container"
|
||||
"github.com/docker/docker/api/types/mount"
|
||||
"github.com/docker/docker/api/types/volume"
|
||||
"github.com/docker/go-units"
|
||||
"github.com/psviderski/uncloud/internal/machine/api/pb"
|
||||
"github.com/psviderski/uncloud/internal/secret"
|
||||
"github.com/psviderski/uncloud/internal/ucind"
|
||||
"github.com/psviderski/uncloud/pkg/api"
|
||||
@@ -271,7 +274,7 @@ func TestDeployment(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
deployment, err := cli.NewCaddyDeployment("", api.Placement{})
|
||||
deployment, err := cli.NewCaddyDeployment("", "", api.Placement{})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = deployment.Run(ctx)
|
||||
@@ -284,6 +287,12 @@ func TestDeployment(t *testing.T) {
|
||||
|
||||
ctr := svc.Containers[0].Container
|
||||
assert.Regexp(t, `^caddy:2\.\d+\.\d+$`, ctr.Config.Image)
|
||||
|
||||
config, err := cli.Caddy.GetConfig(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Contains(t, config.Caddyfile, "# This file is autogenerated by Uncloud")
|
||||
assert.Contains(t, config.Caddyfile, "handle /.uncloud-verify")
|
||||
})
|
||||
|
||||
t.Run("caddy with machine placement", func(t *testing.T) {
|
||||
@@ -295,7 +304,7 @@ func TestDeployment(t *testing.T) {
|
||||
})
|
||||
|
||||
// Deploy to machine #0.
|
||||
deployment, err := cli.NewCaddyDeployment("", api.Placement{
|
||||
deployment, err := cli.NewCaddyDeployment("", "", api.Placement{
|
||||
Machines: []string{c.Machines[0].Name},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
@@ -313,7 +322,7 @@ func TestDeployment(t *testing.T) {
|
||||
// initialContainerID := svc.Containers[0].Container.ID
|
||||
|
||||
// Deploy to all machines without a placement constraint.
|
||||
deployment, err = cli.NewCaddyDeployment(image, api.Placement{})
|
||||
deployment, err = cli.NewCaddyDeployment(image, "", api.Placement{})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = deployment.Run(ctx)
|
||||
@@ -332,6 +341,108 @@ func TestDeployment(t *testing.T) {
|
||||
// assert.True(t, containers.Contains(initialContainerID), "Expected initial container to remain")
|
||||
})
|
||||
|
||||
t.Run("caddy and service with custom configs", func(t *testing.T) {
|
||||
name := "test-custom-caddy-config"
|
||||
t.Cleanup(func() {
|
||||
err := cli.RemoveService(ctx, name)
|
||||
if !errors.Is(err, api.ErrNotFound) {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
err = cli.RemoveService(ctx, client.CaddyServiceName)
|
||||
if !errors.Is(err, api.ErrNotFound) {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
})
|
||||
|
||||
// First deploy a service with custom caddy config before caddy is deployed.
|
||||
serviceCaddyfile := `test-custom-caddy-config.example.com {
|
||||
reverse_proxy {{upstreams}} {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}`
|
||||
spec := api.ServiceSpec{
|
||||
Name: name,
|
||||
Container: api.ContainerSpec{
|
||||
Image: "portainer/pause:latest",
|
||||
},
|
||||
Caddy: &api.CaddySpec{
|
||||
Config: serviceCaddyfile,
|
||||
},
|
||||
}
|
||||
|
||||
deployment := cli.NewDeployment(spec, nil)
|
||||
_, err := deployment.Run(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
svc, err := cli.InspectService(ctx, name)
|
||||
require.NoError(t, err)
|
||||
assertServiceMatchesSpec(t, svc, spec)
|
||||
|
||||
// Check that the generated Caddyfile contains a comment with invalid user-defined configs.
|
||||
var config *pb.GetCaddyConfigResponse
|
||||
require.Eventually(t, func() bool {
|
||||
config, err = cli.Caddy.GetConfig(ctx, nil)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return strings.Contains(config.Caddyfile, "invalid user-defined configs")
|
||||
}, 5*time.Second, 100*time.Millisecond)
|
||||
|
||||
assert.Regexp(t, "- service 'test-custom-caddy-config': validation failed:.*"+
|
||||
"/run/uncloud/caddy/admin.sock: connect:.*", config.Caddyfile,
|
||||
"Expected comment about validation failure for service's user-defined Caddy config")
|
||||
assert.NotContains(t, config.Caddyfile, "test-custom-caddy-config.example.com {")
|
||||
|
||||
// Now deploy caddy with custom config.
|
||||
caddyCaddyfile := `{
|
||||
debug
|
||||
}
|
||||
|
||||
myapp.example.com {
|
||||
reverse_proxy 1.2.3.4:8000
|
||||
}`
|
||||
caddyDeployment, err := cli.NewCaddyDeployment("", caddyCaddyfile, api.Placement{})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = caddyDeployment.Run(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
caddySvc, err := cli.InspectService(ctx, client.CaddyServiceName)
|
||||
require.NoError(t, err)
|
||||
assertServiceMatchesSpec(t, caddySvc, caddyDeployment.Spec)
|
||||
|
||||
// Wait for the Caddyfile to be regenerated with both custom configs.
|
||||
require.Eventually(t, func() bool {
|
||||
config, err = cli.Caddy.GetConfig(ctx, nil)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
// Both configs should be present.
|
||||
return strings.Contains(config.Caddyfile, caddyCaddyfile) &&
|
||||
strings.Contains(config.Caddyfile, "test-custom-caddy-config.example.com")
|
||||
}, 5*time.Second, 100*time.Millisecond,
|
||||
"Expected both custom configs to be included in the Caddyfile")
|
||||
|
||||
assert.Contains(t, config.Caddyfile, "# This file is autogenerated by Uncloud")
|
||||
assert.Contains(t, config.Caddyfile, "handle /.uncloud-verify")
|
||||
assert.Contains(t, config.Caddyfile, caddyCaddyfile,
|
||||
"Expected user-defined global Caddy config to be included in the Caddyfile")
|
||||
|
||||
ctrIP := svc.Containers[0].Container.UncloudNetworkIP().String()
|
||||
renderedServiceCaddyfile := `test-custom-caddy-config.example.com {
|
||||
reverse_proxy ` + ctrIP + ` {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}`
|
||||
assert.Contains(t, config.Caddyfile, renderedServiceCaddyfile,
|
||||
"Expected rendered user-defined Caddy config for test service to be included in the Caddyfile")
|
||||
|
||||
assert.NotContains(t, config.Caddyfile, "invalid user-defined configs",
|
||||
"Should not have validation failure comments after caddy is deployed")
|
||||
})
|
||||
|
||||
t.Run("replicated", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ Docker containers running on different machines get **unique IP addresses** from
|
||||
The design and implementation were highly inspired by
|
||||
Talos [KubeSpan](https://www.talos.dev/v1.10/talos-guides/network/kubespan/).
|
||||
|
||||
### Managed DNS service
|
||||
### Managed DNS service (optional)
|
||||
|
||||
Uncloud can provide **managed DNS records** like `<service-name>.<cluster-id>.cluster.uncloud.run` for your public
|
||||
services through free [Uncloud DNS](https://github.com/psviderski/uncloud-dns) service. You can deploy a service and
|
||||
@@ -99,7 +99,7 @@ containers by their service names, `curl` service endpoints, or analyse traffic
|
||||
|
||||
## Getting started
|
||||
|
||||
Install Uncloud CLI and deploy your first app in minutes:
|
||||
Install Uncloud CLI and deploy your first app:
|
||||
|
||||
* [Install Uncloud CLI](./2-getting-started/1-install-cli.md)
|
||||
* [Deploy demo app](./2-getting-started/2-deploy-demo-app.md)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
sidebar_label: Overview
|
||||
---
|
||||
|
||||
# Ingress & HTTPS
|
||||
|
||||
Uncloud uses [Caddy](https://caddyserver.com/) as its reverse proxy to handle incoming traffic, provide automatic HTTPS
|
||||
with [Let's Encrypt](https://letsencrypt.org/), and route requests to your services.
|
||||
|
||||
## How it works
|
||||
|
||||
Caddy runs as a global service `caddy` on every machine in your cluster, listening on the host ports 80 (HTTP) and 443
|
||||
(HTTPS).
|
||||
|
||||
It's deployed during cluster initialisation (`uc machine init`) unless you use the `--no-caddy` flag.
|
||||
See [Managing Caddy](3-managing-caddy.md) for deployment and customisation instructions.
|
||||
|
||||
When you [publish a service port](2-publishing-services.md), Uncloud automatically configures Caddy to:
|
||||
|
||||
1. Listen for requests on the specified hostname (domain name).
|
||||
2. Automatically obtain and renew a TLS certificate from Let's Encrypt for HTTPS.
|
||||
3. Route traffic to the **healthy** service container(s).
|
||||
4. Load balance across healthy replicas if there are multiple.
|
||||
|
||||
For advanced use cases, Uncloud allows to customise the Caddy config using the `x-caddy` extension in Compose files.
|
||||
See [Custom Caddy configuration](2-publishing-services.md#custom-caddy-configuration) for details.
|
||||
@@ -0,0 +1,352 @@
|
||||
# Publishing services
|
||||
|
||||
Publishing service ports makes your services available outside the cluster. This means your services can be accessed
|
||||
from the internet or local network, depending on your setup.
|
||||
|
||||
You can publish service ports in three ways:
|
||||
|
||||
- Using the `-p/--publish` flag with `uc run`.
|
||||
- Using the `x-ports` extension in a Compose file with `uc deploy`.
|
||||
- Using the `--caddyfile` flag with `uc run` or `x-caddy` extension in a Compose file for custom Caddy configuration.
|
||||
|
||||
For example, run a service with container port 8000 exposed as https://app.example.com via Caddy reverse proxy:
|
||||
|
||||
```shell
|
||||
uc run -p app.example.com:8000/https app:latest
|
||||
```
|
||||
|
||||
```
|
||||
[+] Running service app-mwng (replicated mode) 1/1
|
||||
✔ Container app-mwng-6lub on machine-fnr9 Started
|
||||
|
||||
app-mwng endpoints:
|
||||
• https://app.example.com → :8000
|
||||
```
|
||||
|
||||
Create an `A` record in your DNS provider (Cloudflare, Namecheap, etc.) pointing `app.example.com` to the public IP
|
||||
address or your machine(s). Once DNS is propagated and Caddy obtains a TLS certificate, you can access your service
|
||||
securely over HTTPS.
|
||||
|
||||
## Ingress vs host mode
|
||||
|
||||
**HTTP/HTTPS** ports are exposed via Caddy using the following format for the `-p/--publish` flag and `x-ports`
|
||||
extension:
|
||||
|
||||
```
|
||||
[hostname:]container_port[/protocol]
|
||||
```
|
||||
|
||||
- `hostname` (optional): The domain name to use for accessing the service. If omitted and a cluster domain is reserved,
|
||||
`<service-name>.<cluster-domain>` is used.
|
||||
- `container_port`: The port number within the container that's listening for traffic.
|
||||
- `protocol` (optional): `http` or `https` (default: `https`)
|
||||
|
||||
**TCP/UDP** ports can only be exposed in host mode, which binds the container port directly to the host machine's
|
||||
network interface(s). This is useful for non-HTTP services that need direct port access (bypasses Caddy):
|
||||
|
||||
```
|
||||
[host_ip:]host_port:container_port[/protocol]@host
|
||||
```
|
||||
|
||||
- `host_ip` (optional): The IP address on the host to bind to. If omitted, binds to all interfaces.
|
||||
- `host_port`: The port number on the host to bind to.
|
||||
- `container_port`: The port number within the container that's listening for traffic.
|
||||
- `protocol` (optional): `tcp` or `udp` (default: `tcp`)
|
||||
|
||||
| Port value | Description |
|
||||
|------------------------------|--------------------------------------------------------------------------------------|
|
||||
| `8000/http` | Publish port 8000 as HTTP via Caddy using hostname `<service-name>.<cluster-domain>` |
|
||||
| `app.example.com:8080/https` | Publish port 8080 as HTTPS via Caddy using hostname `app.example.com` |
|
||||
| `127.0.0.1:5432:5432@host` | Bind TCP port 5432 to host port 5432 on loopback interface only |
|
||||
| `53:5353/udp@host` | Bind UDP port 5353 to host port 53 on all network interfaces |
|
||||
|
||||
:::warning
|
||||
|
||||
Do not publish internal-only services like databases unless absolutely necessary. You only need to publish ports for
|
||||
services that should be accessible from outside the cluster. Services within the cluster can communicate with each other
|
||||
by their DNS names `service-name` or `service-name.internal` without publishing ports.
|
||||
|
||||
:::
|
||||
|
||||
## Using Compose
|
||||
|
||||
Use the `x-ports` extension in a Compose file to publish service ports:
|
||||
|
||||
```yaml title="compose.yaml"
|
||||
services:
|
||||
app:
|
||||
image: app:latest
|
||||
x-ports:
|
||||
- example.com:8000/https
|
||||
- www.example.com:8000/https # The same port can be published with multiple hostnames
|
||||
- api.domain.tld:9000/https # Another port can be published with a different hostname
|
||||
```
|
||||
|
||||
## Custom Caddy configuration
|
||||
|
||||
For advanced routing and behavior, use `x-caddy` instead of `x-ports`. It allows you to provide custom Caddy
|
||||
configuration for a service in [Caddyfile](https://caddyserver.com/docs/caddyfile) format.
|
||||
|
||||
```yaml title="compose.yaml"
|
||||
services:
|
||||
app:
|
||||
image: app:latest
|
||||
x-caddy: |
|
||||
www.example.com {
|
||||
redir https://example.com{uri} permanent
|
||||
}
|
||||
|
||||
example.com {
|
||||
basic_auth /admin/* {
|
||||
admin $2a$14$... # bcrypt hash
|
||||
}
|
||||
|
||||
header /static/* Cache-Control max-age=604800
|
||||
reverse_proxy {{upstreams 8000}} {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
```
|
||||
|
||||
You can inline the Caddyfile or load it from a file: `x-caddy: ./Caddyfile`. When using a file, the path is relative to
|
||||
the Compose file location. See the [Caddy documentation](https://caddyserver.com/docs/caddyfile) for syntax and
|
||||
features.
|
||||
|
||||
:::info note
|
||||
|
||||
You cannot use `x-caddy` with `http` or `https` ports in `x-ports`. `tcp` and `udp` ports in host mode are allowed
|
||||
though.
|
||||
|
||||
:::
|
||||
|
||||
Use it when you need:
|
||||
|
||||
- Custom routing rules (different paths, redirects, rewrites, multiple services on one domain).
|
||||
- Custom headers, authentication, or caching.
|
||||
- Custom load balancing strategies and options.
|
||||
- Request and response manipulation.
|
||||
- Advanced TLS settings.
|
||||
- Other Caddy features and plugins.
|
||||
|
||||
See [Deploying or updating Caddy](3-managing-caddy.md#deploying-or-updating-caddy) for details on deploying Caddy with a
|
||||
custom global configuration.
|
||||
|
||||
### Templates
|
||||
|
||||
`x-caddy` configs are processed as [Go templates](https://pkg.go.dev/text/template), allowing you to use dynamic values.
|
||||
The following functions and variables are available:
|
||||
|
||||
| Template | Description |
|
||||
|---------------------------------------|-----------------------------------------------------------------------------------------------|
|
||||
| `{{upstreams [service-name] [port]}}` | A space-separated list of healthy container IPs for the current or specified service and port |
|
||||
| `{{.Name}}` | The name of the service the config belongs to |
|
||||
| `{{.Upstreams}}` | A map of all service names to their healthy container IPs |
|
||||
|
||||
The templates are automatically re-rendered and Caddy is reloaded when service containers start/stop or health status
|
||||
changes.
|
||||
|
||||
**Examples:**
|
||||
|
||||
1. Current service upstreams, default port:
|
||||
```caddyfile
|
||||
reverse_proxy {{upstreams}}
|
||||
```
|
||||
↓
|
||||
|
||||
```caddyfile
|
||||
reverse_proxy 10.210.1.3 10.210.2.5
|
||||
```
|
||||
2. Current service upstreams, port 8000:
|
||||
```caddyfile
|
||||
reverse_proxy {{upstreams 8000}}
|
||||
```
|
||||
↓
|
||||
|
||||
```caddyfile
|
||||
reverse_proxy 10.210.1.3:8000 10.210.2.5:8000
|
||||
```
|
||||
3. Current service upstreams with `https` scheme:
|
||||
```caddyfile
|
||||
reverse_proxy {{- range $ip := index .Upstreams .Name}} https://{{$ip}}{{end}}
|
||||
```
|
||||
↓
|
||||
|
||||
```caddyfile
|
||||
reverse_proxy https://10.210.1.3 https://10.210.2.5
|
||||
```
|
||||
4. `api` service upstreams, port 9000:
|
||||
```caddyfile
|
||||
handle_path /api/* {
|
||||
reverse_proxy {{upstreams "api" 9000}}
|
||||
}
|
||||
```
|
||||
↓
|
||||
|
||||
```caddyfile
|
||||
handle_path /api/* {
|
||||
reverse_proxy 10.210.2.2:9000 10.210.1.7:9000 10.210.2.3:9000
|
||||
}
|
||||
```
|
||||
|
||||
### Verifying Caddy config
|
||||
|
||||
Use `uc caddy config` to view the complete generated Caddyfile served by the `caddy` service. This is useful for
|
||||
debugging and verifying your `x-caddy` configs.
|
||||
|
||||
Example output:
|
||||
|
||||
```caddyfile
|
||||
# This file is autogenerated by Uncloud based on the configuration of running services.
|
||||
# Do not edit manually. Any manual changes will be overwritten on the next update.
|
||||
|
||||
# User-defined global config from service 'caddy'.
|
||||
*.example.com {
|
||||
tls {
|
||||
dns cloudflare {env.CLOUDFLARE_API_TOKEN}
|
||||
}
|
||||
respond "No host matched" 404
|
||||
}
|
||||
|
||||
# Health check endpoint to verify Caddy reachability on this machine.
|
||||
http:// {
|
||||
handle /.uncloud-verify {
|
||||
respond "a369b9388812f9557feef6a0f5b46f2e" 200
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
(common_proxy) {
|
||||
# Retry failed requests up to lb_retries times against other available upstreams.
|
||||
lb_retries 3
|
||||
# Upstreams are marked unhealthy for fail_duration after a failed request (passive health checking).
|
||||
fail_duration 30s
|
||||
}
|
||||
|
||||
# Sites generated from service ports.
|
||||
|
||||
https://app.example.com {
|
||||
reverse_proxy 10.210.1.3:8000 10.210.2.5:8000 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
https://api.example.com {
|
||||
reverse_proxy 10.210.2.2:9000 10.210.1.7:9000 10.210.2.3:9000 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
# User-defined config for service 'web'.
|
||||
www.example.com {
|
||||
redir https://example.com{uri} permanent
|
||||
}
|
||||
|
||||
example.com {
|
||||
reverse_proxy 10.210.0.3:8000 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
# Skipped invalid user-defined configs:
|
||||
# - service 'duplicate-hostname': validation failed: adapting config using caddyfile adapter: ambiguous site definition: example.com
|
||||
# - service 'invalid': validation failed: adapting config using caddyfile adapter: Caddyfile:61: unrecognized directive: invalid_directive
|
||||
```
|
||||
|
||||
The generated config combines:
|
||||
|
||||
- Global Caddy configuration (`x-caddy` from the `caddy` service).
|
||||
See [Deploying or updating Caddy](3-managing-caddy.md#deploying-or-updating-caddy) for details.
|
||||
- Auto-generated configs from published service ports (`x-ports`).
|
||||
- Custom Caddy configs from services (`x-caddy`).
|
||||
- Skipped invalid configs with error messages as comments.
|
||||
|
||||
:::warning important
|
||||
|
||||
Custom Caddy configs from different services must not conflict (all services must use unique hostnames).
|
||||
See [Multiple services on one domain](#multiple-services-on-one-domain) for an example of how to share one hostname
|
||||
between multiple services.
|
||||
|
||||
Conflicting or invalid configs are detected using [caddy adapt](https://caddyserver.com/docs/command-line#caddy-adapt)
|
||||
command and skipped. However, some errors could still break the entire config so Caddy will fail to load it. Check the
|
||||
`caddy` service logs to troubleshoot.
|
||||
|
||||
:::
|
||||
|
||||
### Common use cases
|
||||
|
||||
#### Redirects
|
||||
|
||||
Publish a service on `example.com` and redirect requests from `www.example.com` to `example.com`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="compose.yaml">
|
||||
|
||||
```yaml
|
||||
services:
|
||||
app:
|
||||
image: app:latest
|
||||
x-caddy: ./Caddyfile
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="Caddyfile">
|
||||
|
||||
```caddyfile
|
||||
www.example.com {
|
||||
redir https://example.com{uri} permanent
|
||||
}
|
||||
|
||||
example.com {
|
||||
reverse_proxy {{upstreams 8000}} {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
#### Multiple services on one domain
|
||||
|
||||
You can publish multiple services on the same hostname by using different paths for each service. For example, route
|
||||
`/` to the web service and `/api` to the API service:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="compose.yaml">
|
||||
|
||||
```yaml
|
||||
services:
|
||||
api:
|
||||
image: api:latest
|
||||
web:
|
||||
image: web:latest
|
||||
# Make sure only one service defines a Caddy config for the hostname.
|
||||
x-caddy: ./Caddyfile
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="Caddyfile">
|
||||
|
||||
```caddyfile
|
||||
example.com {
|
||||
handle_path /api/* {
|
||||
reverse_proxy {{upstreams "api" 9000}} {
|
||||
import common_proxy
|
||||
}
|
||||
}
|
||||
|
||||
reverse_proxy {{upstreams}} {
|
||||
import common_proxy
|
||||
}
|
||||
|
||||
log
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
@@ -0,0 +1,233 @@
|
||||
# Managing Caddy
|
||||
|
||||
Caddy is automatically deployed as a global service `caddy` when you initialise a cluster with `uc machine init`. It
|
||||
runs on every machine to handle incoming HTTP/HTTPS traffic and route it to your services.
|
||||
|
||||
## Checking status
|
||||
|
||||
View the `caddy` service status and which machines it's running on:
|
||||
|
||||
```shell
|
||||
uc inspect caddy
|
||||
```
|
||||
|
||||
```
|
||||
ID: b5b269d5dc5ed4fdae6542894f94de82
|
||||
Name: caddy
|
||||
Mode: global
|
||||
|
||||
CONTAINER ID IMAGE CREATED STATUS MACHINE
|
||||
fb8f390e634d caddy:2.10.0 3 weeks ago Up 3 weeks prod-ap1
|
||||
0182f5d7bd9f caddy:2.10.0 3 months ago Up 3 weeks prod-us1
|
||||
```
|
||||
|
||||
## Deploying or updating Caddy
|
||||
|
||||
### Using CLI
|
||||
|
||||
Update to the latest stable version using the [caddy](https://hub.docker.com/_/caddy) image from Docker Hub:
|
||||
|
||||
```shell
|
||||
uc caddy deploy
|
||||
```
|
||||
|
||||
Deploy a specific version or custom image:
|
||||
|
||||
```shell
|
||||
uc caddy deploy --image caddybuilds/caddy-cloudflare:2.10.2
|
||||
```
|
||||
|
||||
Deploy with custom global configuration:
|
||||
|
||||
```shell
|
||||
uc caddy deploy --caddyfile global.Caddyfile
|
||||
```
|
||||
|
||||
Example global configuration:
|
||||
|
||||
```caddyfile title=global.Caddyfile
|
||||
# Global options.
|
||||
{
|
||||
debug
|
||||
}
|
||||
|
||||
# A snippet that can be reused in custom Caddy configs for services (x-caddy).
|
||||
(my_snippet) {
|
||||
...
|
||||
}
|
||||
|
||||
# Expose an internal service that is not managed by Uncloud.
|
||||
internal.example.com {
|
||||
reverse_proxy 192.168.1.100
|
||||
}
|
||||
```
|
||||
|
||||
### Using Compose
|
||||
|
||||
You can manage the Caddy deployment with a Compose file for more control. For example, to deploy a custom global Caddy
|
||||
config that uses the DNS challenge with Cloudflare to obtain a wildcard TLS certificate for `*.example.com`:
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="compose.yaml">
|
||||
|
||||
```yaml
|
||||
services:
|
||||
caddy:
|
||||
image: caddybuilds/caddy-cloudflare:2.10.2
|
||||
command: caddy run -c /config/Caddyfile --watch
|
||||
environment:
|
||||
CADDY_ADMIN: unix//run/caddy/admin.sock
|
||||
env_file:
|
||||
# Contains CLOUDFLARE_API_TOKEN=xxxxx
|
||||
- .env.secrets
|
||||
volumes:
|
||||
- /var/lib/uncloud/caddy:/data
|
||||
- /var/lib/uncloud/caddy:/config
|
||||
- /run/uncloud/caddy:/run/caddy
|
||||
x-ports:
|
||||
- 80:80@host
|
||||
- 443:443@host
|
||||
x-caddy: Caddyfile
|
||||
deploy:
|
||||
mode: global
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="Caddyfile">
|
||||
|
||||
```caddyfile
|
||||
# Global options.
|
||||
{
|
||||
debug
|
||||
}
|
||||
|
||||
# A snippet that can be reused in custom Caddy configs for services (x-caddy).
|
||||
(my_snippet) {
|
||||
...
|
||||
}
|
||||
|
||||
# Obtain a wildcard TLS certificate for all subdomains of example.name using DNS challenge with Cloudflare.
|
||||
# It will be used for services that publish ports with hostnames under example.name.
|
||||
*.example.com {
|
||||
tls {
|
||||
dns cloudflare {env.CLOUDFLARE_API_TOKEN}
|
||||
}
|
||||
respond "No host matched" 404
|
||||
}
|
||||
|
||||
# Expose an internal service that is not managed by Uncloud.
|
||||
internal.example.com {
|
||||
reverse_proxy 192.168.1.100
|
||||
}
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
:::info note
|
||||
|
||||
The specified `command`, `environment`, `volumes`, and `x-ports` properties are essential for Caddy to function
|
||||
correctly in the Uncloud cluster.
|
||||
|
||||
:::
|
||||
|
||||
Deploy or update the `caddy` service from the Compose file:
|
||||
|
||||
```shell
|
||||
uc deploy
|
||||
```
|
||||
|
||||
## Verifying config
|
||||
|
||||
View the complete generated Caddyfile served by the `caddy` service. This is useful for debugging and verifying
|
||||
custom global and service-specific Caddy configs.
|
||||
|
||||
```shell
|
||||
uc caddy config
|
||||
```
|
||||
|
||||
Example output:
|
||||
|
||||
```caddyfile
|
||||
# This file is autogenerated by Uncloud based on the configuration of running services.
|
||||
# Do not edit manually. Any manual changes will be overwritten on the next update.
|
||||
|
||||
# User-defined global config from service 'caddy'.
|
||||
# Global options.
|
||||
{
|
||||
debug
|
||||
}
|
||||
|
||||
# A snippet that can be reused in custom Caddy configs for services (x-caddy).
|
||||
(my_snippet) {
|
||||
...
|
||||
}
|
||||
|
||||
# Obtain a wildcard TLS certificate for all subdomains of example.name using DNS challenge with Cloudflare.
|
||||
# It will be used for services that publish ports with hostnames under example.name.
|
||||
*.example.com {
|
||||
tls {
|
||||
dns cloudflare {env.CLOUDFLARE_API_TOKEN}
|
||||
}
|
||||
respond "No host matched" 404
|
||||
}
|
||||
|
||||
# Expose an internal service that is not managed by Uncloud.
|
||||
internal.example.com {
|
||||
reverse_proxy 192.168.1.100
|
||||
}
|
||||
|
||||
# Health check endpoint to verify Caddy reachability on this machine.
|
||||
http:// {
|
||||
handle /.uncloud-verify {
|
||||
respond "a369b9388812f9557feef6a0f5b46f2e" 200
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
(common_proxy) {
|
||||
# Retry failed requests up to lb_retries times against other available upstreams.
|
||||
lb_retries 3
|
||||
# Upstreams are marked unhealthy for fail_duration after a failed request (passive health checking).
|
||||
fail_duration 30s
|
||||
}
|
||||
|
||||
# Sites generated from service ports.
|
||||
|
||||
https://app.example.com {
|
||||
reverse_proxy 10.210.1.3:8000 10.210.2.5:8000 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
https://api.example.com {
|
||||
reverse_proxy 10.210.2.2:9000 10.210.1.7:9000 10.210.2.3:9000 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
# User-defined config for service 'web'.
|
||||
www.example.com {
|
||||
redir https://example.com{uri} permanent
|
||||
}
|
||||
|
||||
example.com {
|
||||
reverse_proxy 10.210.0.3:8000 {
|
||||
import common_proxy
|
||||
}
|
||||
log
|
||||
}
|
||||
|
||||
# Skipped invalid user-defined configs:
|
||||
# - service 'duplicate-hostname': validation failed: adapting config using caddyfile adapter: ambiguous site definition: example.com
|
||||
# - service 'invalid': validation failed: adapting config using caddyfile adapter: Caddyfile:61: unrecognized directive: invalid_directive
|
||||
```
|
||||
|
||||
The generated config combines:
|
||||
|
||||
- Global Caddy configuration (`x-caddy` from the `caddy` service).
|
||||
- Auto-generated configs from published service ports (`x-ports`).
|
||||
- Custom Caddy configs from services (`x-caddy`).
|
||||
- Skipped invalid configs with error messages as comments.
|
||||
@@ -0,0 +1,4 @@
|
||||
label: Ingress & HTTPS
|
||||
collapsed: true # keep the category closed by default
|
||||
link:
|
||||
type: generated-index
|
||||
@@ -0,0 +1,4 @@
|
||||
label: Concepts
|
||||
collapsed: false # keep the category open by default
|
||||
link:
|
||||
type: generated-index
|
||||
@@ -0,0 +1,4 @@
|
||||
label: CLI reference
|
||||
collapsed: true # keep the category closed by default
|
||||
link:
|
||||
type: generated-index
|
||||
@@ -0,0 +1,29 @@
|
||||
# uc
|
||||
|
||||
A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
-h, --help help for uc
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc build](uc_build.md) - Build services from a Compose file.
|
||||
* [uc caddy](uc_caddy.md) - Manage Caddy reverse proxy service.
|
||||
* [uc ctx](uc_ctx.md) - Switch between different cluster contexts. Contains subcommands to manage contexts.
|
||||
* [uc deploy](uc_deploy.md) - Deploy services from a Compose file.
|
||||
* [uc dns](uc_dns.md) - Manage cluster domain in Uncloud DNS.
|
||||
* [uc inspect](uc_inspect.md) - Display detailed information on a service.
|
||||
* [uc ls](uc_ls.md) - List services.
|
||||
* [uc machine](uc_machine.md) - Manage machines in an Uncloud cluster.
|
||||
* [uc rm](uc_rm.md) - Remove one or more services.
|
||||
* [uc run](uc_run.md) - Run a service.
|
||||
* [uc scale](uc_scale.md) - Scale a replicated service by changing the number of replicas.
|
||||
* [uc service](uc_service.md) - Manage services in an Uncloud cluster.
|
||||
* [uc volume](uc_volume.md) - Manage volumes in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# uc build
|
||||
|
||||
Build services from a Compose file.
|
||||
|
||||
```
|
||||
uc build [FLAGS] [SERVICE...] [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-f, --file strings One or more Compose files to build (default compose.yaml)
|
||||
-h, --help help for build
|
||||
-n, --no-cache Do not use cache when building images. (default false)
|
||||
-p, --profile strings One or more Compose profiles to enable.
|
||||
-P, --push Push built images to the registry after building. (default false)
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc](uc.md) - A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# uc caddy
|
||||
|
||||
Manage Caddy reverse proxy service.
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-h, --help help for caddy
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc](uc.md) - A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
* [uc caddy config](uc_caddy_config.md) - Show the current Caddy configuration (Caddyfile).
|
||||
* [uc caddy deploy](uc_caddy_deploy.md) - Deploy or upgrade Caddy reverse proxy across all machines in the cluster.
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# uc caddy config
|
||||
|
||||
Show the current Caddy configuration (Caddyfile).
|
||||
|
||||
## Synopsis
|
||||
|
||||
Display the current Caddy configuration (Caddyfile) from the connected machine or a specified one.
|
||||
|
||||
```
|
||||
uc caddy config [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for config
|
||||
-m, --machine string Name or ID of the machine to get the configuration from. (default is connected machine)
|
||||
--no-color Disable syntax highlighting for the output.
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc caddy](uc_caddy.md) - Manage Caddy reverse proxy service.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# uc caddy deploy
|
||||
|
||||
Deploy or upgrade Caddy reverse proxy across all machines in the cluster.
|
||||
|
||||
## Synopsis
|
||||
|
||||
Deploy or upgrade Caddy reverse proxy across all machines in the cluster.
|
||||
A rolling update is performed when updating existing containers to minimise disruption.
|
||||
|
||||
```
|
||||
uc caddy deploy [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
--caddyfile string Path to a custom global Caddy config (Caddyfile) that will be prepended to the auto-generated Caddy config.
|
||||
-c, --context string Name of the cluster context to deploy to. (default is the current context)
|
||||
-h, --help help for deploy
|
||||
--image string Caddy Docker image to deploy. (default caddy:LATEST_VERSION)
|
||||
-m, --machine strings Machine names to deploy to. Can be specified multiple times or as a comma-separated list of machine names. (default is all machines)
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc caddy](uc_caddy.md) - Manage Caddy reverse proxy service.
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# uc ctx
|
||||
|
||||
Switch between different cluster contexts. Contains subcommands to manage contexts.
|
||||
|
||||
```
|
||||
uc ctx [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-h, --help help for ctx
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc](uc.md) - A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
* [uc ctx ls](uc_ctx_ls.md) - List available cluster contexts.
|
||||
* [uc ctx use](uc_ctx_use.md) - Switch to a different cluster context.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# uc ctx ls
|
||||
|
||||
List available cluster contexts.
|
||||
|
||||
```
|
||||
uc ctx ls [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for ls
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc ctx](uc_ctx.md) - Switch between different cluster contexts. Contains subcommands to manage contexts.
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# uc ctx use
|
||||
|
||||
Switch to a different cluster context.
|
||||
|
||||
## Synopsis
|
||||
|
||||
Switch to a different cluster context. If no context is provided, a list of available contexts will be displayed for selection.
|
||||
|
||||
```
|
||||
uc ctx use [CONTEXT] [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-h, --help help for use
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc ctx](uc_ctx.md) - Switch between different cluster contexts. Contains subcommands to manage contexts.
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# uc deploy
|
||||
|
||||
Deploy services from a Compose file.
|
||||
|
||||
```
|
||||
uc deploy [FLAGS] [SERVICE...] [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context to deploy to (default is the current context)
|
||||
-f, --file strings One or more Compose files to deploy services from. (default compose.yaml)
|
||||
-h, --help help for deploy
|
||||
-n, --no-build Do not build images before deploying services. (default false)
|
||||
-p, --profile strings One or more Compose profiles to enable.
|
||||
--recreate Recreate containers even if their configuration and image haven't changed.
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc](uc.md) - A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# uc dns
|
||||
|
||||
Manage cluster domain in Uncloud DNS.
|
||||
|
||||
## Synopsis
|
||||
|
||||
Manage cluster domain in Uncloud DNS.
|
||||
DNS commands allow you to reserve or release a unique '\<id>.cluster.uncloud.run' domain for your cluster. When reserved, Caddy service deployments will automatically update DNS records to route traffic to the services in the cluster.
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-h, --help help for dns
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc](uc.md) - A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
* [uc dns release](uc_dns_release.md) - Release the reserved cluster domain.
|
||||
* [uc dns reserve](uc_dns_reserve.md) - Reserve a cluster domain in Uncloud DNS.
|
||||
* [uc dns show](uc_dns_show.md) - Print the cluster domain name.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# uc dns release
|
||||
|
||||
Release the reserved cluster domain.
|
||||
|
||||
```
|
||||
uc dns release [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for release
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc dns](uc_dns.md) - Manage cluster domain in Uncloud DNS.
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# uc dns reserve
|
||||
|
||||
Reserve a cluster domain in Uncloud DNS.
|
||||
|
||||
```
|
||||
uc dns reserve [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
--endpoint string API endpoint for the Uncloud DNS service. (default "https://dns.uncloud.run/v1")
|
||||
-h, --help help for reserve
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc dns](uc_dns.md) - Manage cluster domain in Uncloud DNS.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# uc dns show
|
||||
|
||||
Print the cluster domain name.
|
||||
|
||||
```
|
||||
uc dns show [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for show
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc dns](uc_dns.md) - Manage cluster domain in Uncloud DNS.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# uc inspect
|
||||
|
||||
Display detailed information on a service.
|
||||
|
||||
```
|
||||
uc inspect SERVICE [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for inspect
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc](uc.md) - A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# uc ls
|
||||
|
||||
List services.
|
||||
|
||||
```
|
||||
uc ls [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for ls
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc](uc.md) - A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# uc machine
|
||||
|
||||
Manage machines in an Uncloud cluster.
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-h, --help help for machine
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc](uc.md) - A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
* [uc machine add](uc_machine_add.md) - Add a remote machine to a cluster.
|
||||
* [uc machine init](uc_machine_init.md) - Initialise a new cluster with a remote machine as the first member.
|
||||
* [uc machine ls](uc_machine_ls.md) - List machines in a cluster.
|
||||
* [uc machine rename](uc_machine_rename.md) - Rename a machine in the cluster.
|
||||
* [uc machine rm](uc_machine_rm.md) - Remove a machine from a cluster and reset it.
|
||||
* [uc machine token](uc_machine_token.md) - Print the local machine's token for adding it to a cluster.
|
||||
* [uc machine update](uc_machine_update.md) - Update machine configuration in the cluster.
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# uc machine add
|
||||
|
||||
Add a remote machine to a cluster.
|
||||
|
||||
```
|
||||
uc machine add [USER@]HOST[:PORT] [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context to add the machine to. (default is the current context)
|
||||
-h, --help help for add
|
||||
-n, --name string Assign a name to the machine.
|
||||
--no-caddy Don't deploy Caddy reverse proxy service to the machine.
|
||||
--public-ip string Public IP address of the machine for ingress configuration. Use 'auto' for automatic detection, blank '' or 'none' to disable ingress on this machine, or specify an IP address. (default "auto")
|
||||
-i, --ssh-key string Path to SSH private key for remote login (if not already added to SSH agent). (default "~/.ssh/id_ed25519")
|
||||
--version string Version of the Uncloud daemon to install on the machine. (default "latest")
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc machine](uc_machine.md) - Manage machines in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# uc machine init
|
||||
|
||||
Initialise a new cluster with a remote machine as the first member.
|
||||
|
||||
```
|
||||
uc machine init [USER@HOST:PORT] [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the created context for the initialised cluster in the Uncloud config. (default "default")
|
||||
--dns-endpoint string API endpoint for the Uncloud DNS service. (default "https://dns.uncloud.run/v1")
|
||||
-h, --help help for init
|
||||
-n, --name string Assign a name to the machine.
|
||||
--network string IPv4 network CIDR to use for machines and services. (default "10.210.0.0/16")
|
||||
--no-caddy Don't deploy Caddy reverse proxy service to the machine.
|
||||
--no-dns Don't reserve a cluster domain in Uncloud DNS.
|
||||
--public-ip string Public IP address of the machine for ingress configuration. Use 'auto' for automatic detection, blank '' or 'none' to disable ingress on this machine, or specify an IP address. (default "auto")
|
||||
-i, --ssh-key string Path to SSH private key for remote login (if not already added to SSH agent). (default "~/.ssh/id_ed25519")
|
||||
--version string Version of the Uncloud daemon to install on the machine. (default "latest")
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc machine](uc_machine.md) - Manage machines in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# uc machine ls
|
||||
|
||||
List machines in a cluster.
|
||||
|
||||
```
|
||||
uc machine ls [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for ls
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc machine](uc_machine.md) - Manage machines in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# uc machine rename
|
||||
|
||||
Rename a machine in the cluster.
|
||||
|
||||
## Synopsis
|
||||
|
||||
Rename a machine in the cluster.
|
||||
|
||||
This command changes the name of an existing machine while preserving all other
|
||||
configuration including network settings, public IP, and cluster membership.
|
||||
|
||||
```
|
||||
uc machine rename OLD_NAME NEW_NAME [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for rename
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc machine](uc_machine.md) - Manage machines in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# uc machine rm
|
||||
|
||||
Remove a machine from a cluster and reset it.
|
||||
|
||||
```
|
||||
uc machine rm MACHINE [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for rm
|
||||
--no-reset Do not reset the machine after removing it from the cluster. This will leave all containers and data intact.
|
||||
-y, --yes Do not prompt for confirmation before removing the machine.
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc machine](uc_machine.md) - Manage machines in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# uc machine token
|
||||
|
||||
Print the local machine's token for adding it to a cluster.
|
||||
|
||||
```
|
||||
uc machine token [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-d, --data-dir string Directory for storing persistent machine state. (default "/var/lib/uncloud")
|
||||
-h, --help help for token
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc machine](uc_machine.md) - Manage machines in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
# uc machine update
|
||||
|
||||
Update machine configuration in the cluster.
|
||||
|
||||
## Synopsis
|
||||
|
||||
Update machine configuration in the cluster.
|
||||
|
||||
This command allows setting various machine properties including:
|
||||
- Machine name (--name)
|
||||
- Public IP address (--public-ip)
|
||||
|
||||
At least one flag must be specified to perform an update operation.
|
||||
|
||||
```
|
||||
uc machine update [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for update
|
||||
--name string New name for the machine
|
||||
--public-ip string Public IP address of the machine for ingress configuration. Use 'none' or '' to remove the public IP.
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc machine](uc_machine.md) - Manage machines in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# uc rm
|
||||
|
||||
Remove one or more services.
|
||||
|
||||
```
|
||||
uc rm SERVICE [SERVICE...] [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for rm
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc](uc.md) - A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# uc run
|
||||
|
||||
Run a service.
|
||||
|
||||
```
|
||||
uc run IMAGE [COMMAND...] [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
--caddyfile string Path to a custom Caddy config (Caddyfile) for the service. Cannot be used together with non-@host published ports.
|
||||
-c, --context string Name of the cluster context to run the service in. (default is the current context)
|
||||
--cpu decimal Maximum number of CPU cores a service container can use. Fractional values are allowed: 0.5 for half a core or 2.25 for two and a quarter cores.
|
||||
--entrypoint string Overwrite the default ENTRYPOINT of the image. Pass an empty string "" to reset it.
|
||||
-e, --env strings Set an environment variable for service containers. Can be specified multiple times.
|
||||
Format: VAR=value or just VAR to use the value from the local environment.
|
||||
-h, --help help for run
|
||||
-m, --machine strings Placement constraint by machine names, limiting which machines the service can run on. Can be specified multiple times or as a comma-separated list of machine names. (default is any suitable machine)
|
||||
--memory bytes Maximum amount of memory a service container can use. Value is a positive integer with optional unit suffix (b, k, m, g). Default unit is bytes if no suffix specified.
|
||||
Examples: 1073741824, 1024m, 1g (all equal 1 gibibyte)
|
||||
--mode string Replication mode of the service: either 'replicated' (a specified number of containers across the machines) or 'global' (one container on every machine). (default "replicated")
|
||||
-n, --name string Assign a name to the service. A random name is generated if not specified.
|
||||
--privileged Give extended privileges to service containers. This is a security risk and should be used with caution.
|
||||
-p, --publish strings Publish a service port to make it accessible outside the cluster. Can be specified multiple times.
|
||||
Format: [hostname:]container_port[/protocol] or [host_ip:]host_port:container_port[/protocol]@host
|
||||
Supported protocols: tcp, udp, http, https (default is tcp). If a hostname for http(s) port is not specified
|
||||
and a cluster domain is reserved, service-name.cluster-domain will be used as the hostname.
|
||||
Examples:
|
||||
-p 8080/https Publish port 8080 as HTTPS via reverse proxy with default service-name.cluster-domain hostname
|
||||
-p app.example.com:8080/https Publish port 8080 as HTTPS via reverse proxy with custom hostname
|
||||
-p 53:5353/udp@host Bind UDP port 5353 to host port 53
|
||||
--pull string Pull image from the registry before running service containers ('always', 'missing', 'never'). (default "missing")
|
||||
--replicas uint Number of containers to run for the service. Only valid for a replicated service. (default 1)
|
||||
-u, --user string User name or UID and optionally group name or GID used for running the command inside service containers.
|
||||
Format: USER[:GROUP] or UID[:GID]. If not specified, the user is set to the default user of the image.
|
||||
-v, --volume strings Mount a data volume or host path into service containers. Service containers will be scheduled on the machine(s) where
|
||||
the volume is located. Can be specified multiple times.
|
||||
Format: volume_name:/container/path[:ro|volume-nocopy] or /host/path:/container/path[:ro]
|
||||
Examples:
|
||||
-v postgres-data:/var/lib/postgresql/data Mount volume 'postgres-data' to /var/lib/postgresql/data in container
|
||||
-v /data/uploads:/app/uploads Bind mount /data/uploads host directory to /app/uploads in container
|
||||
-v /host/path:/container/path:ro Bind mount a host directory or file as read-only
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc](uc.md) - A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# uc scale
|
||||
|
||||
Scale a replicated service by changing the number of replicas.
|
||||
|
||||
## Synopsis
|
||||
|
||||
Scale a replicated service by changing the number of replicas. Scaling down requires confirmation.
|
||||
|
||||
```
|
||||
uc scale SERVICE REPLICAS [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for scale
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc](uc.md) - A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# uc service
|
||||
|
||||
Manage services in an Uncloud cluster.
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-h, --help help for service
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc](uc.md) - A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
* [uc service inspect](uc_service_inspect.md) - Display detailed information on a service.
|
||||
* [uc service ls](uc_service_ls.md) - List services.
|
||||
* [uc service rm](uc_service_rm.md) - Remove one or more services.
|
||||
* [uc service run](uc_service_run.md) - Run a service.
|
||||
* [uc service scale](uc_service_scale.md) - Scale a replicated service by changing the number of replicas.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# uc service inspect
|
||||
|
||||
Display detailed information on a service.
|
||||
|
||||
```
|
||||
uc service inspect SERVICE [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for inspect
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc service](uc_service.md) - Manage services in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# uc service ls
|
||||
|
||||
List services.
|
||||
|
||||
```
|
||||
uc service ls [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for ls
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc service](uc_service.md) - Manage services in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# uc service rm
|
||||
|
||||
Remove one or more services.
|
||||
|
||||
```
|
||||
uc service rm SERVICE [SERVICE...] [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for rm
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc service](uc_service.md) - Manage services in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# uc service run
|
||||
|
||||
Run a service.
|
||||
|
||||
```
|
||||
uc service run IMAGE [COMMAND...] [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
--caddyfile string Path to a custom Caddy config (Caddyfile) for the service. Cannot be used together with non-@host published ports.
|
||||
-c, --context string Name of the cluster context to run the service in. (default is the current context)
|
||||
--cpu decimal Maximum number of CPU cores a service container can use. Fractional values are allowed: 0.5 for half a core or 2.25 for two and a quarter cores.
|
||||
--entrypoint string Overwrite the default ENTRYPOINT of the image. Pass an empty string "" to reset it.
|
||||
-e, --env strings Set an environment variable for service containers. Can be specified multiple times.
|
||||
Format: VAR=value or just VAR to use the value from the local environment.
|
||||
-h, --help help for run
|
||||
-m, --machine strings Placement constraint by machine names, limiting which machines the service can run on. Can be specified multiple times or as a comma-separated list of machine names. (default is any suitable machine)
|
||||
--memory bytes Maximum amount of memory a service container can use. Value is a positive integer with optional unit suffix (b, k, m, g). Default unit is bytes if no suffix specified.
|
||||
Examples: 1073741824, 1024m, 1g (all equal 1 gibibyte)
|
||||
--mode string Replication mode of the service: either 'replicated' (a specified number of containers across the machines) or 'global' (one container on every machine). (default "replicated")
|
||||
-n, --name string Assign a name to the service. A random name is generated if not specified.
|
||||
--privileged Give extended privileges to service containers. This is a security risk and should be used with caution.
|
||||
-p, --publish strings Publish a service port to make it accessible outside the cluster. Can be specified multiple times.
|
||||
Format: [hostname:]container_port[/protocol] or [host_ip:]host_port:container_port[/protocol]@host
|
||||
Supported protocols: tcp, udp, http, https (default is tcp). If a hostname for http(s) port is not specified
|
||||
and a cluster domain is reserved, service-name.cluster-domain will be used as the hostname.
|
||||
Examples:
|
||||
-p 8080/https Publish port 8080 as HTTPS via reverse proxy with default service-name.cluster-domain hostname
|
||||
-p app.example.com:8080/https Publish port 8080 as HTTPS via reverse proxy with custom hostname
|
||||
-p 53:5353/udp@host Bind UDP port 5353 to host port 53
|
||||
--pull string Pull image from the registry before running service containers ('always', 'missing', 'never'). (default "missing")
|
||||
--replicas uint Number of containers to run for the service. Only valid for a replicated service. (default 1)
|
||||
-u, --user string User name or UID and optionally group name or GID used for running the command inside service containers.
|
||||
Format: USER[:GROUP] or UID[:GID]. If not specified, the user is set to the default user of the image.
|
||||
-v, --volume strings Mount a data volume or host path into service containers. Service containers will be scheduled on the machine(s) where
|
||||
the volume is located. Can be specified multiple times.
|
||||
Format: volume_name:/container/path[:ro|volume-nocopy] or /host/path:/container/path[:ro]
|
||||
Examples:
|
||||
-v postgres-data:/var/lib/postgresql/data Mount volume 'postgres-data' to /var/lib/postgresql/data in container
|
||||
-v /data/uploads:/app/uploads Bind mount /data/uploads host directory to /app/uploads in container
|
||||
-v /host/path:/container/path:ro Bind mount a host directory or file as read-only
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc service](uc_service.md) - Manage services in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# uc service scale
|
||||
|
||||
Scale a replicated service by changing the number of replicas.
|
||||
|
||||
## Synopsis
|
||||
|
||||
Scale a replicated service by changing the number of replicas. Scaling down requires confirmation.
|
||||
|
||||
```
|
||||
uc service scale SERVICE REPLICAS [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for scale
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc service](uc_service.md) - Manage services in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# uc volume
|
||||
|
||||
Manage volumes in an Uncloud cluster.
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-h, --help help for volume
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc](uc.md) - A CLI tool for managing Uncloud resources such as clusters, machines, and services.
|
||||
* [uc volume create](uc_volume_create.md) - Create a volume on a specific machine.
|
||||
* [uc volume inspect](uc_volume_inspect.md) - Display detailed information on a volume.
|
||||
* [uc volume ls](uc_volume_ls.md) - List volumes across all machines in the cluster.
|
||||
* [uc volume rm](uc_volume_rm.md) - Remove one or more volumes.
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# uc volume create
|
||||
|
||||
Create a volume on a specific machine.
|
||||
|
||||
```
|
||||
uc volume create VOLUME_NAME [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-d, --driver string Volume driver to use. (default "local")
|
||||
-h, --help help for create
|
||||
-l, --label strings Labels to assign to the volume in the form of 'key=value' pairs. Can be specified multiple times.
|
||||
-m, --machine string Name or ID of the machine to create the volume on.
|
||||
-o, --opt strings Driver specific options in the form of 'key=value' pairs. Can be specified multiple times.
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc volume](uc_volume.md) - Manage volumes in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# uc volume inspect
|
||||
|
||||
Display detailed information on a volume.
|
||||
|
||||
```
|
||||
uc volume inspect VOLUME_NAME [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for inspect
|
||||
-m, --machine string Name or ID of the machine where the volume is located. If not specified, the volume will be searched across all machines.
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc volume](uc_volume.md) - Manage volumes in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# uc volume ls
|
||||
|
||||
List volumes across all machines in the cluster.
|
||||
|
||||
```
|
||||
uc volume ls [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-h, --help help for ls
|
||||
-m, --machine strings Filter volumes by machine name or ID. Can be specified multiple times or as a comma-separated list. (default is include all machines)
|
||||
-q, --quiet Only display volume names.
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc volume](uc_volume.md) - Manage volumes in an Uncloud cluster.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# uc volume rm
|
||||
|
||||
Remove one or more volumes.
|
||||
|
||||
## Synopsis
|
||||
|
||||
Remove one or more volumes. You cannot remove a volume that is in use by a container.
|
||||
|
||||
```
|
||||
uc volume rm VOLUME_NAME [VOLUME_NAME...] [flags]
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```
|
||||
-c, --context string Name of the cluster context. (default is the current context)
|
||||
-f, --force Force the removal of one or more volumes.
|
||||
-h, --help help for rm
|
||||
-m, --machine strings Name or ID of the machine to remove one or more volumes from. Can be specified multiple times or as a comma-separated list.
|
||||
If not specified, the found volume(s) will be removed from all machines.
|
||||
-y, --yes Do not prompt for confirmation before removing the volume(s).
|
||||
```
|
||||
|
||||
## Options inherited from parent commands
|
||||
|
||||
```
|
||||
--connect string Connect to a remote cluster machine without using the Uncloud configuration file.
|
||||
Format: [ssh://]user@host[:port] or tcp://host:port
|
||||
--uncloud-config string Path to the Uncloud configuration file. (default "~/.config/uncloud/config.yaml")
|
||||
```
|
||||
|
||||
## See also
|
||||
|
||||
* [uc volume](uc_volume.md) - Manage volumes in an Uncloud cluster.
|
||||
|
||||
Reference in New Issue
Block a user