Update GOPATH in VSCode project (now in gerrit)
[src/xds/xds-gdb.git] / gdb-xds.go
index 981b977..9dfb717 100644 (file)
@@ -1,3 +1,21 @@
+/*
+ * Copyright (C) 2017-2018 "IoT.bzh"
+ * Author Sebastien Douheret <sebastien@iot.bzh>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
 package main
 
 import (
@@ -5,29 +23,32 @@ import (
        "fmt"
        "os"
        "regexp"
+       "runtime"
        "strconv"
        "strings"
        "syscall"
+       "text/tabwriter"
 
+       "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent.git/lib/xaapiv1"
+       common "gerrit.automotivelinux.org/gerrit/src/xds/xds-common.git/golib"
        "github.com/Sirupsen/logrus"
-       "github.com/iotbzh/xds-agent/lib/xaapiv1"
-       common "github.com/iotbzh/xds-common/golib"
        sio_client "github.com/sebd71/go-socket.io-client"
 )
 
-// GdbXds -
+// GdbXds - Implementation of IGDB used to interfacing XDS
 type GdbXds struct {
-       log     *logrus.Logger
-       ccmd    string
-       aargs   []string
-       eenv    []string
-       uri     string
-       prjID   string
-       sdkID   string
-       rPath   string
-       listPrj bool
-       cmdID   string
-       xGdbPid string
+       log       *logrus.Logger
+       ccmd      string
+       aargs     []string
+       eenv      []string
+       agentURL  string
+       serverURL string
+       prjID     string
+       sdkID     string
+       rPath     string
+       listPrj   bool
+       cmdID     string
+       xGdbPid   string
 
        httpCli *common.HTTPClient
        ioSock  *sio_client.Client
@@ -57,15 +78,21 @@ func NewGdbXds(log *logrus.Logger, args []string, env []string) *GdbXds {
 
 // SetConfig set additional config fields
 func (g *GdbXds) SetConfig(name string, value interface{}) error {
+       var val string
+       if name != "listProject" {
+               val = strings.TrimSpace(value.(string))
+       }
        switch name {
-       case "uri":
-               g.uri = value.(string)
+       case "agentURL":
+               g.agentURL = val
+       case "serverURL":
+               g.serverURL = val
        case "prjID":
-               g.prjID = value.(string)
+               g.prjID = val
        case "sdkID":
-               g.sdkID = value.(string)
+               g.sdkID = val
        case "rPath":
-               g.rPath = value.(string)
+               g.rPath = val
        case "listProject":
                g.listPrj = value.(bool)
        default:
@@ -81,9 +108,15 @@ func (g *GdbXds) Init() (int, error) {
        g.cmdID = ""
 
        // Define HTTP and WS url
-       baseURL := g.uri
-       if !strings.HasPrefix(g.uri, "http://") {
-               baseURL = "http://" + g.uri
+       baseURL := g.agentURL
+
+       // Allow to only set port number
+       if match, _ := regexp.MatchString("^([0-9]+)$", baseURL); match {
+               baseURL = "http://localhost:" + g.agentURL
+       }
+       // Add http prefix if missing
+       if baseURL != "" && !strings.HasPrefix(g.agentURL, "http://") {
+               baseURL = "http://" + g.agentURL
        }
 
        // Create HTTP client
@@ -93,14 +126,22 @@ func (g *GdbXds) Init() (int, error) {
                HeaderClientKeyName: "Xds-Agent-Sid",
                CsrfDisable:         true,
                LogOut:              g.log.Out,
-               LogLevel:            common.HTTPLogLevelWarning,
+               LogPrefix:           "XDSAGENT: ",
+               LogLevel:            common.HTTPLogLevelDebug,
        }
        c, err := common.HTTPNewClient(baseURL, conf)
        if err != nil {
                errmsg := err.Error()
-               if m, err := regexp.MatchString("Get http.?://", errmsg); m && err == nil {
+               m, err := regexp.MatchString("Get http.?://", errmsg)
+               if (m && err == nil) || strings.Contains(errmsg, "Failed to get device ID") {
                        i := strings.LastIndex(errmsg, ":")
-                       errmsg = "Cannot connection to " + baseURL + errmsg[i:]
+                       newErr := "Cannot connection to " + baseURL
+                       if i > 0 {
+                               newErr += " (" + strings.TrimSpace(errmsg[i+1:]) + ")"
+                       } else {
+                               newErr += " (" + strings.TrimSpace(errmsg) + ")"
+                       }
+                       errmsg = newErr
                }
                return int(syscallEBADE), fmt.Errorf(errmsg)
        }
@@ -115,8 +156,25 @@ func (g *GdbXds) Init() (int, error) {
        }
        g.log.Infoln("XDS agent & server version:", ver)
 
-       // SEB Check that server is connected
+       // Get current config and update connection to server when needed
+       xdsConf := xaapiv1.APIConfig{}
+       if err := g.httpCli.Get("/config", &xdsConf); err != nil {
+               return int(syscallEBADE), err
+       }
        // FIXME: add multi-servers support
+       idx := 0
+       svrCfg := xdsConf.Servers[idx]
+       if g.serverURL != "" && (svrCfg.URL != g.serverURL || !svrCfg.Connected) {
+               svrCfg.URL = g.serverURL
+               svrCfg.ConnRetry = 10
+               newCfg := xaapiv1.APIConfig{}
+               if err := g.httpCli.Post("/config", xdsConf, &newCfg); err != nil {
+                       return int(syscallEBADE), err
+               }
+
+       } else if !svrCfg.Connected {
+               return int(syscallEBADE), fmt.Errorf("XDS server not connected (url=%s)", svrCfg.URL)
+       }
 
        // Get XDS projects list
        var data []byte
@@ -164,9 +222,29 @@ func (g *GdbXds) Init() (int, error) {
                }
        })
 
+       // SEB gdbPid := ""
        iosk.On(xaapiv1.ExecOutEvent, func(ev xaapiv1.ExecOutMsg) {
                if g.cbRead != nil {
                        g.cbRead(ev.Timestamp, ev.Stdout, ev.Stderr)
+                       /*
+                               stdout := ev.Stdout
+                               // SEB
+                               //New Thread 15139
+                               if strings.Contains(stdout, "pid = ") {
+                                       re := regexp.MustCompile("pid = ([0-9]+)")
+                                       if res := re.FindAllStringSubmatch(stdout, -1); len(res) > 0 {
+                                               gdbPid = res[0][1]
+                                       }
+                                       g.log.Errorf("SEB FOUND THREAD in '%s' => gdbPid=%s", stdout, gdbPid)
+                               }
+                               if gdbPid != "" && g.xGdbPid != "" && strings.Contains(stdout, gdbPid) {
+                                       g.log.Errorf("SEB THREAD REPLACE 1 stdout=%s", stdout)
+                                       stdout = strings.Replace(stdout, gdbPid, g.xGdbPid, -1)
+                                       g.log.Errorf("SEB THREAD REPLACE 2 stdout=%s", stdout)
+                               }
+
+                               g.cbRead(ev.Timestamp, stdout, ev.Stderr)
+                       */
                }
        })
 
