feat: 初始化跨平台远程编译服务与 Android Studio 插件
This commit is contained in:
commit
9eba4556db
44 files changed
+2802
No files matched your search
@@ -0,0 +1,3 @@
|
||||
module remotecompile
|
||||
|
||||
go 1.24.0
|
||||
+595
@@ -0,0 +1,595 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type File struct {
|
||||
Hash string `json:"hash"`
|
||||
Data *string `json:"data,omitempty"`
|
||||
}
|
||||
type SyncRequest struct {
|
||||
Revision string `json:"revision"`
|
||||
Files map[string]File `json:"files"`
|
||||
}
|
||||
type Artifact struct {
|
||||
Name string `json:"name"`
|
||||
Hash string `json:"hash"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
type Build struct {
|
||||
ID string `json:"id"`
|
||||
Project string `json:"project"`
|
||||
Revision string `json:"revision"`
|
||||
Task string `json:"task"`
|
||||
Status string `json:"status"`
|
||||
Logs []string `json:"logs"`
|
||||
Artifacts []Artifact `json:"artifacts"`
|
||||
cmd *exec.Cmd
|
||||
cancelled bool
|
||||
}
|
||||
type Project struct {
|
||||
Revision string `json:"revision"`
|
||||
Files map[string]File `json:"files"`
|
||||
Busy bool `json:"-"`
|
||||
}
|
||||
type Server struct {
|
||||
mu sync.Mutex
|
||||
root, token string
|
||||
tasks map[string]bool
|
||||
projects map[string]*Project
|
||||
builds map[string]*Build
|
||||
}
|
||||
|
||||
var safeID = regexp.MustCompile(`^[a-f0-9]{32}$`)
|
||||
var safeTask = regexp.MustCompile(`^:?[A-Za-z0-9_]+(:[A-Za-z0-9_]+)*$`)
|
||||
|
||||
func id() string {
|
||||
b := make([]byte, 16)
|
||||
if _, e := rand.Read(b); e != nil {
|
||||
panic(e)
|
||||
}
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
func digest(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) }
|
||||
func validPath(p string) bool {
|
||||
if p == "" || strings.ContainsAny(p, "\\:\x00<>\"|?*") || strings.HasPrefix(p, "/") {
|
||||
return false
|
||||
}
|
||||
for _, part := range strings.Split(p, "/") {
|
||||
if part == "" || part == "." || part == ".." || strings.TrimRight(part, ". ") != part {
|
||||
return false
|
||||
}
|
||||
base := strings.ToUpper(strings.Split(part, ".")[0])
|
||||
if regexp.MustCompile(`^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])$`).MatchString(base) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for _, part := range strings.Split(p, "/") {
|
||||
if part == ".git" || part == ".gradle" || part == "build" || part == ".idea" || part == "local.properties" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func noLinks(root string) error {
|
||||
return filepath.WalkDir(root, func(p string, d os.DirEntry, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if d.Type()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("symlink forbidden: %s", p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
func jsonOut(w http.ResponseWriter, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
func decode(w http.ResponseWriter, r *http.Request, v any) error {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 256<<20)
|
||||
d := json.NewDecoder(r.Body)
|
||||
d.DisallowUnknownFields()
|
||||
return d.Decode(v)
|
||||
}
|
||||
func (s *Server) work(p string) string { return filepath.Join(s.root, "projects", p, "work") }
|
||||
func (s *Server) save(p string) error {
|
||||
b, e := json.Marshal(s.projects[p])
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
path := filepath.Join(s.root, "projects", p, "state.json")
|
||||
if e = os.WriteFile(path+".tmp", b, 0600); e != nil {
|
||||
return e
|
||||
}
|
||||
return os.Rename(path+".tmp", path)
|
||||
}
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+s.token)) != 1 {
|
||||
http.Error(w, "unauthorized", 401)
|
||||
return
|
||||
}
|
||||
if r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/logs") {
|
||||
s.streamLogs(w, r)
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
fail := func(e error) { http.Error(w, e.Error(), 400) }
|
||||
if r.URL.Path == "/api/v1/health" {
|
||||
jsonOut(w, map[string]any{"version": "0.1.0", "os": runtime.GOOS, "sync": "http-manifest"})
|
||||
return
|
||||
}
|
||||
if len(parts) < 3 || parts[0] != "api" || parts[1] != "v1" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if parts[2] == "projects" {
|
||||
if len(parts) == 3 && r.Method == "POST" {
|
||||
p := id()
|
||||
if e := os.MkdirAll(s.work(p), 0700); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
s.projects[p] = &Project{Files: map[string]File{}}
|
||||
if e := s.save(p); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
jsonOut(w, map[string]string{"id": p})
|
||||
return
|
||||
}
|
||||
if len(parts) != 5 || !safeID.MatchString(parts[3]) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
p := parts[3]
|
||||
pr := s.projects[p]
|
||||
if pr == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if parts[4] == "manifest" && r.Method == "GET" {
|
||||
jsonOut(w, pr)
|
||||
return
|
||||
}
|
||||
if parts[4] == "sync" && r.Method == "POST" {
|
||||
if pr.Busy {
|
||||
http.Error(w, "workspace busy", 409)
|
||||
return
|
||||
}
|
||||
var req SyncRequest
|
||||
if e := decode(w, r, &req); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
if req.Revision == "" || req.Files == nil {
|
||||
fail(errors.New("revision and files required"))
|
||||
return
|
||||
}
|
||||
if e := noLinks(s.work(p)); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
staged := map[string][]byte{}
|
||||
seen := map[string]bool{}
|
||||
components := map[string]string{}
|
||||
for path, f := range req.Files {
|
||||
key := strings.ToLower(path)
|
||||
if !validPath(path) || seen[key] {
|
||||
fail(fmt.Errorf("invalid or colliding path: %s", path))
|
||||
return
|
||||
}
|
||||
seen[key] = true
|
||||
segments := strings.Split(path, "/")
|
||||
for i := range segments {
|
||||
prefix := strings.Join(segments[:i+1], "/")
|
||||
lower := strings.ToLower(prefix)
|
||||
if previous, ok := components[lower]; ok && previous != prefix {
|
||||
fail(fmt.Errorf("inconsistent path casing: %s", path))
|
||||
return
|
||||
}
|
||||
components[lower] = prefix
|
||||
}
|
||||
if f.Data != nil {
|
||||
b, e := base64.StdEncoding.DecodeString(*f.Data)
|
||||
if e != nil || digest(b) != f.Hash {
|
||||
fail(fmt.Errorf("hash mismatch: %s", path))
|
||||
return
|
||||
}
|
||||
staged[path] = b
|
||||
} else {
|
||||
b, e := os.ReadFile(filepath.Join(s.work(p), filepath.FromSlash(path)))
|
||||
if e != nil || digest(b) != f.Hash {
|
||||
fail(fmt.Errorf("missing content: %s", path))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
for path := range req.Files {
|
||||
segments := strings.Split(path, "/")
|
||||
for i := 1; i < len(segments); i++ {
|
||||
if seen[strings.ToLower(strings.Join(segments[:i], "/"))] {
|
||||
fail(fmt.Errorf("file/directory collision: %s", path))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
// Validate the entire request before touching the working tree. Invalidate first:
|
||||
// an interrupted commit must never permit building a mixed source revision.
|
||||
pr.Revision = ""
|
||||
if e := s.save(p); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
for path := range pr.Files {
|
||||
if _, ok := req.Files[path]; !ok {
|
||||
if e := os.Remove(filepath.Join(s.work(p), filepath.FromSlash(path))); e != nil && !os.IsNotExist(e) {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
for path, b := range staged {
|
||||
dest := filepath.Join(s.work(p), filepath.FromSlash(path))
|
||||
if e := os.MkdirAll(filepath.Dir(dest), 0700); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
if e := os.WriteFile(dest, b, 0600); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
}
|
||||
pr.Files = map[string]File{}
|
||||
for path, f := range req.Files {
|
||||
pr.Files[path] = File{Hash: f.Hash}
|
||||
}
|
||||
pr.Revision = req.Revision
|
||||
if e := s.save(p); e != nil {
|
||||
pr.Revision = ""
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
jsonOut(w, pr)
|
||||
return
|
||||
}
|
||||
if parts[4] == "builds" && r.Method == "POST" {
|
||||
var req struct {
|
||||
Revision string `json:"revision"`
|
||||
Task string `json:"task"`
|
||||
}
|
||||
if e := decode(w, r, &req); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
if !s.tasks[req.Task] || !safeTask.MatchString(req.Task) {
|
||||
fail(errors.New("task not allowed"))
|
||||
return
|
||||
}
|
||||
if pr.Busy || req.Revision == "" || pr.Revision != req.Revision {
|
||||
http.Error(w, "busy or revision mismatch", 409)
|
||||
return
|
||||
}
|
||||
b := &Build{ID: id(), Project: p, Revision: req.Revision, Task: req.Task, Status: "queued", Logs: []string{}, Artifacts: []Artifact{}}
|
||||
if e := os.WriteFile(filepath.Join(s.root, "projects", p, "active-build"), []byte(b.ID), 0600); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
s.builds[b.ID] = b
|
||||
pr.Busy = true
|
||||
go s.run(b)
|
||||
jsonOut(w, b)
|
||||
return
|
||||
}
|
||||
}
|
||||
if parts[2] == "builds" && len(parts) >= 4 {
|
||||
b := s.builds[parts[3]]
|
||||
if b == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if len(parts) == 4 && r.Method == "GET" {
|
||||
jsonOut(w, b)
|
||||
return
|
||||
}
|
||||
if len(parts) == 4 && r.Method == "DELETE" {
|
||||
if b.Status == "queued" || b.Status == "running" {
|
||||
b.cancelled = true
|
||||
if b.cmd != nil && b.cmd.Process != nil {
|
||||
killTree(b.cmd)
|
||||
}
|
||||
}
|
||||
jsonOut(w, b)
|
||||
return
|
||||
}
|
||||
if len(parts) == 6 && parts[4] == "artifacts" && r.Method == "GET" {
|
||||
for _, a := range b.Artifacts {
|
||||
if a.Name == parts[5] {
|
||||
s.mu.Unlock()
|
||||
http.ServeFile(w, r, filepath.Join(s.root, "artifacts", b.ID, a.Name))
|
||||
s.mu.Lock()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
func (s *Server) streamLogs(w http.ResponseWriter, r *http.Request) {
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
if len(parts) != 5 || parts[0] != "api" || parts[1] != "v1" || parts[2] != "builds" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
offset, _ := strconv.Atoi(r.Header.Get("Last-Event-ID"))
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
s.mu.Lock()
|
||||
b := s.builds[parts[3]]
|
||||
s.mu.Unlock()
|
||||
if b == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
ticker := time.NewTicker(400 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
s.mu.Lock()
|
||||
lines := append([]string{}, b.Logs...)
|
||||
terminal := b.Status != "queued" && b.Status != "running"
|
||||
s.mu.Unlock()
|
||||
for offset < len(lines) {
|
||||
if _, e := fmt.Fprintf(w, "id: %d\ndata: %s\n\n", offset+1, mustJSON(lines[offset])); e != nil {
|
||||
return
|
||||
}
|
||||
offset++
|
||||
}
|
||||
if f, ok := w.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
if terminal {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
func isOutputAPK(work, p string) bool {
|
||||
rel, e := filepath.Rel(work, p)
|
||||
if e != nil {
|
||||
return false
|
||||
}
|
||||
return strings.Contains("/"+filepath.ToSlash(rel), "/build/outputs/") && strings.HasSuffix(strings.ToLower(p), ".apk")
|
||||
}
|
||||
func mustJSON(v any) string { b, _ := json.Marshal(v); return string(b) }
|
||||
|
||||
type buildWriter struct {
|
||||
s *Server
|
||||
b *Build
|
||||
}
|
||||
|
||||
func (w buildWriter) Write(p []byte) (int, error) {
|
||||
w.s.mu.Lock()
|
||||
defer w.s.mu.Unlock()
|
||||
w.b.Logs = append(w.b.Logs, string(p))
|
||||
return len(p), nil
|
||||
}
|
||||
func (s *Server) run(b *Build) {
|
||||
s.mu.Lock()
|
||||
if b.cancelled {
|
||||
b.Status = "cancelled"
|
||||
s.projects[b.Project].Busy = false
|
||||
os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build"))
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
b.Status = "running"
|
||||
s.mu.Unlock()
|
||||
work := s.work(b.Project)
|
||||
// Remove old APKs only. Retain compilation caches and all other Gradle outputs.
|
||||
err := noLinks(work)
|
||||
if err == nil {
|
||||
err = filepath.WalkDir(work, func(p string, d os.DirEntry, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if !d.IsDir() && isOutputAPK(work, p) {
|
||||
return os.Remove(p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
if err == nil {
|
||||
cmd := gradleCommand(work, b.Task)
|
||||
cmd.Dir = work
|
||||
cmd.Stdout = buildWriter{s, b}
|
||||
cmd.Stderr = cmd.Stdout
|
||||
s.mu.Lock()
|
||||
b.cmd = cmd
|
||||
if b.cancelled {
|
||||
err = errors.New("cancelled")
|
||||
} else {
|
||||
err = cmd.Start()
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if err == nil {
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cmd.Wait() }()
|
||||
select {
|
||||
case err = <-done:
|
||||
case <-time.After(30 * time.Minute):
|
||||
killTree(cmd)
|
||||
err = <-done
|
||||
if err == nil {
|
||||
err = errors.New("build timeout")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
artifacts := []Artifact{}
|
||||
if err == nil {
|
||||
err = filepath.WalkDir(work, func(p string, d os.DirEntry, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if d.IsDir() || !isOutputAPK(work, p) {
|
||||
return nil
|
||||
}
|
||||
data, e := os.ReadFile(p)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
name := fmt.Sprintf("%d-%s", len(artifacts), filepath.Base(p))
|
||||
dest := filepath.Join(s.root, "artifacts", b.ID)
|
||||
if e = os.MkdirAll(dest, 0700); e != nil {
|
||||
return e
|
||||
}
|
||||
if e = os.WriteFile(filepath.Join(dest, name), data, 0600); e != nil {
|
||||
return e
|
||||
}
|
||||
artifacts = append(artifacts, Artifact{name, digest(data), int64(len(data))})
|
||||
return nil
|
||||
})
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
b.cmd = nil
|
||||
b.Artifacts = artifacts
|
||||
b.Status = "success"
|
||||
if len(artifacts) == 0 && err == nil {
|
||||
err = errors.New("no APK produced")
|
||||
}
|
||||
if err != nil {
|
||||
b.Status = "failed"
|
||||
b.Logs = append(b.Logs, err.Error())
|
||||
}
|
||||
if b.cancelled {
|
||||
b.Status = "cancelled"
|
||||
}
|
||||
s.projects[b.Project].Busy = false
|
||||
dir := filepath.Join(s.root, "artifacts", b.ID)
|
||||
os.MkdirAll(dir, 0700)
|
||||
data, _ := json.MarshalIndent(b, "", " ")
|
||||
os.WriteFile(filepath.Join(dir, "build.json"), data, 0600)
|
||||
os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build"))
|
||||
}
|
||||
func main() {
|
||||
addr := flag.String("listen", "127.0.0.1:8765", "HTTP bind address; use HTTPS proxy or SSH tunnel remotely")
|
||||
root := flag.String("data", "./data", "service data directory")
|
||||
tasks := flag.String("tasks", ":app:assembleDebug", "comma separated allowed Gradle tasks")
|
||||
flag.Parse()
|
||||
token := os.Getenv("REMOTE_BUILD_TOKEN")
|
||||
if len(token) < 24 {
|
||||
log.Fatal("REMOTE_BUILD_TOKEN must contain at least 24 characters")
|
||||
}
|
||||
abs, e := filepath.Abs(*root)
|
||||
if e != nil {
|
||||
log.Fatal(e)
|
||||
}
|
||||
s := &Server{root: abs, token: token, tasks: map[string]bool{}, projects: map[string]*Project{}, builds: map[string]*Build{}}
|
||||
for _, t := range strings.Split(*tasks, ",") {
|
||||
if !safeTask.MatchString(t) {
|
||||
log.Fatal("invalid task")
|
||||
}
|
||||
s.tasks[t] = true
|
||||
}
|
||||
entries, _ := os.ReadDir(filepath.Join(abs, "projects"))
|
||||
for _, entry := range entries {
|
||||
if !safeID.MatchString(entry.Name()) {
|
||||
continue
|
||||
}
|
||||
if _, e := os.Stat(filepath.Join(abs, "projects", entry.Name(), "active-build")); e == nil {
|
||||
log.Fatalf("unfinished build in project %s: stop its remaining Gradle processes, then remove active-build marker before restarting", entry.Name())
|
||||
}
|
||||
data, e := os.ReadFile(filepath.Join(abs, "projects", entry.Name(), "state.json"))
|
||||
if e != nil {
|
||||
continue
|
||||
}
|
||||
var p Project
|
||||
if json.Unmarshal(data, &p) == nil {
|
||||
s.projects[entry.Name()] = &p
|
||||
}
|
||||
}
|
||||
entries, _ = os.ReadDir(filepath.Join(abs, "artifacts"))
|
||||
for _, entry := range entries {
|
||||
data, e := os.ReadFile(filepath.Join(abs, "artifacts", entry.Name(), "build.json"))
|
||||
if e != nil {
|
||||
continue
|
||||
}
|
||||
var b Build
|
||||
if json.Unmarshal(data, &b) == nil {
|
||||
s.builds[b.ID] = &b
|
||||
}
|
||||
}
|
||||
log.Printf("remotecompile listening on %s (%s)", *addr, runtime.GOOS)
|
||||
srv := &http.Server{Addr: *addr, Handler: s, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 5 * time.Minute, IdleTimeout: 60 * time.Second}
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
|
||||
go func() {
|
||||
<-stop
|
||||
s.mu.Lock()
|
||||
for _, b := range s.builds {
|
||||
if b.Status == "running" || b.Status == "queued" {
|
||||
b.cancelled = true
|
||||
if b.cmd != nil {
|
||||
killTree(b.cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
srv.Shutdown(ctx)
|
||||
}()
|
||||
if e := srv.ListenAndServe(); e != nil && e != http.ErrServerClosed {
|
||||
log.Fatal(e)
|
||||
}
|
||||
// Let workers persist terminal state and clear their active markers.
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
s.mu.Lock()
|
||||
busy := false
|
||||
for _, p := range s.projects {
|
||||
busy = busy || p.Busy
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if !busy {
|
||||
return
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
var _ io.Writer = buildWriter{}
|
||||
@@ -0,0 +1,188 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func testServer(t *testing.T) *Server {
|
||||
t.Helper()
|
||||
return &Server{root: t.TempDir(), token: "test-token-abcdefghijklmnopqrstuvwxyz", tasks: map[string]bool{":app:assembleDebug": true}, projects: map[string]*Project{}, builds: map[string]*Build{}}
|
||||
}
|
||||
|
||||
func TestRunningCancellation(t *testing.T) {
|
||||
s := testServer(t)
|
||||
p := project(t, s)
|
||||
name, wrapper := "gradlew", "#!/bin/sh\nsleep 20\n"
|
||||
if runtime.GOOS == "windows" {
|
||||
name = "gradlew.bat"
|
||||
wrapper = "@echo off\r\nping 127.0.0.1 -n 20 >nul\r\n"
|
||||
}
|
||||
os.WriteFile(filepath.Join(s.work(p), name), []byte(wrapper), 0600)
|
||||
b := &Build{ID: id(), Project: p, Revision: "r", Task: ":app:assembleDebug", Status: "queued", Logs: []string{}}
|
||||
s.builds[b.ID] = b
|
||||
s.projects[p].Busy = true
|
||||
done := make(chan struct{})
|
||||
go func() { s.run(b); close(done) }()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
s.mu.Lock()
|
||||
started := b.cmd != nil && b.cmd.Process != nil
|
||||
s.mu.Unlock()
|
||||
if started {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("executor failed to start")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if w := call(t, s, "DELETE", "/builds/"+b.ID, nil); w.Code != 200 {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("cancel did not stop process tree")
|
||||
}
|
||||
if b.Status != "cancelled" || s.projects[p].Busy {
|
||||
t.Fatal("incorrect cancellation state")
|
||||
}
|
||||
}
|
||||
func TestSSEReplay(t *testing.T) {
|
||||
s := testServer(t)
|
||||
b := &Build{ID: id(), Status: "success", Logs: []string{"first", "second"}}
|
||||
s.builds[b.ID] = b
|
||||
r := httptest.NewRequest("GET", "/api/v1/builds/"+b.ID+"/logs", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+s.token)
|
||||
r.Header.Set("Last-Event-ID", "1")
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeHTTP(w, r)
|
||||
if strings.Contains(w.Body.String(), "first") || !strings.Contains(w.Body.String(), "second") {
|
||||
t.Fatal("SSE replay offset ignored")
|
||||
}
|
||||
}
|
||||
func call(t *testing.T, s *Server, method, path string, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
b, _ := json.Marshal(body)
|
||||
r := httptest.NewRequest(method, "/api/v1"+path, bytes.NewReader(b))
|
||||
r.Header.Set("Authorization", "Bearer "+s.token)
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
func project(t *testing.T, s *Server) string {
|
||||
w := call(t, s, "POST", "/projects", nil)
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
var v map[string]string
|
||||
json.Unmarshal(w.Body.Bytes(), &v)
|
||||
return v["id"]
|
||||
}
|
||||
func file(data string) File {
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte(data))
|
||||
return File{Hash: digest([]byte(data)), Data: &encoded}
|
||||
}
|
||||
func TestPaths(t *testing.T) {
|
||||
for _, p := range []string{"../x", "/x", "C:/x", "a\\b", "a/../x", "a//b", "CON.txt", "a./x", ".git/config", "app/build/x"} {
|
||||
if validPath(p) {
|
||||
t.Errorf("accepted %q", p)
|
||||
}
|
||||
}
|
||||
if !validPath("app/src/中文 a.kt") {
|
||||
t.Fatal("valid unicode path rejected")
|
||||
}
|
||||
}
|
||||
func TestAuthentication(t *testing.T) {
|
||||
s := testServer(t)
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/health", nil))
|
||||
if w.Code != 401 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
}
|
||||
func TestSyncAndRevision(t *testing.T) {
|
||||
s := testServer(t)
|
||||
p := project(t, s)
|
||||
path := "/projects/" + p + "/sync"
|
||||
req := SyncRequest{"one", map[string]File{"a.txt": file("hello"), "b.txt": file("remove me")}}
|
||||
if w := call(t, s, "POST", path, req); w.Code != 200 {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
bad := SyncRequest{"bad", map[string]File{"a.txt": {Hash: "wrong"}}}
|
||||
if w := call(t, s, "POST", path, bad); w.Code != 400 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
if s.projects[p].Revision != "one" {
|
||||
t.Fatal("invalid sync changed revision")
|
||||
}
|
||||
req = SyncRequest{"two", map[string]File{"a.txt": {Hash: digest([]byte("hello"))}}}
|
||||
if w := call(t, s, "POST", path, req); w.Code != 200 {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
if _, e := os.Stat(filepath.Join(s.work(p), "b.txt")); !os.IsNotExist(e) {
|
||||
t.Fatal("deleted source retained")
|
||||
}
|
||||
s.projects[p].Busy = true
|
||||
if w := call(t, s, "POST", path, req); w.Code != 409 {
|
||||
t.Fatal("sync allowed while building")
|
||||
}
|
||||
s.projects[p].Busy = false
|
||||
if w := call(t, s, "POST", "/projects/"+p+"/builds", map[string]string{"revision": "one", "task": ":app:assembleDebug"}); w.Code != 409 {
|
||||
t.Fatal("stale revision accepted")
|
||||
}
|
||||
if w := call(t, s, "POST", "/projects/"+p+"/builds", map[string]string{"revision": "two", "task": "evil & command"}); w.Code != 400 {
|
||||
t.Fatal("unapproved command accepted")
|
||||
}
|
||||
}
|
||||
func TestBuildArtifactAndFailure(t *testing.T) {
|
||||
s := testServer(t)
|
||||
p := project(t, s)
|
||||
wrapper := "#!/bin/sh\nmkdir -p app/build/outputs/apk/debug\nprintf fresh > app/build/outputs/apk/debug/app-debug.apk\n"
|
||||
name := "gradlew"
|
||||
if runtime.GOOS == "windows" {
|
||||
name = "gradlew.bat"
|
||||
wrapper = "@echo off\r\nmkdir app\\build\\outputs\\apk\\debug 2>nul\r\necho fresh>app\\build\\outputs\\apk\\debug\\app-debug.apk\r\nexit /b 0\r\n"
|
||||
}
|
||||
req := SyncRequest{"one", map[string]File{name: file(wrapper)}}
|
||||
if w := call(t, s, "POST", "/projects/"+p+"/sync", req); w.Code != 200 {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
b := &Build{ID: id(), Project: p, Revision: "one", Task: ":app:assembleDebug", Status: "queued"}
|
||||
s.builds[b.ID] = b
|
||||
s.projects[p].Busy = true
|
||||
s.run(b)
|
||||
if b.Status != "success" || len(b.Artifacts) != 1 {
|
||||
t.Fatalf("%s %v", b.Status, b.Logs)
|
||||
}
|
||||
a := b.Artifacts[0]
|
||||
w := call(t, s, "GET", "/builds/"+b.ID+"/artifacts/"+a.Name, nil)
|
||||
if w.Code != 200 || digest(w.Body.Bytes()) != a.Hash {
|
||||
t.Fatal("artifact mismatch")
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
wrapper = "@exit /b 1\r\n"
|
||||
} else {
|
||||
wrapper = "#!/bin/sh\nexit 1\n"
|
||||
}
|
||||
os.WriteFile(filepath.Join(s.work(p), name), []byte(wrapper), 0600)
|
||||
failed := &Build{ID: id(), Project: p, Revision: "one", Task: ":app:assembleDebug", Status: "queued"}
|
||||
s.run(failed)
|
||||
if failed.Status != "failed" || len(failed.Artifacts) != 0 {
|
||||
t.Fatal("failed build returned artifacts")
|
||||
}
|
||||
cancelled := &Build{ID: id(), Project: p, Status: "queued", cancelled: true}
|
||||
s.run(cancelled)
|
||||
if cancelled.Status != "cancelled" || s.projects[p].Busy {
|
||||
t.Fatal("queued cancellation failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func gradleCommand(work, task string) *exec.Cmd {
|
||||
c := exec.Command("sh", filepath.Join(work, "gradlew"), task, "--console=plain", "--no-daemon")
|
||||
c.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
return c
|
||||
}
|
||||
func killTree(c *exec.Cmd) {
|
||||
if c.Process != nil {
|
||||
_ = syscall.Kill(-c.Process.Pid, syscall.SIGKILL)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func gradleCommand(work, task string) *exec.Cmd {
|
||||
return exec.Command("cmd.exe", "/d", "/c", "gradlew.bat", task, "--console=plain", "--no-daemon")
|
||||
}
|
||||
func killTree(c *exec.Cmd) {
|
||||
if c.Process != nil {
|
||||
_ = exec.Command("taskkill.exe", "/PID", strconv.Itoa(c.Process.Pid), "/T", "/F").Run()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user