Add stdin support to /exec
[src/xds/xds-server.git] / lib / apiv1 / exec.go
index 18fdc7e..ce0241a 100644 (file)
@@ -6,17 +6,22 @@ import (
        "strings"
        "time"
 
+       "fmt"
+
        "github.com/gin-gonic/gin"
-       "github.com/iotbzh/xds-server/lib/common"
+       common "github.com/iotbzh/xds-common/golib"
 )
 
 // ExecArgs JSON parameters of /exec command
 type ExecArgs struct {
-       ID         string   `json:"id"`
-       RPath      string   `json:"rpath"` // relative path into project
-       Cmd        string   `json:"cmd" binding:"required"`
-       Args       []string `json:"args"`
-       CmdTimeout int      `json:"timeout"` // command completion timeout in Second
+       ID            string   `json:"id" binding:"required"`
+       SdkID         string   `json:"sdkid"` // sdk ID to use for setting env
+       Cmd           string   `json:"cmd" binding:"required"`
+       Args          []string `json:"args"`
+       Env           []string `json:"env"`
+       RPath         string   `json:"rpath"`         // relative path into project
+       ExitImmediate bool     `json:"exitImmediate"` // when true, exit event sent immediately when command exited (IOW, don't wait file synchronization)
+       CmdTimeout    int      `json:"timeout"`       // command completion timeout in Second
 }
 
 // ExecOutMsg Message send on each output (stdout+stderr) of executed command
@@ -35,6 +40,12 @@ type ExecExitMsg struct {
        Error     error  `json:"error"`
 }
 
+// ExecSignalArgs JSON parameters of /exec/signal command
+type ExecSignalArgs struct {
+       CmdID  string `json:"cmdID" binding:"required"`  // command id
+       Signal string `json:"signal" binding:"required"` // signal number
+}
+
 // ExecOutEvent Event send in WS when characters are received
 const ExecOutEvent = "exec:output"
 
@@ -51,7 +62,7 @@ func (s *APIService) execCmd(c *gin.Context) {
                return
        }
 
-       // TODO: add permission
+       // TODO: add permission ?
 
        // Retrieve session info
        sess := s.sessions.Get(c)
@@ -82,25 +93,48 @@ func (s *APIService) execCmd(c *gin.Context) {
        }
 
        execTmo := args.CmdTimeout
