12 "github.com/gin-gonic/gin"
13 common "github.com/iotbzh/xds-common/golib"
14 "github.com/iotbzh/xds-common/golib/eows"
19 // ExecArgs JSON parameters of /exec command
21 ID string `json:"id" binding:"required"`
22 SdkID string `json:"sdkid"` // sdk ID to use for setting env
23 Cmd string `json:"cmd" binding:"required"`
24 Args []string `json:"args"`
25 Env []string `json:"env"`
26 RPath string `json:"rpath"` // relative path into project
27 TTY bool `json:"tty"` // Use a tty, specific to gdb --tty option
28 TTYGdbserverFix bool `json:"ttyGdbserverFix"` // Set to true to activate gdbserver workaround about inferior output
29 ExitImmediate bool `json:"exitImmediate"` // when true, exit event sent immediately when command exited (IOW, don't wait file synchronization)
30 CmdTimeout int `json:"timeout"` // command completion timeout in Second
33 // ExecInMsg Message used to received input characters (stdin)
35 CmdID string `json:"cmdID"`
36 Timestamp string `json:"timestamp"`
37 Stdin string `json:"stdin"`
40 // ExecOutMsg Message used to send output characters (stdout+stderr)
42 CmdID string `json:"cmdID"`
43 Timestamp string `json:"timestamp"`
44 Stdout string `json:"stdout"`
45 Stderr string `json:"stderr"`
48 // ExecExitMsg Message sent when executed command exited
50 CmdID string `json:"cmdID"`
51 Timestamp string `json:"timestamp"`
52 Code int `json:"code"`
53 Error error `json:"error"`
56 // ExecSignalArgs JSON parameters of /exec/signal command
57 ExecSignalArgs struct {
58 CmdID string `json:"cmdID" binding:"required"` // command id
59 Signal string `json:"signal" binding:"required"` // signal number
64 // ExecInEvent Event send in WS when characters are sent (stdin)
65 ExecInEvent = "exec:input"
67 // ExecOutEvent Event send in WS when characters are received (stdout or stderr)
68 ExecOutEvent = "exec:output"
70 // ExecExitEvent Event send in WS when program exited
71 ExecExitEvent = "exec:exit"
73 // ExecInferiorInEvent Event send in WS when characters are sent to an inferior (used by gdb inferior/tty)
74 ExecInferiorInEvent = "exec:inferior-input"
76 // ExecInferiorOutEvent Event send in WS when characters are received by an inferior
77 ExecInferiorOutEvent = "exec:inferior-output"
82 // ExecCmd executes remotely a command
83 func (s *APIService) execCmd(c *gin.Context) {
84 var gdbPty, gdbTty *os.File
87 if c.BindJSON(&args) != nil {
88 common.APIError(c, "Invalid arguments")
92 // TODO: add permission ?
94 // Retrieve session info
95 sess := s.sessions.Get(c)
97 common.APIError(c, "Unknown sessions")
102 common.APIError(c, "Websocket not established")
106 // Allow to pass id in url (/exec/:id) or as JSON argument
112 common.APIError(c, "Invalid id")
116 f := s.mfolders.Get(id)
118 common.APIError(c, "Unknown id")
122 prj := folder.GetConfig()
124 // Build command line
126 // Setup env var regarding Sdk ID (used for example to setup cross toolchain)
127 if envCmd := s.sdks.GetEnvCmd(args.SdkID, prj.DefaultSdk); len(envCmd) > 0 {
128 cmd = append(cmd, envCmd...)
129 cmd = append(cmd, "&&")
131 // It's an error if no envcmd found while a sdkid has been provided
132 if args.SdkID != "" {
133 common.APIError(c, "Unknown sdkid")
138 cmd = append(cmd, "cd", folder.GetFullPath(args.RPath))
139 // FIXME - add 'exec' prevents to use syntax:
140 // xds-exec -l debug -c xds-config.env -- "cd build && cmake .."
141 // but exec is mandatory to allow to pass correctly signals
142 // As workaround, exec is set for now on client side (eg. in xds-gdb)
143 //cmd = append(cmd, "&&", "exec", args.Cmd)
144 cmd = append(cmd, "&&", args.Cmd)
146 // Process command arguments
147 cmdArgs := make([]string, len(args.Args)+1)
148 copy(cmdArgs, args.Args)
150 // Allocate pts if tty if used
152 gdbPty, gdbTty, err = pty.Open()
154 common.APIError(c, err.Error())
158 s.log.Debugf("Client command tty: %v %v\n", gdbTty.Name(), gdbTty.Name())
159 cmdArgs = append(cmdArgs, "--tty="+gdbTty.Name())
162 // Unique ID for each commands
163 cmdID := strconv.Itoa(execCommandID)
166 // Create new execution over WS context
167 execWS := eows.New(strings.Join(cmd, " "), cmdArgs, sop, sess.ID, cmdID)
170 // Append client project dir to environment
171 execWS.Env = append(args.Env, "CLIENT_PROJECT_DIR="+prj.ClientPath)
173 // Set command execution timeout
174 if args.CmdTimeout == 0 {
175 // 0 : default timeout
176 // TODO get default timeout from config.json file
177 execWS.CmdExecTimeout = 24 * 60 * 60 // 1 day
179 execWS.CmdExecTimeout = args.CmdTimeout
182 // Define callback for input (stdin)
183 execWS.InputEvent = ExecInEvent
184 execWS.InputCB = func(e *eows.ExecOverWS, stdin string) (string, error) {
185 s.log.Debugf("STDIN <<%v>>", strings.Replace(stdin, "\n", "\\n", -1))
188 if len(stdin) == 1 && stdin == "\x04" {
190 errMsg := fmt.Errorf("close stdin: %v", stdin)
196 rootPath := (*data)["RootPath"].(string)
197 clientPath := (*data)["ClientPath"].(string)
198 stdin = strings.Replace(stdin, clientPath, rootPath+"/"+clientPath, -1)
203 // Define callback for output (stdout+stderr)
204 execWS.OutputCB = func(e *eows.ExecOverWS, stdout, stderr string) {
205 // IO socket can be nil when disconnected
206 so := s.sessions.IOSocketGet(e.Sid)
208 s.log.Infof("%s not emitted: WS closed (sid:%s, msgid:%s)", ExecOutEvent, e.Sid, e.CmdID)
212 // Retrieve project ID and RootPath
214 prjID := (*data)["ID"].(string)
215 prjRootPath := (*data)["RootPath"].(string)
216 gdbServerTTY := (*data)["gdbServerTTY"].(string)
218 // Cleanup any references to internal rootpath in stdout & stderr
219 stdout = strings.Replace(stdout, prjRootPath, "", -1)
220 stderr = strings.Replace(stderr, prjRootPath, "", -1)
222 s.log.Debugf("%s emitted - WS sid[4:] %s - id:%s - prjID:%s", ExecOutEvent, e.Sid[4:], e.CmdID, prjID)
224 s.log.Debugf("STDOUT <<%v>>", strings.Replace(stdout, "\n", "\\n", -1))
227 s.log.Debugf("STDERR <<%v>>", strings.Replace(stderr, "\n", "\\n", -1))
230 // FIXME replace by .BroadcastTo a room
231 err := (*so).Emit(ExecOutEvent, ExecOutMsg{
233 Timestamp: time.Now().String(),
238 s.log.Errorf("WS Emit : %v", err)
241 // XXX - Workaround due to gdbserver bug that doesn't redirect
242 // inferior output (https://bugs.eclipse.org/bugs/show_bug.cgi?id=437532#c13)
243 if gdbServerTTY == "workaround" && len(stdout) > 1 && stdout[0] == '&' {
245 // Extract and cleanup string like &"bla bla\n"
246 re := regexp.MustCompile("&\"(.*)\"")
247 rer := re.FindAllStringSubmatch(stdout, -1)
249 if rer != nil && len(rer) > 0 {
250 for _, o := range rer {
252 out = strings.Replace(o[1], "\\n", "\n", -1)
253 out = strings.Replace(out, "\\r", "\r", -1)
254 out = strings.Replace(out, "\\t", "\t", -1)
256 s.log.Debugf("STDOUT INFERIOR: <<%v>>", out)
257 err := (*so).Emit(ExecInferiorOutEvent, ExecOutMsg{
259 Timestamp: time.Now().String(),
264 s.log.Errorf("WS Emit : %v", err)
269 s.log.Errorf("INFERIOR out parsing error: stdout=<%v>", stdout)
274 // Define callback for output
275 execWS.ExitCB = func(e *eows.ExecOverWS, code int, err error) {
276 s.log.Debugf("Command [Cmd ID %s] exited: code %d, error: %v", e.CmdID, code, err)
278 // IO socket can be nil when disconnected
279 so := s.sessions.IOSocketGet(e.Sid)
281 s.log.Infof("%s not emitted - WS closed (id:%s)", ExecExitEvent, e.CmdID)
285 // Retrieve project ID and RootPath
287 prjID := (*data)["ID"].(string)
288 exitImm := (*data)["ExitImmediate"].(bool)
290 // XXX - workaround to be sure that Syncthing detected all changes
291 if err := s.mfolders.ForceSync(prjID); err != nil {
292 s.log.Errorf("Error while syncing folder %s: %v", prjID, err)
295 // Wait end of file sync
296 // FIXME pass as argument
298 for t := tmo; t > 0; t-- {
299 s.log.Debugf("Wait file in-sync for %s (%d/%d)", prjID, t, tmo)
300 if sync, err := s.mfolders.IsFolderInSync(prjID); sync || err != nil {
302 s.log.Errorf("ERROR IsFolderInSync (%s): %v", prjID, err)
306 time.Sleep(time.Second)
318 // FIXME replace by .BroadcastTo a room
319 errSoEmit := (*so).Emit(ExecExitEvent, ExecExitMsg{
321 Timestamp: time.Now().String(),
325 if errSoEmit != nil {
326 s.log.Errorf("WS Emit : %v", errSoEmit)
330 // User data (used within callbacks)
331 data := make(map[string]interface{})
333 data["RootPath"] = prj.RootPath
334 data["ClientPath"] = prj.ClientPath
335 data["ExitImmediate"] = args.ExitImmediate
336 if args.TTY && args.TTYGdbserverFix {
337 data["gdbServerTTY"] = "workaround"
339 data["gdbServerTTY"] = ""
341 execWS.UserData = &data
343 // Start command execution
344 s.log.Debugf("Execute [Cmd ID %s]: %v %v", execWS.CmdID, execWS.Cmd, execWS.Args)
348 common.APIError(c, err.Error())
352 c.JSON(http.StatusOK,
355 "cmdID": execWS.CmdID,
359 // ExecCmd executes remotely a command
360 func (s *APIService) execSignalCmd(c *gin.Context) {
361 var args ExecSignalArgs
363 if c.BindJSON(&args) != nil {
364 common.APIError(c, "Invalid arguments")
368 s.log.Debugf("Signal %s for command ID %s", args.Signal, args.CmdID)
370 e := eows.GetEows(args.CmdID)
372 common.APIError(c, "unknown cmdID")
376 err := e.Signal(args.Signal)
378 common.APIError(c, err.Error())
382 c.JSON(http.StatusOK,