|
1 | 1 | package main
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "bufio" |
4 | 5 | "bytes"
|
5 | 6 | "context"
|
6 | 7 | "errors"
|
7 | 8 | "fmt"
|
8 | 9 | "os"
|
9 | 10 | "os/exec"
|
| 11 | + "strings" |
10 | 12 |
|
11 | 13 | "github.com/glasskube/distr/api"
|
12 | 14 | "github.com/glasskube/distr/internal/agentauth"
|
| 15 | + "github.com/glasskube/distr/internal/types" |
13 | 16 | "go.uber.org/zap"
|
| 17 | + "gopkg.in/yaml.v3" |
14 | 18 | )
|
15 | 19 |
|
16 |
| -func ApplyComposeFile(ctx context.Context, deployment api.DockerAgentDeployment) (*AgentDeployment, string, error) { |
| 20 | +func DockerEngineApply( |
| 21 | + ctx context.Context, |
| 22 | + deployment api.DockerAgentDeployment, |
| 23 | +) (*AgentDeployment, string, error) { |
| 24 | + |
| 25 | + if deployment.DockerType == types.DockerTypeSwarm { |
| 26 | + |
| 27 | + fmt.Println(deployment.RevisionID) |
| 28 | + |
| 29 | + // Step 1 Ensure Docker Swarm is initialized |
| 30 | + initCmd := exec.CommandContext(ctx, "docker", "info", "--format", "{{.Swarm.LocalNodeState}}") |
| 31 | + initOutput, err := initCmd.CombinedOutput() |
| 32 | + if err != nil { |
| 33 | + logger.Error("Failed to check Docker Swarm state", zap.Error(err)) |
| 34 | + return nil, "", fmt.Errorf("failed to check Docker Swarm state: %w", err) |
| 35 | + } |
| 36 | + |
| 37 | + if !strings.Contains(strings.TrimSpace(string(initOutput)), "active") { |
| 38 | + logger.Error("Docker Swarm not initialized", zap.String("output", string(initOutput))) |
| 39 | + return nil, "", fmt.Errorf("docker Swarm not initialized: %s", string(initOutput)) |
| 40 | + } |
| 41 | + // Step 2: Pull images before deployment |
| 42 | + _, err = PullSwarmMode(ctx, deployment) |
| 43 | + if err != nil { |
| 44 | + logger.Error("Failed to Pull", zap.Error(err)) |
| 45 | + return nil, "", err |
| 46 | + } |
| 47 | + return ApplyComposeFileSwarm(ctx, deployment) |
| 48 | + |
| 49 | + } |
| 50 | + return ApplyComposeFile(ctx, deployment) |
| 51 | + |
| 52 | +} |
| 53 | +func DockerEngineUninstall( |
| 54 | + ctx context.Context, deployment AgentDeployment, |
| 55 | +) error { |
| 56 | + if deployment.DockerType == types.DockerTypeSwarm { |
| 57 | + return UninstallDockerSwarm(ctx, deployment) |
| 58 | + } |
| 59 | + return UninstallDockerCompose(ctx, deployment) |
| 60 | +} |
| 61 | +func ApplyComposeFile( |
| 62 | + ctx context.Context, |
| 63 | + deployment api.DockerAgentDeployment, |
| 64 | +) (*AgentDeployment, string, error) { |
| 65 | + |
17 | 66 | agentDeploymet, err := NewAgentDeployment(deployment)
|
18 | 67 | if err != nil {
|
19 | 68 | return nil, "", err
|
@@ -60,11 +109,173 @@ func ApplyComposeFile(ctx context.Context, deployment api.DockerAgentDeployment)
|
60 | 109 | }
|
61 | 110 | }
|
62 | 111 |
|
63 |
| -func UninstallDockerCompose(ctx context.Context, deployment AgentDeployment) error { |
| 112 | +func ApplyComposeFileSwarm( |
| 113 | + ctx context.Context, |
| 114 | + deployment api.DockerAgentDeployment, |
| 115 | +) (*AgentDeployment, string, error) { |
| 116 | + |
| 117 | + agentDeployment, err := NewAgentDeployment(deployment) |
| 118 | + if err != nil { |
| 119 | + return nil, "", err |
| 120 | + } |
| 121 | + |
| 122 | + // Read the Compose file without replacing environment variables |
| 123 | + cleanedCompose := cleanComposeFile(deployment.ComposeFile) |
| 124 | + |
| 125 | + // Construct environment variables |
| 126 | + envVars := os.Environ() |
| 127 | + envVars = append(envVars, agentauth.DockerConfigEnv(deployment.AgentDeployment)...) |
| 128 | + |
| 129 | + // // If an env file is provided, load its values |
| 130 | + if deployment.EnvFile != nil { |
| 131 | + parsedEnv, err := parseEnvFile(deployment.EnvFile) |
| 132 | + if err != nil { |
| 133 | + logger.Error("Failed to parse env file", zap.Error(err)) |
| 134 | + return nil, "", fmt.Errorf("failed to parse env file: %w", err) |
| 135 | + } |
| 136 | + for key, value := range parsedEnv { |
| 137 | + envVars = append(envVars, fmt.Sprintf("%s=%s", key, value)) |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + // Deploy the stack |
| 142 | + composeArgs := []string{ |
| 143 | + "stack", "deploy", |
| 144 | + "--compose-file", "-", |
| 145 | + "--with-registry-auth", |
| 146 | + "--detach=true", |
| 147 | + agentDeployment.ProjectName, |
| 148 | + } |
| 149 | + cmd := exec.CommandContext(ctx, "docker", composeArgs...) |
| 150 | + cmd.Stdin = bytes.NewReader(cleanedCompose) |
| 151 | + cmd.Env = envVars // Ensure the same env variables are used |
| 152 | + |
| 153 | + // Execute the command and capture output |
| 154 | + cmdOut, err := cmd.CombinedOutput() |
| 155 | + statusStr := string(cmdOut) |
| 156 | + |
| 157 | + if err != nil { |
| 158 | + logger.Error("Docker stack deploy failed", zap.String("output", statusStr)) |
| 159 | + return nil, "", errors.New(statusStr) |
| 160 | + } |
| 161 | + |
| 162 | + return agentDeployment, statusStr, nil |
| 163 | +} |
| 164 | + |
| 165 | +func UninstallDockerCompose( |
| 166 | + ctx context.Context, deployment AgentDeployment, |
| 167 | +) error { |
64 | 168 | cmd := exec.CommandContext(ctx, "docker", "compose", "--project-name", deployment.ProjectName, "down", "--volumes")
|
65 | 169 | out, err := cmd.CombinedOutput()
|
66 | 170 | if err != nil {
|
67 | 171 | return fmt.Errorf("%w: %v", err, string(out))
|
68 | 172 | }
|
69 | 173 | return nil
|
70 | 174 | }
|
| 175 | + |
| 176 | +func UninstallDockerSwarm( |
| 177 | + ctx context.Context, deployment AgentDeployment, |
| 178 | +) error { |
| 179 | + |
| 180 | + cmd := exec.CommandContext(ctx, "docker", "stack", "rm", deployment.ProjectName) |
| 181 | + out, err := cmd.CombinedOutput() |
| 182 | + if err != nil { |
| 183 | + return fmt.Errorf("failed to remove Docker Swarm stack: %w: %v", err, string(out)) |
| 184 | + } |
| 185 | + |
| 186 | + // Optional: Prune unused networks created by Swarm |
| 187 | + pruneCmd := exec.CommandContext(ctx, "docker", "network", "prune", "-f") |
| 188 | + pruneOut, pruneErr := pruneCmd.CombinedOutput() |
| 189 | + if pruneErr != nil { |
| 190 | + logger.Warn("Failed to prune networks", zap.String("output", string(pruneOut)), zap.Error(pruneErr)) |
| 191 | + } |
| 192 | + |
| 193 | + return nil |
| 194 | +} |
| 195 | +func cleanComposeFile(composeData []byte) []byte { |
| 196 | + lines := strings.Split(string(composeData), "\n") |
| 197 | + cleanedLines := make([]string, 0, 50) |
| 198 | + |
| 199 | + for _, line := range lines { |
| 200 | + // Skip lines that define `name:` |
| 201 | + if strings.HasPrefix(strings.TrimSpace(line), "name:") { |
| 202 | + continue |
| 203 | + } |
| 204 | + cleanedLines = append(cleanedLines, line) |
| 205 | + } |
| 206 | + return []byte(strings.Join(cleanedLines, "\n")) |
| 207 | +} |
| 208 | +func parseEnvFile(envData []byte) (map[string]string, error) { |
| 209 | + envVars := make(map[string]string) |
| 210 | + scanner := bufio.NewScanner(bytes.NewReader(envData)) |
| 211 | + for scanner.Scan() { |
| 212 | + line := scanner.Text() |
| 213 | + if strings.TrimSpace(line) == "" || strings.HasPrefix(line, "#") { |
| 214 | + continue // Skip empty lines and comments |
| 215 | + } |
| 216 | + parts := strings.SplitN(line, "=", 2) |
| 217 | + if len(parts) != 2 { |
| 218 | + return nil, fmt.Errorf("invalid environment variable: %s", line) |
| 219 | + } |
| 220 | + envVars[parts[0]] = parts[1] |
| 221 | + } |
| 222 | + return envVars, scanner.Err() |
| 223 | +} |
| 224 | + |
| 225 | +type ComposeService struct { |
| 226 | + Image string `yaml:"image"` |
| 227 | +} |
| 228 | + |
| 229 | +// ComposeFile represents the structure of docker-compose.yml |
| 230 | +type ComposeFile struct { |
| 231 | + Services map[string]ComposeService `yaml:"services"` |
| 232 | +} |
| 233 | + |
| 234 | +func PullSwarmMode( |
| 235 | + ctx context.Context, deployment api.DockerAgentDeployment, |
| 236 | +) (string, error) { |
| 237 | + |
| 238 | + // Parse the compose YAML file |
| 239 | + var compose ComposeFile |
| 240 | + err := yaml.Unmarshal(deployment.ComposeFile, &compose) |
| 241 | + if err != nil { |
| 242 | + return "", fmt.Errorf("failed to parse docker-compose.yml: %w", err) |
| 243 | + } |
| 244 | + |
| 245 | + // Extract image names |
| 246 | + var images []string |
| 247 | + for _, service := range compose.Services { |
| 248 | + if service.Image != "" { |
| 249 | + images = append(images, service.Image) |
| 250 | + } |
| 251 | + } |
| 252 | + |
| 253 | + if len(images) == 0 { |
| 254 | + return "", fmt.Errorf("no images found in the compose file") |
| 255 | + } |
| 256 | + |
| 257 | + // Pull images using Docker CLI |
| 258 | + var pullLogs bytes.Buffer |
| 259 | + for _, image := range images { |
| 260 | + fmt.Println("Pulling image:", image) |
| 261 | + logger.Info("Pulling image:", zap.String("id", image)) |
| 262 | + // Run `docker pull IMAGE_NAME` |
| 263 | + cmd := exec.CommandContext(ctx, "docker", "pull", image) |
| 264 | + var out bytes.Buffer |
| 265 | + cmd.Stdout = &out |
| 266 | + cmd.Stderr = &out |
| 267 | + |
| 268 | + err := cmd.Run() |
| 269 | + if err != nil { |
| 270 | + logger.Error("failed to pull image", zap.Error(err)) |
| 271 | + return "", fmt.Errorf("failed to pull image %s: %w\nOutput: %s", image, err, out.String()) |
| 272 | + } |
| 273 | + |
| 274 | + // Append logs |
| 275 | + pullLogs.WriteString(out.String() + "\n") |
| 276 | + fmt.Println(out.String()) |
| 277 | + } |
| 278 | + |
| 279 | + fmt.Println("Image pulling complete.") |
| 280 | + return pullLogs.String(), nil |
| 281 | +} |
0 commit comments