-       if execTmo == 0 {
+       if execTmo == -1 {
+               // -1 : no timeout
+               execTmo = 365 * 24 * 60 * 60 // 1 year == no timeout
+       } else if execTmo == 0 {
+               // 0 : default timeout
                // TODO get default timeout from config.json file
                execTmo = 24 * 60 * 60 // 1 day
        }
 
+       // Define callback for input
+       /* SEB TODO
+       var iCB common.OnInputCB
+       iCB = func() {
+
+       }
+       */
+
        // Define callback for output
        var oCB common.EmitOutputCB
-       oCB = func(sid string, id int, stdout, stderr string) {
+       oCB = func(sid string, id string, stdout, stderr string, data *map[string]interface{}) {
                // IO socket can be nil when disconnected
                so := s.sessions.IOSocketGet(sid)
                if so == nil {
                        s.log.Infof("%s not emitted: WS closed - sid: %s - msg id:%d", ExecOutEvent, sid, id)
                        return
                }
-               s.log.Debugf("%s emitted - WS sid %s - id:%d", ExecOutEvent, sid, id)
+
+               // Retrieve project ID and RootPath
+               prjID := (*data)["ID"].(string)
+               prjRootPath := (*data)["RootPath"].(string)
+
+               // Cleanup any references to internal rootpath in stdout & stderr
+               stdout = strings.Replace(stdout, prjRootPath, "", -1)
+               stderr = strings.Replace(stderr, prjRootPath, "", -1)
+
+               s.log.Debugf("%s emitted - WS sid %s - id:%d - prjID:%s", ExecOutEvent, sid, id, prjID)
+
+               fmt.Printf("SEB SEND out <%v>, err <%v>\n", stdout, stderr)
 
                // FIXME replace by .BroadcastTo a room
                err := (*so).Emit(ExecOutEvent, ExecOutMsg{
-                       CmdID:     strconv.Itoa(id),
+                       CmdID:     id,
                        Timestamp: time.Now().String(),
                        Stdout:    stdout,
                        Stderr:    stderr,
@@ -111,7 +145,7 @@ func (s *APIService) execCmd(c *gin.Context) {
        }
 
        // Define callback for output
-       eCB := func(sid string, id int, code int, err error) {
+       eCB := func(sid string, id string, code int, err error, data *map[string]interface{}) {
                s.log.Debugf("Command [Cmd ID %d] exited: code %d, error: %v", id, code, err)
 
                // IO socket can be nil when disconnected
@@ -121,9 +155,33 @@ func (s *APIService) execCmd(c *gin.Context) {
                        return
                }
 
+               // Retrieve project ID and RootPath
+               prjID := (*data)["ID"].(string)
+               exitImm := (*data)["ExitImmediate"].(bool)
+
+               // XXX - workaround to be sure that Syncthing detected all changes
+               if err := s.mfolder.ForceSync(prjID); err != nil {
+                       s.log.Errorf("Error while syncing folder %s: %v", prjID, err)
+               }
+               if !exitImm {
+                       // Wait end of file sync
+                       // FIXME pass as argument
+                       tmo := 60
+                       for t := tmo; t > 0; t-- {
+                               s.log.Debugf("Wait file insync for %s (%d/%d)", prjID, t, tmo)
+                               if sync, err := s.mfolder.IsFolderInSync(prjID); sync || err != nil {
+                                       if err != nil {
+                                               s.log.Errorf("ERROR IsFolderInSync (%s): %v", prjID, err)
+                                       }
+                                       break
+                               }
+                               time.Sleep(time.Second)
+                       }
+               }
+
                // FIXME replace by .BroadcastTo a room
                e := (*so).Emit(ExecExitEvent, ExecExitMsg{
-                       CmdID:     strconv.Itoa(id),
+                       CmdID:     id,
                        Timestamp: time.Now().String(),
                        Code:      code,
                        Error:     err,
@@ -133,16 +191,41 @@ func (s *APIService) execCmd(c *gin.Context) {
                }
        }
 
-       cmdID := execCommandID
+       cmdID := strconv.Itoa(execCommandID)
        execCommandID++
+       cmd := []string{}
+
+       // Setup env var regarding Sdk ID (used for example to setup cross toolchain)
+       if envCmd := s.sdks.GetEnvCmd(args.SdkID, prj.DefaultSdk); len(envCmd) > 0 {
+               cmd = append(cmd, envCmd...)
+               cmd = append(cmd, "&&")
+       } else {
+               // It's an error if no envcmd found while a sdkid has been provided
+               if args.SdkID != "" {
+                       common.APIError(c, "Unknown sdkid")
+                       return
+               }
+       }
 
-       cmd := "cd " + prj.GetFullPath(args.RPath) + " && " + args.Cmd
+       cmd = append(cmd, "cd", prj.GetFullPath(args.RPath), "&&", args.Cmd)
        if len(args.Args) > 0 {
-               cmd += " " + strings.Join(args.Args, " ")
+               cmd = append(cmd, args.Args...)
        }
 
-       s.log.Debugf("Execute [Cmd ID %d]: %v %v", cmdID, cmd)
-       err := common.ExecPipeWs(cmd, sop, sess.ID, cmdID, execTmo, s.log, oCB, eCB)
+       // SEB Workaround for stderr issue (order not respected with stdout)
+       cmd = append(cmd, " 2>&1")
+
+       // Append client project dir to environment
+       args.Env = append(args.Env, "CLIENT_PROJECT_DIR="+prj.RelativePath)
+
+       s.log.Debugf("Execute [Cmd ID %s]: %v", cmdID, cmd)
+
+       data := make(map[string]interface{})
+       data["ID"] = prj.ID
+       data["RootPath"] = prj.RootPath
+       data["ExitImmediate"] = args.ExitImmediate
+
+       err := common.ExecPipeWs(cmd, args.Env, sop, sess.ID, cmdID, execTmo, s.log, oCB, eCB, &data)
        if err != nil {
                common.APIError(c, err.Error())
                return
@@ -154,3 +237,25 @@ func (s *APIService) execCmd(c *gin.Context) {
                        "cmdID":  cmdID,
                })
 }
+
+// ExecCmd executes remotely a command
+func (s *APIService) execSignalCmd(c *gin.Context) {
+       var args ExecSignalArgs
+
+       if c.BindJSON(&args) != nil {
+               common.APIError(c, "Invalid arguments")
+               return
+       }
+
+       s.log.Debugf("Signal %s for command ID %s", args.Signal, args.CmdID)
+       err := common.ExecSignal(args.CmdID, args.Signal)
+       if err != nil {
+               common.APIError(c, err.Error())
+               return
+       }
+
+       c.JSON(http.StatusOK,
+               gin.H{
+                       "status": "OK",
+               })
+}