01671969e867777570d9571a59fc72e11b6495ee
[src/xds/xds-server.git] / lib / apiv1 / exec.go
1 package apiv1
2
3 import (
4         "fmt"
5         "net/http"
6         "os"
7         "regexp"
8         "strconv"
9         "strings"
10         "time"
11
12         "github.com/gin-gonic/gin"
13         common "github.com/iotbzh/xds-common/golib"
14         "github.com/iotbzh/xds-common/golib/eows"
15         "github.com/kr/pty"
16 )
17
18 type (
19         // ExecArgs JSON parameters of /exec command
20         ExecArgs struct {
21                 ID              string   `json:"id" binding:"required"`
22                 SdkID           string   `json:"sdkID"` // sdk ID to use for setting env
23                 CmdID           string   `json:"cmdID"` // command unique ID
24                 Cmd             string   `json:"cmd" binding:"required"`
25                 Args            []string `json:"args"`
26                 Env             []string `json:"env"`
27                 RPath           string   `json:"rpath"`           // relative path into project
28                 TTY             bool     `json:"tty"`             // Use a tty, specific to gdb --tty option
29                 TTYGdbserverFix bool     `json:"ttyGdbserverFix"` // Set to true to activate gdbserver workaround about inferior output
30                 ExitImmediate   bool     `json:"exitImmediate"`   // when true, exit event sent immediately when command exited (IOW, don't wait file synchronization)
31                 CmdTimeout      int      `json:"timeout"`         // command completion timeout in Second
32         }
33
34         // ExecInMsg Message used to received input characters (stdin)
35         ExecInMsg struct {
36                 CmdID     string `json:"cmdID"`
37                 Timestamp string `json:"timestamp"`
38                 Stdin     string `json:"stdin"`
39         }
40
41         // ExecOutMsg Message used to send output characters (stdout+stderr)
42         ExecOutMsg struct {
43                 CmdID     string `json:"cmdID"`
44                 Timestamp string `json:"timestamp"`
45                 Stdout    string `json:"stdout"`
46                 Stderr    string `json:"stderr"`
47         }
48
49         // ExecExitMsg Message sent when executed command exited
50         ExecExitMsg struct {
51                 CmdID     string `json:"cmdID"`
52                 Timestamp string `json:"timestamp"`
53                 Code      int    `json:"code"`
54                 Error     error  `json:"error"`
55         }
56
57         // ExecSignalArgs JSON parameters of /exec/signal command
58         ExecSignalArgs struct {
59                 CmdID  string `json:"cmdID" binding:"required"`  // command id
60                 Signal string `json:"signal" binding:"required"` // signal number
61         }
62 )
63
64 const (
65         // ExecInEvent Event send in WS when characters are sent (stdin)
66         ExecInEvent = "exec:input"
67
68         // ExecOutEvent Event send in WS when characters are received (stdout or stderr)
69         ExecOutEvent = "exec:output"
70
71         // ExecExitEvent Event send in WS when program exited
72         ExecExitEvent = "exec:exit"
73
74         // ExecInferiorInEvent Event send in WS when characters are sent to an inferior (used by gdb inferior/tty)
75         ExecInferiorInEvent = "exec:inferior-input"
76
77         // ExecInferiorOutEvent Event send in WS when characters are received by an inferior
78         ExecInferiorOutEvent = "exec:inferior-output"
79 )
80
81 var execCommandID = 1
82
83 // ExecCmd executes remotely a command
84 func (s *APIService) execCmd(c *gin.Context) {
85         var gdbPty, gdbTty *os.File
86         var err error
87         var args ExecArgs
88         if c.BindJSON(&args) != nil {
89                 common.APIError(c, "Invalid arguments")
90                 return
91         }
92
93         // TODO: add permission ?
94
95         // Retrieve session info
96         sess := s.sessions.Get(c)
97         if sess == nil {
98                 common.APIError(c, "Unknown sessions")
99                 return
100         }
101         sop := sess.IOSocket
102         if sop == nil {
103                 common.APIError(c, "Websocket not established")
104                 return
105         }
106
107         // Allow to pass id in url (/exec/:id) or as JSON argument
108         id := c.Param("id")
109         if id == "" {
110                 id = args.ID
111         }
112         if id == "" {
113                 common.APIError(c, "Invalid id")
114                 return
115         }
116
117         f := s.mfolders.Get(id)
118         if f == nil {
119                 common.APIError(c, "Unknown id")
120                 return
121         }
122         fld := *f
123         prj := fld.GetConfig()
124
125         // Build command line
126         cmd := []string{}
127         // Setup env var regarding Sdk ID (used for example to setup cross toolchain)
128         if envCmd := s.sdks.GetEnvCmd(args.SdkID, prj.DefaultSdk); len(envCmd) > 0 {
129                 cmd = append(cmd, envCmd...)
130                 cmd = append(cmd, "&&")
131         } else {
132                 // It's an error if no envcmd found while a sdkid has been provided
133                 if args.SdkID != "" {
134                         common.APIError(c, "Unknown sdkid")
135                         return
136                 }
137         }
138
139         cmd = append(cmd, "cd", fld.GetFullPath(args.RPath))
140         // FIXME - add 'exec' prevents to use syntax:
141         //       xds-exec -l debug -c xds-config.env -- "cd build && cmake .."
142         //  but exec is mandatory to allow to pass correctly signals
143         //  As workaround, exec is set for now on client side (eg. in xds-gdb)
144         //cmd = append(cmd, "&&", "exec", args.Cmd)
145         cmd = append(cmd, "&&", args.Cmd)
146
147         // Process command arguments
148         cmdArgs := make([]string, len(args.Args)+1)
149
150         // Copy and Translate path from client to server
151         for _, aa := range args.Args {
152                 if strings.Contains(aa, prj.ClientPath) {
153                         cmdArgs = append(cmdArgs, fld.ConvPathCli2Svr(aa))
154                 } else {
155                         cmdArgs = append(cmdArgs, aa)
156                 }
157         }
158
159         // Allocate pts if tty if used
160         if args.TTY {
161                 gdbPty, gdbTty, err = pty.Open()
162                 if err != nil {
163                         common.APIError(c, err.Error())
164                         return
165                 }
166
167                 s.log.Debugf("Client command tty: %v %v\n", gdbTty.Name(), gdbTty.Name())
168                 cmdArgs = append(cmdArgs, "--tty="+gdbTty.Name())
169         }
170
171         // Unique ID for each commands
172         if args.CmdID == "" {
173                 args.CmdID = s.cfg.ServerUID[:18] + "_" + strconv.Itoa(execCommandID)
174                 execCommandID++
175         }
176
177         // Create new execution over WS context
178         execWS := eows.New(strings.Join(cmd, " "), cmdArgs, sop, sess.ID, args.CmdID)
179         execWS.Log = s.log
180
181         // Append client project dir to environment
182         execWS.Env = append(args.Env, "CLIENT_PROJECT_DIR="+prj.ClientPath)
183
184         // Set command execution timeout
185         if args.CmdTimeout == 0 {
186                 // 0 : default timeout
187                 // TODO get default timeout from config.json file
188                 execWS.CmdExecTimeout = 24 * 60 * 60 // 1 day
189         } else {
190                 execWS.CmdExecTimeout = args.CmdTimeout
191         }
192
193         // Define callback for input (stdin)
194         execWS.InputEvent = ExecInEvent
195         execWS.InputCB = func(e *eows.ExecOverWS, stdin string) (string, error) {
196                 s.log.Debugf("STDIN <<%v>>", strings.Replace(stdin, "\n", "\\n", -1))
197
198                 // Handle Ctrl-D
199                 if len(stdin) == 1 && stdin == "\x04" {
200                         // Close stdin
201                         errMsg := fmt.Errorf("close stdin: %v", stdin)
202                         return "", errMsg
203                 }
204
205                 // Set correct path
206                 data := e.UserData
207                 prjID := (*data)["ID"].(string)
208                 f := s.mfolders.Get(prjID)
209                 if f == nil {
210                         s.log.Errorf("InputCB: Cannot get folder ID %s", prjID)
211                 } else {
212                         // Translate paths from client to server
213                         stdin = (*f).ConvPathCli2Svr(stdin)
214                 }
215
216                 return stdin, nil
217         }
218
219         // Define callback for output (stdout+stderr)
220         execWS.OutputCB = func(e *eows.ExecOverWS, stdout, stderr string) {
221                 // IO socket can be nil when disconnected
222                 so := s.sessions.IOSocketGet(e.Sid)
223                 if so == nil {
224                         s.log.Infof("%s not emitted: WS closed (sid:%s, msgid:%s)", ExecOutEvent, e.Sid, e.CmdID)
225                         return
226                 }
227
228                 // Retrieve project ID and RootPath
229                 data := e.UserData
230                 prjID := (*data)["ID"].(string)
231                 gdbServerTTY := (*data)["gdbServerTTY"].(string)
232
233                 f := s.mfolders.Get(prjID)
234                 if f == nil {
235                         s.log.Errorf("OutputCB: Cannot get folder ID %s", prjID)
236                 } else {
237                         // Translate paths from server to client
238                         stdout = (*f).ConvPathSvr2Cli(stdout)
239                         stderr = (*f).ConvPathSvr2Cli(stderr)
240                 }
241
242                 s.log.Debugf("%s emitted - WS sid[4:] %s - id:%s - prjID:%s", ExecOutEvent, e.Sid[4:], e.CmdID, prjID)
243                 if stdout != "" {
244                         s.log.Debugf("STDOUT <<%v>>", strings.Replace(stdout, "\n", "\\n", -1))
245                 }
246                 if stderr != "" {
247                         s.log.Debugf("STDERR <<%v>>", strings.Replace(stderr, "\n", "\\n", -1))
248                 }
249
250                 // FIXME replace by .BroadcastTo a room
251                 err := (*so).Emit(ExecOutEvent, ExecOutMsg{
252                         CmdID:     e.CmdID,
253                         Timestamp: time.Now().String(),
254                         Stdout:    stdout,
255                         Stderr:    stderr,
256                 })
257                 if err != nil {
258                         s.log.Errorf("WS Emit : %v", err)
259                 }
260
261                 // XXX - Workaround due to gdbserver bug that doesn't redirect
262                 // inferior output (https://bugs.eclipse.org/bugs/show_bug.cgi?id=437532#c13)
263                 if gdbServerTTY == "workaround" && len(stdout) > 1 && stdout[0] == '&' {
264
265                         // Extract and cleanup string like &"bla bla\n"
266                         re := regexp.MustCompile("&\"(.*)\"")
267                         rer := re.FindAllStringSubmatch(stdout, -1)
268                         out := ""
269                         if rer != nil && len(rer) > 0 {
270                                 for _, o := range rer {
271                                         if len(o) >= 1 {
272                                                 out = strings.Replace(o[1], "\\n", "\n", -1)
273                                                 out = strings.Replace(out, "\\r", "\r", -1)
274                                                 out = strings.Replace(out, "\\t", "\t", -1)
275
276                                                 s.log.Debugf("STDOUT INFERIOR: <<%v>>", out)
277                                                 err := (*so).Emit(ExecInferiorOutEvent, ExecOutMsg{
278                                                         CmdID:     e.CmdID,
279                                                         Timestamp: time.Now().String(),
280                                                         Stdout:    out,
281                                                         Stderr:    "",
282                                                 })
283                                                 if err != nil {
284                                                         s.log.Errorf("WS Emit : %v", err)
285                                                 }
286                                         }
287                                 }
288                         } else {
289                                 s.log.Errorf("INFERIOR out parsing error: stdout=<%v>", stdout)
290                         }
291                 }
292         }
293
294         // Define callback for output
295         execWS.ExitCB = func(e *eows.ExecOverWS, code int, err error) {
296                 s.log.Debugf("Command [Cmd ID %s] exited: code %d, error: %v", e.CmdID, code, err)
297
298                 // IO socket can be nil when disconnected
299                 so := s.sessions.IOSocketGet(e.Sid)
300                 if so == nil {
301                         s.log.Infof("%s not emitted - WS closed (id:%s)", ExecExitEvent, e.CmdID)
302                         return
303                 }
304
305                 // Retrieve project ID and RootPath
306                 data := e.UserData
307                 prjID := (*data)["ID"].(string)
308                 exitImm := (*data)["ExitImmediate"].(bool)
309
310                 // XXX - workaround to be sure that Syncthing detected all changes
311                 if err := s.mfolders.ForceSync(prjID); err != nil {
312                         s.log.Errorf("Error while syncing folder %s: %v", prjID, err)
313                 }
314                 if !exitImm {
315                         // Wait end of file sync
316                         // FIXME pass as argument
317                         tmo := 60
318                         for t := tmo; t > 0; t-- {
319                                 s.log.Debugf("Wait file in-sync for %s (%d/%d)", prjID, t, tmo)
320                                 if sync, err := s.mfolders.IsFolderInSync(prjID); sync || err != nil {
321                                         if err != nil {
322                                                 s.log.Errorf("ERROR IsFolderInSync (%s): %v", prjID, err)
323                                         }
324                                         break
325                                 }
326                                 time.Sleep(time.Second)
327                         }
328                 }
329
330                 // Close client tty
331                 if gdbPty != nil {
332                         gdbPty.Close()
333                 }
334                 if gdbTty != nil {
335                         gdbTty.Close()
336                 }
337
338                 // FIXME replace by .BroadcastTo a room
339                 errSoEmit := (*so).Emit(ExecExitEvent, ExecExitMsg{
340                         CmdID:     e.CmdID,
341                         Timestamp: time.Now().String(),
342                         Code:      code,
343                         Error:     err,
344                 })
345                 if errSoEmit != nil {
346                         s.log.Errorf("WS Emit : %v", errSoEmit)
347                 }
348         }
349
350         // User data (used within callbacks)
351         data := make(map[string]interface{})
352         data["ID"] = prj.ID
353         data["ExitImmediate"] = args.ExitImmediate
354         if args.TTY && args.TTYGdbserverFix {
355                 data["gdbServerTTY"] = "workaround"
356         } else {
357                 data["gdbServerTTY"] = ""
358         }
359         execWS.UserData = &data
360
361         // Start command execution
362         s.log.Infof("Execute [Cmd ID %s]: %v %v", execWS.CmdID, execWS.Cmd, execWS.Args)
363
364         err = execWS.Start()
365         if err != nil {
366                 common.APIError(c, err.Error())
367                 return
368         }
369
370         c.JSON(http.StatusOK,
371                 gin.H{
372                         "status": "OK",
373                         "cmdID":  execWS.CmdID,
374                 })
375 }
376
377 // ExecCmd executes remotely a command
378 func (s *APIService) execSignalCmd(c *gin.Context) {
379         var args ExecSignalArgs
380
381         if c.BindJSON(&args) != nil {
382                 common.APIError(c, "Invalid arguments")
383                 return
384         }
385
386         s.log.Debugf("Signal %s for command ID %s", args.Signal, args.CmdID)
387
388         e := eows.GetEows(args.CmdID)
389         if e == nil {
390                 common.APIError(c, "unknown cmdID")
391                 return
392         }
393
394         err := e.Signal(args.Signal)
395         if err != nil {
396                 common.APIError(c, err.Error())
397                 return
398         }
399
400         c.JSON(http.StatusOK,
401                 gin.H{
402                         "status": "OK",
403                 })
404 }