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
|
package api
import (
"bytes"
"context"
"net/http"
"os/exec"
"path/filepath"
"time"
)
const scriptTimeout = 30 * time.Second
func (s *Server) startNextTaskScriptPath() string {
if s.startNextTaskScript != "" {
return s.startNextTaskScript
}
return filepath.Join(s.workDir, "scripts", "start-next-task")
}
func (s *Server) deployScriptPath() string {
if s.deployScript != "" {
return s.deployScript
}
return filepath.Join(s.workDir, "scripts", "deploy")
}
func (s *Server) handleStartNextTask(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), scriptTimeout)
defer cancel()
scriptPath := s.startNextTaskScriptPath()
cmd := exec.CommandContext(ctx, scriptPath)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
exitCode := 0
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode = exitErr.ExitCode()
} else {
s.logger.Error("start-next-task: script execution failed", "error", err, "path", scriptPath)
writeJSON(w, http.StatusInternalServerError, map[string]string{
"error": "script execution failed: " + err.Error(),
})
return
}
}
writeJSON(w, http.StatusOK, map[string]interface{}{
"output": stdout.String(),
"exit_code": exitCode,
})
}
func (s *Server) handleDeploy(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), scriptTimeout)
defer cancel()
scriptPath := s.deployScriptPath()
cmd := exec.CommandContext(ctx, scriptPath)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
exitCode := 0
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode = exitErr.ExitCode()
} else {
s.logger.Error("deploy: script execution failed", "error", err, "path", scriptPath)
writeJSON(w, http.StatusInternalServerError, map[string]string{
"error": "script execution failed: " + err.Error(),
})
return
}
}
writeJSON(w, http.StatusOK, map[string]interface{}{
"output": stdout.String() + stderr.String(),
"exit_code": exitCode,
})
}
|