Add stdin support to /exec
[src/xds/xds-server.git] / lib / apiv1 / exec.go
index 895807d..ce0241a 100644 (file)
@@ -6,19 +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" 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
-       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
@@ -37,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"
 
@@ -84,14 +93,26 @@ 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, data *map[string]interface{}) {
+       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 {
@@ -109,9 +130,11 @@ func (s *APIService) execCmd(c *gin.Context) {
 
                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,
@@ -122,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
@@ -132,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,
@@ -144,7 +191,7 @@ func (s *APIService) execCmd(c *gin.Context) {
                }
        }
 
-       cmdID := execCommandID
+       cmdID := strconv.Itoa(execCommandID)
        execCommandID++
        cmd := []string{}
 
@@ -152,6 +199,12 @@ func (s *APIService) execCmd(c *gin.Context) {
        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 = append(cmd, "cd", prj.GetFullPath(args.RPath), "&&", args.Cmd)
@@ -159,11 +212,18 @@ func (s *APIService) execCmd(c *gin.Context) {
                cmd = append(cmd, args.Args...)
        }
 
-       s.log.Debugf("Execute [Cmd ID %d]: %v", cmdID, cmd)
+       // 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 {
@@ -177,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",
+               })
+}