blob: 4174ece38d2106ed7ae59cda1ac99b831baad6ea [file] [log] [blame]
gio0eaf2712024-04-14 13:08:46 +04001package main
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
gio183e8342024-08-20 06:01:24 +04007 "io"
gio0eaf2712024-04-14 13:08:46 +04008 "net/http"
9 "os"
10 "os/exec"
giofc441e32024-11-11 16:26:14 +040011 "path/filepath"
giobcd25e92025-05-03 19:14:10 +040012 "strings"
gio0eaf2712024-04-14 13:08:46 +040013 "sync"
gioff0ee0f2024-10-15 23:11:54 +040014 "syscall"
gio0eaf2712024-04-14 13:08:46 +040015 "time"
16
17 "golang.org/x/crypto/ssh"
18)
19
gio5155c1a2025-05-21 15:36:21 +040020type CommandState string
21
22type CommandStatus struct {
23 Command string `json:"command"`
24 State CommandState `json:"state"`
25}
26
27type Status struct {
gio9635ccb2025-05-22 08:33:38 +040028 Commit *Commit `json:"commit"`
gio5155c1a2025-05-21 15:36:21 +040029 Commands []CommandStatus `json:"commands"`
30}
31
gio0eaf2712024-04-14 13:08:46 +040032type Server struct {
33 l sync.Locker
34 port int
gio266c04f2024-07-03 14:18:45 +040035 appId string
giob87415c2025-05-08 22:32:11 +040036 service string
gio5155c1a2025-05-21 15:36:21 +040037 id string
gio0eaf2712024-04-14 13:08:46 +040038 ready bool
39 cmd *exec.Cmd
40 repoAddr string
gio2b1157a2024-10-24 08:45:07 +040041 branch string
giofc441e32024-11-11 16:26:14 +040042 rootDir string
gio0eaf2712024-04-14 13:08:46 +040043 signer ssh.Signer
44 appDir string
45 runCommands []Command
46 self string
gioa60f0de2024-07-08 10:49:48 +040047 managerAddr string
gio183e8342024-08-20 06:01:24 +040048 logs *Log
gio45c31822024-10-24 10:58:02 +040049 currDir string
gio5155c1a2025-05-21 15:36:21 +040050 status *Status
gio0eaf2712024-04-14 13:08:46 +040051}
52
gio5155c1a2025-05-21 15:36:21 +040053func NewServer(port int, appId, service, id, repoAddr, branch, rootDir string, signer ssh.Signer, appDir string, runCommands []Command, self string, manager string) *Server {
gio0eaf2712024-04-14 13:08:46 +040054 return &Server{
55 l: &sync.Mutex{},
56 port: port,
57 ready: false,
gio266c04f2024-07-03 14:18:45 +040058 appId: appId,
giob87415c2025-05-08 22:32:11 +040059 service: service,
gio5155c1a2025-05-21 15:36:21 +040060 id: id,
gio0eaf2712024-04-14 13:08:46 +040061 repoAddr: repoAddr,
gio2b1157a2024-10-24 08:45:07 +040062 branch: branch,
giofc441e32024-11-11 16:26:14 +040063 rootDir: rootDir,
gio0eaf2712024-04-14 13:08:46 +040064 signer: signer,
65 appDir: appDir,
66 runCommands: runCommands,
67 self: self,
gioa60f0de2024-07-08 10:49:48 +040068 managerAddr: manager,
gio183e8342024-08-20 06:01:24 +040069 logs: &Log{},
gio45c31822024-10-24 10:58:02 +040070 currDir: "",
gio5155c1a2025-05-21 15:36:21 +040071 status: nil,
gio0eaf2712024-04-14 13:08:46 +040072 }
73}
74
75func (s *Server) Start() error {
76 http.HandleFunc("/update", s.handleUpdate)
77 http.HandleFunc("/ready", s.handleReady)
gio183e8342024-08-20 06:01:24 +040078 http.HandleFunc("/logs", s.handleLogs)
gioec744fa2025-05-20 12:47:03 +040079 if s.managerAddr != "" && s.appId != "" {
80 go s.pingManager()
81 }
gio0eaf2712024-04-14 13:08:46 +040082 if err := s.run(); err != nil {
83 return err
84 }
gio0eaf2712024-04-14 13:08:46 +040085 return http.ListenAndServe(fmt.Sprintf(":%d", s.port), nil)
86}
87
gio183e8342024-08-20 06:01:24 +040088func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
89 fmt.Fprint(w, s.logs.Contents())
90}
91
gio0eaf2712024-04-14 13:08:46 +040092func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) {
93 s.l.Lock()
94 defer s.l.Unlock()
95 if s.ready {
96 fmt.Fprintln(w, "ok")
97 } else {
98 http.Error(w, "not ready", http.StatusInternalServerError)
99 }
100}
101
102func (s *Server) handleUpdate(w http.ResponseWriter, r *http.Request) {
103 fmt.Println("update")
104 s.l.Lock()
105 s.ready = false
106 s.l.Unlock()
gio0eaf2712024-04-14 13:08:46 +0400107 if err := s.run(); err != nil {
108 http.Error(w, err.Error(), http.StatusInternalServerError)
109 return
110 }
111 s.l.Lock()
112 s.ready = true
113 s.l.Unlock()
114}
115
116func (s *Server) run() error {
gio45c31822024-10-24 10:58:02 +0400117 newDir, err := os.MkdirTemp(s.appDir, "code-*")
118 if err != nil {
119 return err
120 }
gio5155c1a2025-05-21 15:36:21 +0400121 commit, err := CloneRepositoryBranch(s.repoAddr, s.branch, s.rootDir, s.signer, newDir)
122 if err != nil {
123 s.status = &Status{
gio9635ccb2025-05-22 08:33:38 +0400124 Commit: nil,
gio5155c1a2025-05-21 15:36:21 +0400125 }
gio0eaf2712024-04-14 13:08:46 +0400126 return err
127 }
gio5155c1a2025-05-21 15:36:21 +0400128 s.status = &Status{
gio5155c1a2025-05-21 15:36:21 +0400129 Commit: commit,
130 Commands: []CommandStatus{},
131 }
132 commands := []string{}
133 for _, c := range s.runCommands {
gio0eaf2712024-04-14 13:08:46 +0400134 args := []string{c.Bin}
135 args = append(args, c.Args...)
gio5155c1a2025-05-21 15:36:21 +0400136 cmd := strings.Join(args, " ")
137 commands = append(commands, cmd)
138 s.status.Commands = append(s.status.Commands, CommandStatus{
139 Command: cmd,
140 State: "waiting",
141 })
142 }
143 logM := io.MultiWriter(os.Stdout, s.logs)
144 for i, c := range commands {
145 if i > 0 {
146 s.status.Commands[i-1].State = "success"
147 }
gio0eaf2712024-04-14 13:08:46 +0400148 cmd := &exec.Cmd{
giofc441e32024-11-11 16:26:14 +0400149 Dir: filepath.Join(newDir, s.rootDir),
giobcd25e92025-05-03 19:14:10 +0400150 Path: "/bin/sh",
gio5155c1a2025-05-21 15:36:21 +0400151 Args: []string{"/bin/sh", "-c", c},
152 Env: append(os.Environ(), s.runCommands[i].Env...),
gio183e8342024-08-20 06:01:24 +0400153 Stdout: logM,
154 Stderr: logM,
gio0eaf2712024-04-14 13:08:46 +0400155 }
gioff0ee0f2024-10-15 23:11:54 +0400156 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
gio5155c1a2025-05-21 15:36:21 +0400157 fmt.Printf("Running: %s\n", c)
158 s.status.Commands[i].State = "running"
gio0eaf2712024-04-14 13:08:46 +0400159 if i < len(s.runCommands)-1 {
160 if err := cmd.Run(); err != nil {
161 return err
162 }
163 } else {
gio45c31822024-10-24 10:58:02 +0400164 if s.cmd != nil {
165 // TODO(gio): make this point configurable
166 if err := s.kill(); err != nil {
167 return err
168 }
gio5155c1a2025-05-21 15:36:21 +0400169 if s.currDir != "" {
170 if err := os.RemoveAll(s.currDir); err != nil {
171 return err
172 }
gio45c31822024-10-24 10:58:02 +0400173 }
174 }
gio0eaf2712024-04-14 13:08:46 +0400175 if err := cmd.Start(); err != nil {
176 return err
177 }
178 s.cmd = cmd
179 }
180 }
gio45c31822024-10-24 10:58:02 +0400181 s.currDir = newDir
gio0eaf2712024-04-14 13:08:46 +0400182 return nil
183}
184
185type pingReq struct {
gio5155c1a2025-05-21 15:36:21 +0400186 Id string `json:"id"`
187 Service string `json:"service"`
188 Address string `json:"address"`
189 Status *Status `json:"status,omitempty"`
190 Logs string `json:"logs"`
gio0eaf2712024-04-14 13:08:46 +0400191}
192
193func (s *Server) pingManager() {
194 defer func() {
195 go func() {
196 time.Sleep(5 * time.Second)
197 s.pingManager()
198 }()
199 }()
gioa60f0de2024-07-08 10:49:48 +0400200 buf, err := json.Marshal(pingReq{
gio5155c1a2025-05-21 15:36:21 +0400201 Id: s.id,
giob87415c2025-05-08 22:32:11 +0400202 Service: s.service,
203 Address: fmt.Sprintf("http://%s:%d", s.self, s.port),
gio5155c1a2025-05-21 15:36:21 +0400204 Status: s.status,
gio183e8342024-08-20 06:01:24 +0400205 Logs: s.logs.Contents(),
gioa60f0de2024-07-08 10:49:48 +0400206 })
gio0eaf2712024-04-14 13:08:46 +0400207 if err != nil {
208 return
209 }
giob87415c2025-05-08 22:32:11 +0400210 registerWorkerAddr := fmt.Sprintf("%s/api/project/%s/workers", s.managerAddr, s.appId)
211 resp, err := http.Post(registerWorkerAddr, "application/json", bytes.NewReader(buf))
212 if err != nil {
213 fmt.Println(err)
214 } else {
215 // check resp code
216 io.Copy(os.Stdout, resp.Body)
217 }
gio0eaf2712024-04-14 13:08:46 +0400218}
gio45c31822024-10-24 10:58:02 +0400219
220func (s *Server) kill() error {
221 if s.cmd == nil {
222 return nil
223 }
224
225 err := syscall.Kill(-s.cmd.Process.Pid, syscall.SIGKILL)
226 if err != nil {
227 return err
228 }
229 // NOTE(gio): No need to check err as we just killed the process
230 s.cmd.Wait()
231 s.cmd = nil
232 return nil
233}