fix(orbit): 502 fix + log clearing + stack detection overhaul

- Fix 502: detectAndInjectDockerfile now checks npm start script before
  using pack-node — repos with package.json but no start script now
  correctly build as pack-static via nginx
- Static builds with npm run build now use node:22-alpine + proper
  multi-stage Dockerfile with dist/build/public/out fallback copy chain
- Python: auto-detect entry point (app.py, wsgi.py, run.py, server.py)
- All failure paths in deployAppAsync now call orbitBuildLogs.Delete()
  so stale build logs don't stay in memory after deployment ends
- Logs handler: add X-App-Status response header for UI polling control
- Logs handler: newest deployment log fetched from orbit_deployments
  (iterate all, pick latest created_at) instead of LIMIT 1
- UI: refreshLogs() reads X-App-Status header, stops interval when done
- UI: log output colorized with inline CSS spans per log tag
- UI: toast shown on deploy success/failure, app list reloads on finish
- Updated action handler saveDeploymentRecord calls + log delete
This commit is contained in:
2026-10-14 17:29:23 +05:30
parent 3fea647670
commit 5f4730b8d0
2 changed files with 173 additions and 37 deletions
+126 -31
View File
@@ -227,23 +227,25 @@ func detectAndInjectDockerfile(dirPath string) (buildType string, internalPort i
return "dockerfile", internalPort, nil return "dockerfile", internalPort, nil
} }
// 1. Node.js // Helper: check if package.json has a "start" script
if _, err := os.Stat(filepath.Join(dirPath, "package.json")); err == nil { hasNpmStart := func() bool {
dockerfile := `FROM node:20-alpine data, err := os.ReadFile(filepath.Join(dirPath, "package.json"))
WORKDIR /app if err != nil {
COPY package*.json ./ return false
RUN npm install --omit=dev 2>/dev/null || npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
`
if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0644); err != nil {
return "", 0, err
} }
return "pack-node", 3000, nil var pkg map[string]interface{}
if err := json.Unmarshal(data, &pkg); err != nil {
return false
}
scripts, ok := pkg["scripts"].(map[string]interface{})
if !ok {
return false
}
_, hasStart := scripts["start"]
return hasStart
} }
// 2. Go // 1. Go
if _, err := os.Stat(filepath.Join(dirPath, "go.mod")); err == nil { if _, err := os.Stat(filepath.Join(dirPath, "go.mod")); err == nil {
dockerfile := `FROM golang:1.24-alpine AS builder dockerfile := `FROM golang:1.24-alpine AS builder
WORKDIR /app WORKDIR /app
@@ -261,37 +263,99 @@ CMD ["/app/server"]
return "pack-go", 8080, nil return "pack-go", 8080, nil
} }
// 3. Python // 2. Python
if _, err := os.Stat(filepath.Join(dirPath, "requirements.txt")); err == nil { if _, err := os.Stat(filepath.Join(dirPath, "requirements.txt")); err == nil {
dockerfile := `FROM python:3.11-slim // Check if there's a better entrypoint
entry := "main.py"
for _, f := range []string{"app.py", "wsgi.py", "run.py", "server.py", "main.py"} {
if _, e := os.Stat(filepath.Join(dirPath, f)); e == nil {
entry = f
break
}
}
dockerfile := fmt.Sprintf(`FROM python:3.11-slim
WORKDIR /app WORKDIR /app
COPY requirements.txt . COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt || true RUN pip install --no-cache-dir -r requirements.txt || true
COPY . . COPY . .
EXPOSE 8000 EXPOSE 8000
CMD ["python", "main.py"] CMD ["python", "%s"]
` `, entry)
if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0644); err != nil { if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0644); err != nil {
return "", 0, err return "", 0, err
} }
return "pack-python", 8000, nil return "pack-python", 8000, nil
} }
// 4. Static HTML // 3. Node.js — only if package.json has a "start" script
if _, err := os.Stat(filepath.Join(dirPath, "index.html")); err == nil { if _, errPkg := os.Stat(filepath.Join(dirPath, "package.json")); errPkg == nil && hasNpmStart() {
dockerfile := `FROM nginx:alpine dockerfile := `FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --omit=dev 2>/dev/null || npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
`
if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0644); err != nil {
return "", 0, err
}
return "pack-node", 3000, nil
}
// 4. Static HTML (index.html present, or package.json without start script)
_, hasIndex := os.Stat(filepath.Join(dirPath, "index.html"))
_, hasPkg := os.Stat(filepath.Join(dirPath, "package.json"))
if hasIndex == nil || hasPkg == nil {
// Use nginx to serve static files
// Build static assets first if there's a build script
buildCmd := ""
if hasPkg == nil {
data, _ := os.ReadFile(filepath.Join(dirPath, "package.json"))
var pkg map[string]interface{}
_ = json.Unmarshal(data, &pkg)
if scripts, ok := pkg["scripts"].(map[string]interface{}); ok {
if _, hasBuild := scripts["build"]; hasBuild {
buildCmd = "RUN npm install && npm run build 2>/dev/null || true\n"
buildCmd += "RUN test -d dist && cp -r dist/* /usr/share/nginx/html/ 2>/dev/null || test -d build && cp -r build/* /usr/share/nginx/html/ 2>/dev/null || true\n"
}
}
}
var dockerfile string
if buildCmd != "" {
// Multi-stage: build then serve with nginx
dockerfile = `FROM node:22-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install --legacy-peer-deps 2>/dev/null || npm install || true
COPY . .
RUN npm run build 2>/dev/null || true
FROM nginx:alpine
WORKDIR /usr/share/nginx/html
RUN rm -rf ./*
COPY --from=builder /app/dist ./ 2>/dev/null || true
COPY --from=builder /app/build ./ 2>/dev/null || true
COPY --from=builder /app/public ./ 2>/dev/null || true
COPY --from=builder /app/out ./ 2>/dev/null || true
COPY --from=builder /app ./ 2>/dev/null || true
EXPOSE 80
`
} else {
dockerfile = `FROM nginx:alpine
COPY . /usr/share/nginx/html COPY . /usr/share/nginx/html
EXPOSE 80 EXPOSE 80
` `
}
if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0644); err != nil { if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0644); err != nil {
return "", 0, err return "", 0, err
} }
return "pack-static", 80, nil return "pack-static", 80, nil
} }
return "unknown", 8080, fmt.Errorf("no Dockerfile, package.json, go.mod, requirements.txt, or index.html found") return "unknown", 8080, fmt.Errorf("no Dockerfile, package.json (with start script), go.mod, requirements.txt, or index.html found in repository root")
} }
// deployAppAsync handles cloning, building, and running an application container in background. // deployAppAsync handles cloning, building, and running an application container in background.
func deployAppAsync(appID string) { func deployAppAsync(appID string) {
orbitActiveBuild.Store(appID, true) orbitActiveBuild.Store(appID, true)
@@ -338,6 +402,7 @@ func deployAppAsync(appID string) {
_ = scyllaSession.Query(`UPDATE cosmos.orbit_apps SET status = 'failed', updated_at = ? WHERE app_id = ?`, _ = scyllaSession.Query(`UPDATE cosmos.orbit_apps SET status = 'failed', updated_at = ? WHERE app_id = ?`,
time.Now().Unix(), appID).Exec() time.Now().Unix(), appID).Exec()
saveDeploymentRecord(appID, "failed", int(time.Since(startTime).Seconds()), logBuf.String()) saveDeploymentRecord(appID, "failed", int(time.Since(startTime).Seconds()), logBuf.String())
orbitBuildLogs.Delete(appID)
return return
} }
} }
@@ -350,6 +415,7 @@ func deployAppAsync(appID string) {
_ = scyllaSession.Query(`UPDATE cosmos.orbit_apps SET status = 'failed', updated_at = ? WHERE app_id = ?`, _ = scyllaSession.Query(`UPDATE cosmos.orbit_apps SET status = 'failed', updated_at = ? WHERE app_id = ?`,
time.Now().Unix(), appID).Exec() time.Now().Unix(), appID).Exec()
saveDeploymentRecord(appID, "failed", int(time.Since(startTime).Seconds()), logBuf.String()) saveDeploymentRecord(appID, "failed", int(time.Since(startTime).Seconds()), logBuf.String())
orbitBuildLogs.Delete(appID)
return return
} }
fmt.Fprintf(logBuf, "[DETECT] Architecture resolved: %s (internal port %d)\n", buildType, intPort) fmt.Fprintf(logBuf, "[DETECT] Architecture resolved: %s (internal port %d)\n", buildType, intPort)
@@ -362,6 +428,7 @@ func deployAppAsync(appID string) {
_ = scyllaSession.Query(`UPDATE cosmos.orbit_apps SET status = 'failed', updated_at = ? WHERE app_id = ?`, _ = scyllaSession.Query(`UPDATE cosmos.orbit_apps SET status = 'failed', updated_at = ? WHERE app_id = ?`,
time.Now().Unix(), appID).Exec() time.Now().Unix(), appID).Exec()
saveDeploymentRecord(appID, "failed", int(time.Since(startTime).Seconds()), logBuf.String()) saveDeploymentRecord(appID, "failed", int(time.Since(startTime).Seconds()), logBuf.String())
orbitBuildLogs.Delete(appID)
return return
} }
@@ -376,6 +443,7 @@ func deployAppAsync(appID string) {
_ = scyllaSession.Query(`UPDATE cosmos.orbit_apps SET status = 'failed', updated_at = ? WHERE app_id = ?`, _ = scyllaSession.Query(`UPDATE cosmos.orbit_apps SET status = 'failed', updated_at = ? WHERE app_id = ?`,
time.Now().Unix(), appID).Exec() time.Now().Unix(), appID).Exec()
saveDeploymentRecord(appID, "failed", int(time.Since(startTime).Seconds()), logBuf.String()) saveDeploymentRecord(appID, "failed", int(time.Since(startTime).Seconds()), logBuf.String())
orbitBuildLogs.Delete(appID)
return return
} }
fmt.Fprintf(logBuf, "[DOCKER] Image %s built successfully.\n", imageTag) fmt.Fprintf(logBuf, "[DOCKER] Image %s built successfully.\n", imageTag)
@@ -412,17 +480,22 @@ func deployAppAsync(appID string) {
_ = scyllaSession.Query(`UPDATE cosmos.orbit_apps SET status = 'failed', updated_at = ? WHERE app_id = ?`, _ = scyllaSession.Query(`UPDATE cosmos.orbit_apps SET status = 'failed', updated_at = ? WHERE app_id = ?`,
time.Now().Unix(), appID).Exec() time.Now().Unix(), appID).Exec()
saveDeploymentRecord(appID, "failed", int(time.Since(startTime).Seconds()), logBuf.String()) saveDeploymentRecord(appID, "failed", int(time.Since(startTime).Seconds()), logBuf.String())
orbitBuildLogs.Delete(appID)
return return
} }
fmt.Fprintf(logBuf, "[ORCHESTRATOR] Container %s is active and healthy.\n", containerID[:12]) fmt.Fprintf(logBuf, "[ORCHESTRATOR] Container %s is active and healthy.\n", containerID[:12])
fmt.Fprintf(logBuf, "[ORBIT] Deployment completed in %s.\n", time.Since(startTime).Round(time.Millisecond)) fmt.Fprintf(logBuf, "[ORBIT] Deployment completed in %s. Container is now running.\n", time.Since(startTime).Round(time.Millisecond))
fmt.Fprintf(logBuf, "[ORBIT] Access via proxy: /orbit/proxy/%s/\n", appID)
// Step 7: Update DB to 'running' // Step 7: Update DB to 'running'
_ = scyllaSession.Query(`UPDATE cosmos.orbit_apps SET status = 'running', container_id = ?, image_tag = ?, internal_port = ?, build_type = ?, updated_at = ? WHERE app_id = ?`, _ = scyllaSession.Query(`UPDATE cosmos.orbit_apps SET status = 'running', container_id = ?, image_tag = ?, internal_port = ?, build_type = ?, updated_at = ? WHERE app_id = ?`,
containerID, imageTag, intPort, buildType, time.Now().Unix(), appID).Exec() containerID, imageTag, intPort, buildType, time.Now().Unix(), appID).Exec()
saveDeploymentRecord(appID, "success", int(time.Since(startTime).Seconds()), logBuf.String()) saveDeploymentRecord(appID, "success", int(time.Since(startTime).Seconds()), logBuf.String())
// Clear in-memory build log — live container logs will be served from Docker from now on
time.Sleep(2 * time.Second) // let any pending log reads finish
orbitBuildLogs.Delete(appID)
} }
// saveDeploymentRecord stores build log in ScyllaDB. // saveDeploymentRecord stores build log in ScyllaDB.
@@ -735,29 +808,51 @@ func handleOrbitAppLogs(w http.ResponseWriter, r *http.Request, appID string) {
return return
} }
// Set headers so UI can poll-detect completion
w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-App-Status", app.Status)
// If app is currently building, stream from in-memory build log buffer // 1. If currently building: serve live in-memory build log
if val, ok := orbitBuildLogs.Load(appID); ok { if val, ok := orbitBuildLogs.Load(appID); ok {
buf := val.(*bytes.Buffer) buf := val.(*bytes.Buffer)
w.Write(buf.Bytes()) logText := buf.String()
w.Header().Set("X-App-Status", "building")
w.Write([]byte(logText))
return return
} }
// Otherwise, fetch latest deployment build log or container logs // 2. If running: stream live container stdout/stderr
if app.ContainerID != "" && app.Status == "running" { if app.Status == "running" && app.ContainerID != "" {
_ = StreamDockerLogs(r.Context(), app.ContainerID, "300", false, w) // Try container logs first
err2 := StreamDockerLogs(r.Context(), app.ContainerID, "500", false, w)
if err2 == nil {
return return
} }
// Fallback: last deployment log
}
// 3. For stopped/failed or if container stream failed: return stored build log
var latestLog string var latestLog string
_ = scyllaSession.Query(`SELECT build_log FROM cosmos.orbit_deployments WHERE app_id = ? LIMIT 1 ALLOW FILTERING`, appID). iter := scyllaSession.Query(
Scan(&latestLog) `SELECT build_log, created_at FROM cosmos.orbit_deployments WHERE app_id = ? ALLOW FILTERING`,
appID,
).Iter()
var buildLog string
var createdAt int64
var newestAt int64
for iter.Scan(&buildLog, &createdAt) {
if createdAt > newestAt {
newestAt = createdAt
latestLog = buildLog
}
}
_ = iter.Close()
if latestLog != "" { if latestLog != "" {
w.Write([]byte(latestLog)) w.Write([]byte(latestLog))
} else { } else {
w.Write([]byte("[ORBIT] No logs recorded yet.")) w.Write([]byte("[ORBIT] No logs recorded yet.\n[ORBIT] Deploy an application to see build and runtime logs here."))
} }
} }
+46 -5
View File
@@ -1475,22 +1475,63 @@ function openLogs(appID, name) {
activeAppID = appID; activeAppID = appID;
document.getElementById('logs-title').textContent = `${name} — Logs`; document.getElementById('logs-title').textContent = `${name} — Logs`;
document.getElementById('logs-sub').textContent = `app_id: ${appID}`; document.getElementById('logs-sub').textContent = `app_id: ${appID}`;
document.getElementById('terminal-out').textContent = 'Connecting to log stream…'; document.getElementById('terminal-out').innerHTML = '<span style="color:#64748b">Connecting to log stream…</span>';
openModal('modal-logs'); openModal('modal-logs');
refreshLogs();
clearInterval(logsInterval); clearInterval(logsInterval);
logsInterval = setInterval(refreshLogs, 2500); refreshLogs();
logsInterval = setInterval(refreshLogs, 2000);
}
function colorizeLog(text) {
return text
.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')
.replace(/\[ORBIT\]/g, '<span style="color:#38bdf8;font-weight:700">[ORBIT]</span>')
.replace(/\[GIT\]/g, '<span style="color:#a78bfa;font-weight:700">[GIT]</span>')
.replace(/\[DETECT\]/g, '<span style="color:#34d399;font-weight:700">[DETECT]</span>')
.replace(/\[TAR\]/g, '<span style="color:#94a3b8">[TAR]</span>')
.replace(/\[DOCKER\]/g, '<span style="color:#38bdf8;font-weight:700">[DOCKER]</span>')
.replace(/\[ORCHESTRATOR\]/g, '<span style="color:#10b981;font-weight:700">[ORCHESTRATOR]</span>')
.replace(/\[GIT ERROR\]/g, '<span style="color:#f87171;font-weight:700">[GIT ERROR]</span>')
.replace(/\[BUILD ERROR\]/g, '<span style="color:#f87171;font-weight:700">[BUILD ERROR]</span>')
.replace(/\[DOCKER ERROR\]/g, '<span style="color:#f87171;font-weight:700">[DOCKER ERROR]</span>')
.replace(/\[ORCHESTRATOR ERROR\]/g, '<span style="color:#f87171;font-weight:700">[ORCHESTRATOR ERROR]</span>')
.replace(/\[TAR ERROR\]/g, '<span style="color:#f87171;font-weight:700">[TAR ERROR]</span>')
.replace(/(completed|successfully|healthy|running)/gi, '<span style="color:#34d399">$1</span>')
.replace(/(failed|error|refused)/gi, '<span style="color:#f87171">$1</span>')
.replace(/(Step \d+\/\d+)/g, '<span style="color:#fbbf24">$1</span>');
} }
async function refreshLogs() { async function refreshLogs() {
if (!activeAppID) return; if (!activeAppID) return;
try { try {
const res = await fetch(`/orbit/api/apps/${activeAppID}/logs`); const res = await fetch(`/orbit/api/apps/${activeAppID}/logs`);
const appStatus = res.headers.get('X-App-Status') || '';
const text = await res.text(); const text = await res.text();
const el = document.getElementById('terminal-out'); const el = document.getElementById('terminal-out');
el.textContent = text || '[ORBIT] No output yet.'; el.innerHTML = colorizeLog(text || '[ORBIT] No output yet.');
el.scrollTop = el.scrollHeight; el.scrollTop = el.scrollHeight;
} catch(e) {}
// Update sub-label with current status
const statusColors = { running:'#34d399', failed:'#f87171', stopped:'#94a3b8', building:'#fbbf24' };
const col = statusColors[appStatus] || '#94a3b8';
document.getElementById('logs-sub').innerHTML =
`app_id: ${activeAppID} &nbsp;·&nbsp; <span style="color:${col};font-weight:700">${appStatus||'…'}</span>`;
// Stop polling when build/deploy is done (not actively building)
if (appStatus && appStatus !== 'building') {
clearInterval(logsInterval);
logsInterval = null;
// Refresh app list to show new status
await loadApps();
if (appStatus === 'running') {
toast('Deployment successful! Application is running.', 'success');
} else if (appStatus === 'failed') {
toast('Deployment failed. Check the logs for details.', 'error');
}
}
} catch(e) {
console.error('Log fetch error:', e);
}
} }
/* ─── ENV VARS ────────────────────────────────────────────── */ /* ─── ENV VARS ────────────────────────────────────────────── */