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 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
34 // ExecInMsg Message used to received input characters (stdin)
36 CmdID string `json:"cmdID"`
37 Timestamp string `json:"timestamp"`
38 Stdin string `json:"stdin"`
41 // ExecOutMsg Message used to send output characters (stdout+stderr)
43 CmdID string `json:"cmdID"`
44 Timestamp string `json:"timestamp"`
45 Stdout string `json:"stdout"`
46 Stderr string `json:"stderr"`
49 // ExecExitMsg Message sent when executed command exited
51 CmdID string `json:"cmdID"`
52 Timestamp string `json:"timestamp"`
53 Code int `json:"code"`
54 Error error `json:"error"`
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
65 // ExecInEvent Event send in WS when characters are sent (stdin)
66 ExecInEvent = "exec:input"
68 // ExecOutEvent Event send in WS when characters are received (stdout or stderr)
69 ExecOutEvent = "exec:output"
71 // ExecExitEvent Event send in WS when program exited
72 ExecExitEvent = "exec:exit"
74 // ExecInferiorInEvent Event send in WS when characters are sent to an inferior (used by gdb inferior/tty)
75 ExecInferiorInEvent = "exec:inferior-input"
77 // ExecInferiorOutEvent Event send in WS when characters are received by an inferior
78 ExecInferiorOutEvent = "exec:inferior-output"
83 // ExecCmd executes remotely a command
84 func (s *APIService) execCmd(c *gin.Context) {
85 var gdbPty, gdbTty *os.File
88 if c.BindJSON(&args) != nil {
89 common.APIError(c, "Invalid arguments")
93 // TODO: add permission ?
95 // Retrieve session info
96 sess := s.sessions.Get(c)
98 common.APIError(c, "Unknown sessions")
103 common.APIError(c, "Websocket not established")
107 // Allow to pass id in url (/exec/:id) or as JSON argument
113 common.APIError(c, "Invalid id")
117 f := s.mfolders.Get(id)
119 common.APIError(c, "Unknown id")
123 prj := fld.GetConfig()
125 // Build command line
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, "&&")
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")
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)
147 // Process command arguments
148 cmdArgs := make([]string, len(args.Args)+1)
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))
155 cmdArgs = append(cmdArgs, aa)
159 // Allocate pts if tty if used
161 gdbPty, gdbTty, err = pty.Open()
163 common.APIError(c, err.Error())
167 s.log.Debugf("Client command tty: %v %v\n", gdbTty.Name(), gdbTty.Name())
168 cmdArgs = append(cmdArgs, "--tty="+gdbTty.Name())
171 // Unique ID for each commands
172 if args.CmdID == "" {
173 args.CmdID = s.cfg.ServerUID[:18] + "_" + strconv.Itoa(execCommandID)
177 // Create new execution over WS context
178 execWS := eows.New(strings.Join(cmd, " "), cmdArgs, sop, sess.ID, args.CmdID)
181 // Append client project dir to environment
182 execWS.Env = append(args.Env, "CLIENT_PROJECT_DIR="+prj.ClientPath)
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
190 execWS.CmdExecTimeout = args.CmdTimeout
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))
199 if len(stdin) == 1 && stdin == "\x04" {
201 errMsg := fmt.Errorf("close stdin: %v", stdin)
207 prjID := (*data)["ID"].(string)
208 f := s.mfolders.Get(prjID)
210 s.log.Errorf("InputCB: Cannot get folder ID %s", prjID)
212 // Translate paths from client to server
213 stdin = (*f).ConvPathCli2Svr(stdin)
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)
224 s.log.Infof("%s not emitted: WS closed (sid:%s, msgid:%s)", ExecOutEvent, e.Sid, e.CmdID)
228 // Retrieve project ID and RootPath
230 prjID := (*data)["ID"].(string)
231 gdbServerTTY := (*data)["gdbServerTTY"].(string)
233 f := s.mfolders.Get(prjID)
235 s.log.Errorf("OutputCB: Cannot get folder ID %s", prjID)
237 // Translate paths from server to client
238 stdout = (*f).ConvPathSvr2Cli(stdout)
239 stderr = (*f).ConvPathSvr2Cli(stderr)
242 s.log.Debugf("%s emitted - WS sid[4:] %s - id:%s - prjID:%s", ExecOutEvent, e.Sid[4:], e.CmdID, prjID)
244 s.log.Debugf("STDOUT <<%v>>", strings.Replace(stdout, "\n", "\\n", -1))
247 s.log.Debugf("STDERR <<%v>>", strings.Replace(stderr, "\n", "\\n", -1))
250 // FIXME replace by .BroadcastTo a room
251 err := (*so).Emit(ExecOutEvent, ExecOutMsg{
253 Timestamp: time.Now().String(),
258 s.log.Errorf("WS Emit : %v", err)
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] == '&' {
265 // Extract and cleanup string like &"bla bla\n"
266 re := regexp.MustCompile("&\"(.*)\"")
267 rer := re.FindAllStringSubmatch(stdout, -1)
269 if rer != nil && len(rer) > 0 {
270 for _, o := range rer {
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)
276 s.log.Debugf("STDOUT INFERIOR: <<%v>>", out)
277 err := (*so).Emit(ExecInferiorOutEvent, ExecOutMsg{
279 Timestamp: time.Now().String(),
284 s.log.Errorf("WS Emit : %v", err)
289 s.log.Errorf("INFERIOR out parsing error: stdout=<%v>", stdout)
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)
298 // IO socket can be nil when disconnected
299 so := s.sessions.IOSocketGet(e.Sid)
301 s.log.Infof("%s not emitted - WS closed (id:%s)", ExecExitEvent, e.CmdID)
305 // Retrieve project ID and RootPath
307 prjID := (*data)["ID"].(string)
308 exitImm := (*data)["ExitImmediate"].(bool)
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)
315 // Wait end of file sync
316 // FIXME pass as argument
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 {
322 s.log.Errorf("ERROR IsFolderInSync (%s): %v", prjID, err)
326 time.Sleep(time.Second)
338 // FIXME replace by .BroadcastTo a room
339 errSoEmit := (*so).Emit(ExecExitEvent, ExecExitMsg{
341 Timestamp: time.Now().String(),
345 if errSoEmit != nil {
346 s.log.Errorf("WS Emit : %v", errSoEmit)
350 // User data (used within callbacks)
351 data := make(map[string]interface{})
353 data["ExitImmediate"] = args.ExitImmediate
354 if args.TTY && args.TTYGdbserverFix {
355 data["gdbServerTTY"] = "workaround"
357 data["gdbServerTTY"] = ""
359 execWS.UserData = &data
361 // Start command execution
362 s.log.Infof("Execute [Cmd ID %s]: %v %v", execWS.CmdID, execWS.Cmd, execWS.Args)
366 common.APIError(c, err.Error())
370 c.JSON(http.StatusOK,
373 "cmdID": execWS.CmdID,
377 // ExecCmd executes remotely a command
378 func (s *APIService) execSignalCmd(c *gin.Context) {
379 var args ExecSignalArgs
381 if c.BindJSON(&args) != nil {
382 common.APIError(c, "Invalid arguments")
386 s.log.Debugf("Signal %s for command ID %s", args.Signal, args.CmdID)
388 e := eows.GetEows(args.CmdID)
390 common.APIError(c, "unknown cmdID")
394 err := e.Signal(args.Signal)
396 common.APIError(c, err.Error())
400 c.JSON(http.StatusOK,