blob: a65cb0a251fb9fe37a04d0f56205fae9d4e7ea69 [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 != "" {
gioe8402352025-06-24 21:28:25 +0400135 if _, err := os.Stat(filepath.Join(newDir, ".git")); err != nil && os.IsNotExist(err) {
136 commit, err := CloneRepositoryBranch(s.repoAddr, s.branch, s.rootDir, s.signer, newDir)
137 if err != nil {
138 fmt.Fprintf(s.logs, "!!! dodo: Failed to clone repository\n")
139 s.status = &Status{
140 Commit: nil,
141 }
142 return err
gioe65d9a92025-06-19 09:02:32 +0400143 }
gioe8402352025-06-24 21:28:25 +0400144 fmt.Fprintf(s.logs, "!!! dodo: Successfully cloned repository %s\n", commit.Hash)
145 s.status = &Status{
146 Commit: commit,
147 Commands: []CommandStatus{},
148 }
149 } else {
150 s.status = &Status{
151 Commands: []CommandStatus{},
152 }
gioe65d9a92025-06-19 09:02:32 +0400153 }
154 } else {
155 s.status = &Status{
156 Commit: nil,
157 Commands: []CommandStatus{},
158 }
gio5155c1a2025-05-21 15:36:21 +0400159 }
gio24d6e9a2025-06-24 15:02:29 +0400160 if s.agentMode && s.repoAddr == "" {
gioe65d9a92025-06-19 09:02:32 +0400161 if _, err := os.Stat(filepath.Join(newDir, ".git")); err != nil && os.IsNotExist(err) {
162 commands = append(commands, command{cmd: "git config --global user.name dodo"})
163 s.status.Commands = append(s.status.Commands, CommandStatus{
164 Command: commands[len(commands)-1].cmd,
165 State: "waiting",
166 })
167 commands = append(commands, command{cmd: "git config --global user.email dodo@dodo.cloud"})
168 s.status.Commands = append(s.status.Commands, CommandStatus{
169 Command: commands[len(commands)-1].cmd,
170 State: "waiting",
171 })
172 commands = append(commands, command{cmd: "git init ."})
173 s.status.Commands = append(s.status.Commands, CommandStatus{
174 Command: commands[len(commands)-1].cmd,
175 State: "waiting",
176 })
177 commands = append(commands, command{cmd: "echo \"TODO: Describe project\" > README.md"})
178 s.status.Commands = append(s.status.Commands, CommandStatus{
179 Command: commands[len(commands)-1].cmd,
180 State: "waiting",
181 })
182 commands = append(commands, command{cmd: "git add README.md"})
183 s.status.Commands = append(s.status.Commands, CommandStatus{
184 Command: commands[len(commands)-1].cmd,
185 State: "waiting",
186 })
187 commands = append(commands, command{cmd: "git commit -m \"init\""})
188 s.status.Commands = append(s.status.Commands, CommandStatus{
189 Command: commands[len(commands)-1].cmd,
190 State: "waiting",
191 })
192 }
193 }
gio5155c1a2025-05-21 15:36:21 +0400194 for _, c := range s.runCommands {
gio0eaf2712024-04-14 13:08:46 +0400195 args := []string{c.Bin}
196 args = append(args, c.Args...)
gio5155c1a2025-05-21 15:36:21 +0400197 cmd := strings.Join(args, " ")
gioe65d9a92025-06-19 09:02:32 +0400198 commands = append(commands, command{cmd, c.Env})
gio5155c1a2025-05-21 15:36:21 +0400199 s.status.Commands = append(s.status.Commands, CommandStatus{
200 Command: cmd,
201 State: "waiting",
202 })
203 }
204 logM := io.MultiWriter(os.Stdout, s.logs)
205 for i, c := range commands {
206 if i > 0 {
207 s.status.Commands[i-1].State = "success"
208 }
gio0eaf2712024-04-14 13:08:46 +0400209 cmd := &exec.Cmd{
giofc441e32024-11-11 16:26:14 +0400210 Dir: filepath.Join(newDir, s.rootDir),
giobcd25e92025-05-03 19:14:10 +0400211 Path: "/bin/sh",
gioe65d9a92025-06-19 09:02:32 +0400212 Args: []string{"/bin/sh", "-c", c.cmd},
213 Env: append(os.Environ(), c.env...),
gio183e8342024-08-20 06:01:24 +0400214 Stdout: logM,
215 Stderr: logM,
gio0eaf2712024-04-14 13:08:46 +0400216 }
gioff0ee0f2024-10-15 23:11:54 +0400217 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
gio5155c1a2025-05-21 15:36:21 +0400218 fmt.Printf("Running: %s\n", c)
gio4bfed002025-05-22 13:23:22 +0400219 fmt.Fprintf(s.logs, "!!! dodo: Running: %s\n", c)
gio5155c1a2025-05-21 15:36:21 +0400220 s.status.Commands[i].State = "running"
gioe65d9a92025-06-19 09:02:32 +0400221 if i < len(commands)-1 {
gio0eaf2712024-04-14 13:08:46 +0400222 if err := cmd.Run(); err != nil {
223 return err
224 }
225 } else {
gio45c31822024-10-24 10:58:02 +0400226 if s.cmd != nil {
227 // TODO(gio): make this point configurable
228 if err := s.kill(); err != nil {
229 return err
230 }
gioe65d9a92025-06-19 09:02:32 +0400231 if s.currDir != "" && !s.agentMode {
gio5155c1a2025-05-21 15:36:21 +0400232 if err := os.RemoveAll(s.currDir); err != nil {
233 return err
234 }
gio45c31822024-10-24 10:58:02 +0400235 }
236 }
gio0eaf2712024-04-14 13:08:46 +0400237 if err := cmd.Start(); err != nil {
238 return err
239 }
240 s.cmd = cmd
241 }
242 }
gio45c31822024-10-24 10:58:02 +0400243 s.currDir = newDir
gio0eaf2712024-04-14 13:08:46 +0400244 return nil
245}
246
247type pingReq struct {
gio5155c1a2025-05-21 15:36:21 +0400248 Id string `json:"id"`
249 Service string `json:"service"`
250 Address string `json:"address"`
251 Status *Status `json:"status,omitempty"`
252 Logs string `json:"logs"`
gio0eaf2712024-04-14 13:08:46 +0400253}
254
255func (s *Server) pingManager() {
256 defer func() {
257 go func() {
258 time.Sleep(5 * time.Second)
259 s.pingManager()
260 }()
261 }()
gioa60f0de2024-07-08 10:49:48 +0400262 buf, err := json.Marshal(pingReq{
gio5155c1a2025-05-21 15:36:21 +0400263 Id: s.id,
giob87415c2025-05-08 22:32:11 +0400264 Service: s.service,
265 Address: fmt.Sprintf("http://%s:%d", s.self, s.port),
gio5155c1a2025-05-21 15:36:21 +0400266 Status: s.status,
gio183e8342024-08-20 06:01:24 +0400267 Logs: s.logs.Contents(),
gioa60f0de2024-07-08 10:49:48 +0400268 })
gio0eaf2712024-04-14 13:08:46 +0400269 if err != nil {
270 return
271 }
giob87415c2025-05-08 22:32:11 +0400272 registerWorkerAddr := fmt.Sprintf("%s/api/project/%s/workers", s.managerAddr, s.appId)
273 resp, err := http.Post(registerWorkerAddr, "application/json", bytes.NewReader(buf))
274 if err != nil {
275 fmt.Println(err)
276 } else {
277 // check resp code
278 io.Copy(os.Stdout, resp.Body)
279 }
gio0eaf2712024-04-14 13:08:46 +0400280}
gio45c31822024-10-24 10:58:02 +0400281
282func (s *Server) kill() error {
283 if s.cmd == nil {
284 return nil
285 }
286
287 err := syscall.Kill(-s.cmd.Process.Pid, syscall.SIGKILL)
288 if err != nil {
289 return err
290 }
291 // NOTE(gio): No need to check err as we just killed the process
292 s.cmd.Wait()
293 s.cmd = nil
294 return nil
295}