@@ -182,6 +260,25 @@ func (g *GdbXds) Init() (int, error) {
                }
        })
 
+       // Monitor XDS server configuration changes (and specifically connected status)
+       iosk.On(xaapiv1.EVTServerConfig, func(ev xaapiv1.EventMsg) {
+               svrCfg, err := ev.DecodeServerCfg()
+               if err == nil && !svrCfg.Connected {
+                       // TODO: should wait that server will be connected back
+                       if g.cbOnExit != nil {
+                               g.cbOnExit(-1, fmt.Errorf("XDS Server disconnected"))
+                       } else {
+                               fmt.Printf("XDS Server disconnected")
+                               os.Exit(-1)
+                       }
+               }
+       })
+
+       args := xaapiv1.EventRegisterArgs{Name: xaapiv1.EVTServerConfig}
+       if err := g.httpCli.Post("/events/register", args, nil); err != nil {
+               return 0, err
+       }
+
        return 0, nil
 }
 
@@ -231,6 +328,11 @@ func (g *GdbXds) Start(inferiorTTY bool) (int, error) {
        // except if XDS_GDBSERVER_OUTPUT_NOFIX is defined
        _, gdbserverNoFix := os.LookupEnv("XDS_GDBSERVER_OUTPUT_NOFIX")
 
+       // SDK ID must be set else $GDB cannot be resolved
+       if g.sdkID == "" {
+               return int(syscall.EINVAL), fmt.Errorf("sdkid must be set")
+       }
+
        args := xaapiv1.ExecArgs{
                ID:              g.prjID,
                SdkID:           g.sdkID,
@@ -243,7 +345,7 @@ func (g *GdbXds) Start(inferiorTTY bool) (int, error) {
                CmdTimeout:      -1, // no timeout, end when stdin close or command exited normally
        }
 
-       g.log.Infof("POST %s/exec %v", g.uri, args)
+       g.log.Infof("POST %s/exec %v", g.agentURL, args)
        res := xaapiv1.ExecResult{}
        err = g.httpCli.Post("/exec", args, &res)
        if err != nil {
@@ -319,17 +421,15 @@ func (g *GdbXds) SendSignal(sig os.Signal) error {
 //***** Private functions *****
 
 func (g *GdbXds) printProjectsList() (int, error) {
+       writer := new(tabwriter.Writer)
+       writer.Init(os.Stdout, 0, 8, 0, '\t', 0)
        msg := ""
        if len(g.projects) > 0 {
-               msg += "List of existing projects (use: export XDS_PROJECT_ID=<< ID >>): \n"
-               msg += "  ID\t\t\t\t | Label"
+               fmt.Fprintln(writer, "List of existing projects (use: export XDS_PROJECT_ID=<< ID >>):")
+               fmt.Fprintln(writer, "ID \t Label")
                for _, f := range g.projects {
-                       msg += fmt.Sprintf("\n  %s\t | %s", f.ID, f.Label)
-                       if f.DefaultSdk != "" {
-                               msg += fmt.Sprintf("\t(default SDK: %s)", f.DefaultSdk)
-                       }
+                       fmt.Fprintf(writer, " %s \t  %s\n", f.ID, f.Label)
                }
-               msg += "\n"
        }
 
        // FIXME : support multiple servers
@@ -337,18 +437,28 @@ func (g *GdbXds) printProjectsList() (int, error) {
        if err := g.httpCli.Get("/servers/0/sdks", &sdks); err != nil {
                return int(syscallEBADE), err
        }
-       msg += "\nList of installed cross SDKs (use: export XDS_SDK_ID=<< ID >>): \n"
-       msg += "  ID\t\t\t\t\t | NAME\n"
+       fmt.Fprintln(writer, "\nList of installed cross SDKs (use: export XDS_SDK_ID=<< ID >>):")
+       fmt.Fprintln(writer, "ID \t Name")
        for _, s := range sdks {
-               msg += fmt.Sprintf("  %s\t | %s\n", s.ID, s.Name)
+               if s.Status == xaapiv1.SdkStatusInstalled {
+                       fmt.Fprintf(writer, " %s \t  %s\n", s.ID, s.Name)
+               }
        }
 
        if len(g.projects) > 0 && len(sdks) > 0 {
-               msg += fmt.Sprintf("\n")
-               msg += fmt.Sprintf("For example: \n")
-               msg += fmt.Sprintf("  XDS_PROJECT_ID=%q XDS_SDK_ID=%q  %s -x myGdbConf.ini\n",
-                       g.projects[0].ID, sdks[0].ID, AppName)
+               fmt.Fprintln(writer, "")
+               fmt.Fprintln(writer, "For example: ")
+               if runtime.GOOS == "windows" {
+                       fmt.Fprintf(writer, "  SET XDS_PROJECT_ID=%s && SET XDS_SDK_ID=%s &&  %s -x myGdbConf.ini\n",
+                               g.projects[0].ID[:8], sdks[0].ID[:8], AppName)
+               } else {
+                       fmt.Fprintf(writer, "  XDS_PROJECT_ID=%s XDS_SDK_ID=%s  %s -x myGdbConf.ini\n",
+                               g.projects[0].ID[:8], sdks[0].ID[:8], AppName)
+               }
        }
+       fmt.Fprintln(writer, "")
+       fmt.Fprintln(writer, "Or define settings within gdb configuration file (see help and :XDS-ENV: tag)")
+       writer.Flush()
 
        return 0, fmt.Errorf(msg)
 }