-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdeploy_errors.go
More file actions
304 lines (271 loc) · 8.34 KB
/
Copy pathdeploy_errors.go
File metadata and controls
304 lines (271 loc) · 8.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package cmd
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
)
// DeployErrorClass represents a known failure class during deployment.
type DeployErrorClass string
const (
ErrorClassDockerPortConflict DeployErrorClass = "docker_port_conflict"
ErrorClassDockerBindFailed DeployErrorClass = "docker_bind_failed"
ErrorClassAzureAuth DeployErrorClass = "azure_auth"
ErrorClassAzureMySQLStopped DeployErrorClass = "azure_mysql_stopped"
ErrorClassAzureKeyVault DeployErrorClass = "azure_keyvault_softdelete"
ErrorClassUnknown DeployErrorClass = "unknown"
)
// DeployError represents a classified deployment error with recovery context.
type DeployError struct {
Class DeployErrorClass
OriginalErr error
Port string // For port conflict errors
Container string // For port conflict errors
ComposeFile string // For port conflict errors
Message string // Human-readable classification
}
// classifyDockerComposeError inspects a docker compose error and returns
// a classified error with recovery context. This covers:
// - "port is already allocated"
// - "Bind for 0.0.0.0:PORT"
// - "ports are not available" / "Ports are not available"
// - "address already in use"
// - "failed programming external connectivity"
func classifyDockerComposeError(err error) *DeployError {
if err == nil {
return nil
}
errStr := err.Error()
errStrLower := strings.ToLower(errStr)
// Port conflict patterns (case-insensitive)
portConflictPatterns := []string{
"port is already allocated",
"bind for",
"ports are not available",
"address already in use",
"failed programming external connectivity",
}
isPortConflict := false
for _, pattern := range portConflictPatterns {
if strings.Contains(errStrLower, pattern) {
isPortConflict = true
break
}
}
if !isPortConflict {
return &DeployError{
Class: ErrorClassUnknown,
OriginalErr: err,
Message: "Docker Compose failed",
}
}
// Extract port number from various error formats
port := extractPortFromError(errStr)
result := &DeployError{
Class: ErrorClassDockerPortConflict,
OriginalErr: err,
Port: port,
Message: "Docker port conflict detected",
}
// Try to identify owning container
if port != "" {
container, composeFile := findPortOwner(port)
result.Container = container
result.ComposeFile = composeFile
}
return result
}
// extractPortFromError extracts the port number from various Docker error formats:
// - "Bind for 0.0.0.0:8080: failed: port is already allocated"
// - "Error response from daemon: Ports are not available: exposing port TCP 0.0.0.0:8080"
// - "bind: address already in use (listening on [::]:8080)"
// - "failed programming external connectivity on endpoint devlake (8080/tcp)"
func extractPortFromError(errStr string) string {
// Pattern 1: "Bind for 0.0.0.0:PORT" (case-insensitive using regexp)
re := regexp.MustCompile(`(?i)bind for 0\.0\.0\.0:(\d+)`)
if matches := re.FindStringSubmatch(errStr); len(matches) > 1 {
port := matches[1]
if isValidPort(port) {
return port
}
}
// Pattern 2: "exposing port TCP 0.0.0.0:PORT"
if idx := strings.Index(errStr, "0.0.0.0:"); idx != -1 {
rest := errStr[idx+len("0.0.0.0:"):]
if end := strings.IndexAny(rest, " ->\n"); end > 0 {
port := rest[:end]
if isValidPort(port) {
return port
}
}
}
// Pattern 3: "listening on [::]:PORT" or "[::]PORT"
if idx := strings.Index(errStr, "[::]"); idx != -1 {
rest := errStr[idx+len("[::]"):]
// Skip potential colon separator
if strings.HasPrefix(rest, ":") {
rest = rest[1:]
}
if end := strings.IndexAny(rest, " )\n"); end > 0 {
port := rest[:end]
if isValidPort(port) {
return port
}
}
// If no delimiter found, but there are digits, use them
if len(rest) > 0 {
for i, ch := range rest {
if ch < '0' || ch > '9' {
if i > 0 {
port := rest[:i]
if isValidPort(port) {
return port
}
}
break
}
}
}
}
// Pattern 4: "(PORT/tcp)" or "(PORT/udp)" in endpoint errors
if idx := strings.Index(errStr, "("); idx != -1 {
rest := errStr[idx+1:]
if end := strings.Index(rest, "/tcp)"); end > 0 {
port := strings.TrimSpace(rest[:end])
if isValidPort(port) {
return port
}
}
if end := strings.Index(rest, "/udp)"); end > 0 {
port := strings.TrimSpace(rest[:end])
if isValidPort(port) {
return port
}
}
}
// Pattern 5: Generic port number extraction (last resort)
// Look for sequences like ":8080" or " 8080 " in the error
for _, candidate := range strings.Fields(errStr) {
// Try splitting by colons
if strings.Contains(candidate, ":") {
parts := strings.Split(candidate, ":")
for _, part := range parts {
part = strings.Trim(part, "(),[]")
if isValidPort(part) {
return part
}
}
}
// Try the field itself (for cases like "[::] 3002")
cleaned := strings.Trim(candidate, "(),[]")
if isValidPort(cleaned) {
return cleaned
}
}
return ""
}
// isValidPort checks if a string looks like a valid port number (all digits, 1-65535).
func isValidPort(s string) bool {
if len(s) < 1 || len(s) > 5 {
return false
}
for _, ch := range s {
if ch < '0' || ch > '9' {
return false
}
}
// Parse to int and validate range 1-65535
port := 0
for _, ch := range s {
port = port*10 + int(ch-'0')
}
return port >= 1 && port <= 65535
}
// findPortOwner queries Docker to find which container is using the specified port.
// Returns (containerName, composeFilePath).
func findPortOwner(port string) (string, string) {
out, err := exec.Command(
"docker",
"ps",
"--filter", "publish="+port,
"--format", "{{.Names}}\t{{.Label \"com.docker.compose.project.config_files\"}}\t{{.Label \"com.docker.compose.project.working_dir\"}}",
).Output()
if err != nil || len(strings.TrimSpace(string(out))) == 0 {
return "", ""
}
lines := strings.Split(strings.TrimSpace(string(out)), "\n")
parts := strings.SplitN(lines[0], "\t", 3)
containerName := parts[0]
configFiles := ""
workDir := ""
if len(parts) >= 2 {
configFiles = strings.TrimSpace(parts[1])
}
if len(parts) == 3 {
workDir = strings.TrimSpace(parts[2])
}
// Prefer the exact compose file path Docker recorded
if configFiles != "" {
configFile := strings.Split(configFiles, ";")[0]
configFile = strings.TrimSpace(configFile)
if configFile != "" {
if _, statErr := os.Stat(configFile); statErr == nil {
return containerName, configFile
}
}
}
// Fallback: assume docker-compose.yml under working_dir
if workDir != "" {
composePath := filepath.Join(workDir, "docker-compose.yml")
if _, statErr := os.Stat(composePath); statErr == nil {
return containerName, composePath
}
}
return containerName, ""
}
// printDockerPortConflictError prints a user-friendly error message for port conflicts
// with actionable remediation steps.
// If customHeader is provided, it replaces the default "Port conflict detected" header.
// If nextSteps is provided, it replaces the default "Then re-run: gh devlake deploy local" text.
func printDockerPortConflictError(de *DeployError, customHeader string, nextSteps string) {
// Print header
if customHeader != "" {
// Normalize header to ensure consistent spacing (blank line before emoji-prefixed steps)
normalizedHeader := customHeader
if !strings.HasPrefix(normalizedHeader, "\n") {
normalizedHeader = "\n" + normalizedHeader
}
fmt.Println(normalizedHeader)
} else {
if de.Port != "" {
fmt.Printf("\n❌ Port conflict detected: port %s is already in use.\n", de.Port)
} else {
fmt.Println("\n❌ Port conflict detected: a required port is already in use.")
}
}
// Print container info and stop commands
if de.Container != "" {
fmt.Printf(" Container holding the port: %s\n", de.Container)
if de.ComposeFile != "" {
fmt.Println(" Stop it with:")
fmt.Printf(" docker compose -f \"%s\" down\n", de.ComposeFile)
} else {
fmt.Println(" Stop it with:")
fmt.Printf(" docker stop %s\n", de.Container)
}
} else if de.Port != "" {
fmt.Println(" Find what's using it:")
fmt.Println(" docker ps --format \"table {{.Names}}\\t{{.Ports}}\"")
}
// Print next steps
if nextSteps != "" {
fmt.Println(nextSteps)
} else {
fmt.Println(" Then re-run:")
fmt.Println(" gh devlake deploy local")
}
fmt.Println("\n💡 To clean up partial artifacts:")
fmt.Println(" gh devlake cleanup --local --force")
}