blob: 89f621a72f996cb5a91b69c25a42ace7ab32cd84 [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
gioe65d9a92025-06-19 09:02:32 +040034 agentMode bool
gio0eaf2712024-04-14 13:08:46 +040035 port int
gio266c04f2024-07-03 14:18:45 +040036 appId string
giob87415c2025-05-08 22:32:11 +040037 service string
gio5155c1a2025-05-21 15:36:21 +040038 id string
gio0eaf2712024-04-14 13:08:46 +040039 ready bool
40 cmd *exec.Cmd
41 repoAddr string
gio2b1157a2024-10-24 08:45:07 +040042 branch string
giofc441e32024-11-11 16:26:14 +040043 rootDir string
gio0eaf2712024-04-14 13:08:46 +040044 signer ssh.Signer
45 appDir string
46 runCommands []Command
47 self string
gioa60f0de2024-07-08 10:49:48 +040048 managerAddr string
gio183e8342024-08-20 06:01:24 +040049 logs *Log
gio45c31822024-10-24 10:58:02 +040050 currDir string
gio5155c1a2025-05-21 15:36:21 +040051 status *Status
gio0eaf2712024-04-14 13:08:46 +040052}
53
gioe65d9a92025-06-19 09:02:32 +040054func NewServer(agentMode bool, 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 +040055 return &Server{
56 l: &sync.Mutex{},
gioe65d9a92025-06-19 09:02:32 +040057 agentMode: agentMode,
gio0eaf2712024-04-14 13:08:46 +040058 port: port,
59 ready: false,
gio266c04f2024-07-03 14:18:45 +040060 appId: appId,
giob87415c2025-05-08 22:32:11 +040061 service: service,
gio5155c1a2025-05-21 15:36:21 +040062 id: id,
gio0eaf2712024-04-14 13:08:46 +040063 repoAddr: repoAddr,
gio2b1157a2024-10-24 08:45:07 +040064 branch: branch,
giofc441e32024-11-11 16:26:14 +040065 rootDir: rootDir,
gio0eaf2712024-04-14 13:08:46 +040066 signer: signer,
67 appDir: appDir,
68 runCommands: runCommands,
69 self: self,
gioa60f0de2024-07-08 10:49:48 +040070 managerAddr: manager,
gio183e8342024-08-20 06:01:24 +040071 logs: &Log{},
gio45c31822024-10-24 10:58:02 +040072 currDir: "",
gio5155c1a2025-05-21 15:36:21 +040073 status: nil,
gio0eaf2712024-04-14 13:08:46 +040074 }
75}
76
77func (s *Server) Start() error {
78 http.HandleFunc("/update", s.handleUpdate)
79 http.HandleFunc("/ready", s.handleReady)
gio183e8342024-08-20 06:01:24 +040080 http.HandleFunc("/logs", s.handleLogs)
gioec744fa2025-05-20 12:47:03 +040081 if s.managerAddr != "" && s.appId != "" {
82 go s.pingManager()
83 }
gio0eaf2712024-04-14 13:08:46 +040084 if err := s.run(); err != nil {
85 return err
86 }
gio0eaf2712024-04-14 13:08:46 +040087 return http.ListenAndServe(fmt.Sprintf(":%d", s.port), nil)
88}
89
gio183e8342024-08-20 06:01:24 +040090func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
91 fmt.Fprint(w, s.logs.Contents())
92}
93
gio0eaf2712024-04-14 13:08:46 +040094func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) {
95 s.l.Lock()
96 defer s.l.Unlock()
97 if s.ready {
98 fmt.Fprintln(w, "ok")
99 } else {
100 http.Error(w, "not ready", http.StatusInternalServerError)
101 }
102}
103
104func (s *Server) handleUpdate(w http.ResponseWriter, r *http.Request) {
105 fmt.Println("update")
106 s.l.Lock()
107 s.ready = false
108 s.l.Unlock()
gio4bfed002025-05-22 13:23:22 +0400109 fmt.Fprintf(s.logs, "!!! dodo: Reloading service\n")
gio0eaf2712024-04-14 13:08:46 +0400110 if err := s.run(); err != nil {
111 http.Error(w, err.Error(), http.StatusInternalServerError)
112 return
113 }
114 s.l.Lock()
115 s.ready = true
116 s.l.Unlock()
117}
118
gioe65d9a92025-06-19 09:02:32 +0400119type command struct {
120 cmd string
121 env []string
122}
123
gio0eaf2712024-04-14 13:08:46 +0400124func (s *Server) run() error {
gioe65d9a92025-06-19 09:02:32 +0400125 newDir := s.appDir
126 commands := []command{}
127 if !s.agentMode {
128 var err error
129 newDir, err = os.MkdirTemp(s.appDir, "code-*")
130 if err != nil {
131 return err
gio5155c1a2025-05-21 15:36:21 +0400132 }
gio0eaf2712024-04-14 13:08:46 +0400133 }
gioe65d9a92025-06-19 09:02:32 +0400134 if s.repoAddr != "" {
135 commit, err := CloneRepositoryBranch(s.repoAddr, s.branch, s.rootDir, s.signer, newDir)
136 if err != nil {
137 fmt.Fprintf(s.logs, "!!! dodo: Failed to clone repository\n")
138 s.status = &Status{
139 Commit: nil,
140 }
141 return err
142 }
143 fmt.Fprintf(s.logs, "!!! dodo: Successfully cloned repository %s\n", commit.Hash)
144 s.status = &Status{
145 Commit: commit,
146 Commands: []CommandStatus{},
147 }
148 } else {
149 s.status = &Status{
150 Commit: nil,
151 Commands: []CommandStatus{},
152 }
gio5155c1a2025-05-21 15:36:21 +0400153 }
gioe65d9a92025-06-19 09:02:32 +0400154 if s.agentMode {
155 if _, err := os.Stat(filepath.Join(newDir, ".git")); err != nil && os.IsNotExist(err) {
156 commands = append(commands, command{cmd: "git config --global user.name dodo"})
157 s.status.Commands = append(s.status.Commands, CommandStatus{
158 Command: commands[len(commands)-1].cmd,
159 State: "waiting",
160 })
161 commands = append(commands, command{cmd: "git config --global user.email dodo@dodo.cloud"})
162 s.status.Commands = append(s.status.Commands, CommandStatus{
163 Command: commands[len(commands)-1].cmd,
164 State: "waiting",
165 })
166 commands = append(commands, command{cmd: "git init ."})
167 s.status.Commands = append(s.status.Commands, CommandStatus{
168 Command: commands[len(commands)-1].cmd,
169 State: "waiting",
170 })
171 commands = append(commands, command{cmd: "echo \"TODO: Describe project\" > README.md"})
172 s.status.Commands = append(s.status.Commands, CommandStatus{
173 Command: commands[len(commands)-1].cmd,
174 State: "waiting",
175 })
176 commands = append(commands, command{cmd: "git add README.md"})
177 s.status.Commands = append(s.status.Commands, CommandStatus{
178 Command: commands[len(commands)-1].cmd,
179 State: "waiting",
180 })
181 commands = append(commands, command{cmd: "git commit -m \"init\""})
182 s.status.Commands = append(s.status.Commands, CommandStatus{
183 Command: commands[len(commands)-1].cmd,
184 State: "waiting",
185 })
186 }
187 }
gio5155c1a2025-05-21 15:36:21 +0400188 for _, c := range s.runCommands {
gio0eaf2712024-04-14 13:08:46 +0400189 args := []string{c.Bin}
190 args = append(args, c.Args...)
gio5155c1a2025-05-21 15:36:21 +0400191 cmd := strings.Join(args, " ")
gioe65d9a92025-06-19 09:02:32 +0400192 commands = append(commands, command{cmd, c.Env})
gio5155c1a2025-05-21 15:36:21 +0400193 s.status.Commands = append(s.status.Commands, CommandStatus{
194 Command: cmd,
195 State: "waiting",
196 })
197 }
198 logM := io.MultiWriter(os.Stdout, s.logs)
199 for i, c := range commands {
200 if i > 0 {
201 s.status.Commands[i-1].State = "success"
202 }
gio0eaf2712024-04-14 13:08:46 +0400203 cmd := &exec.Cmd{
giofc441e32024-11-11 16:26:14 +0400204 Dir: filepath.Join(newDir, s.rootDir),
giobcd25e92025-05-03 19:14:10 +0400205 Path: "/bin/sh",
gioe65d9a92025-06-19 09:02:32 +0400206 Args: []string{"/bin/sh", "-c", c.cmd},
207 Env: append(os.Environ(), c.env...),
gio183e8342024-08-20 06:01:24 +0400208 Stdout: logM,
209 Stderr: logM,
gio0eaf2712024-04-14 13:08:46 +0400210 }
gioff0ee0f2024-10-15 23:11:54 +0400211 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
gio5155c1a2025-05-21 15:36:21 +0400212 fmt.Printf("Running: %s\n", c)
gio4bfed002025-05-22 13:23:22 +0400213 fmt.Fprintf(s.logs, "!!! dodo: Running: %s\n", c)
gio5155c1a2025-05-21 15:36:21 +0400214 s.status.Commands[i].State = "running"
gioe65d9a92025-06-19 09:02:32 +0400215 if i < len(commands)-1 {
gio0eaf2712024-04-14 13:08:46 +0400216 if err := cmd.Run(); err != nil {
217 return err
218 }
219 } else {
gio45c31822024-10-24 10:58:02 +0400220 if s.cmd != nil {
221 // TODO(gio): make this point configurable
222 if err := s.kill(); err != nil {
223 return err
224 }
gioe65d9a92025-06-19 09:02:32 +0400225 if s.currDir != "" && !s.agentMode {
gio5155c1a2025-05-21 15:36:21 +0400226 if err := os.RemoveAll(s.currDir); err != nil {
227 return err
228 }
gio45c31822024-10-24 10:58:02 +0400229 }
230 }
gio0eaf2712024-04-14 13:08:46 +0400231 if err := cmd.Start(); err != nil {
232 return err
233 }
234 s.cmd = cmd
235 }
236 }
gio45c31822024-10-24 10:58:02 +0400237 s.currDir = newDir
gio0eaf2712024-04-14 13:08:46 +0400238 return nil
239}
240
241type pingReq struct {
gio5155c1a2025-05-21 15:36:21 +0400242 Id string `json:"id"`
243 Service string `json:"service"`
244 Address string `json:"address"`
245 Status *Status `json:"status,omitempty"`
246 Logs string `json:"logs"`
gio0eaf2712024-04-14 13:08:46 +0400247}
248
249func (s *Server) pingManager() {
250 defer func() {
251 go func() {
252 time.Sleep(5 * time.Second)
253 s.pingManager()
254 }()
255 }()
gioa60f0de2024-07-08 10:49:48 +0400256 buf, err := json.Marshal(pingReq{
gio5155c1a2025-05-21 15:36:21 +0400257 Id: s.id,
giob87415c2025-05-08 22:32:11 +0400258 Service: s.service,
259 Address: fmt.Sprintf("http://%s:%d", s.self, s.port),
gio5155c1a2025-05-21 15:36:21 +0400260 Status: s.status,
gio183e8342024-08-20 06:01:24 +0400261 Logs: s.logs.Contents(),
gioa60f0de2024-07-08 10:49:48 +0400262 })
gio0eaf2712024-04-14 13:08:46 +0400263 if err != nil {
264 return
265 }
giob87415c2025-05-08 22:32:11 +0400266 registerWorkerAddr := fmt.Sprintf("%s/api/project/%s/workers", s.managerAddr, s.appId)
267 resp, err := http.Post(registerWorkerAddr, "application/json", bytes.NewReader(buf))
268 if err != nil {
269 fmt.Println(err)
270 } else {
271 // check resp code
272 io.Copy(os.Stdout, resp.Body)
273 }
gio0eaf2712024-04-14 13:08:46 +0400274}
gio45c31822024-10-24 10:58:02 +0400275
276func (s *Server) kill() error {
277 if s.cmd == nil {
278 return nil
279 }
280
281 err := syscall.Kill(-s.cmd.Process.Pid, syscall.SIGKILL)
282 if err != nil {
283 return err
284 }
285 // NOTE(gio): No need to check err as we just killed the process
286 s.cmd.Wait()
287 s.cmd = nil
288 return nil
289}