2 * Copyright (C) 2017 "IoT.bzh"
3 * Author Sebastien Douheret <sebastien@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
31 "github.com/Sirupsen/logrus"
32 "github.com/iotbzh/xds-agent/lib/xaapiv1"
33 common "github.com/iotbzh/xds-common/golib"
34 sio_client "github.com/sebd71/go-socket.io-client"
37 // GdbXds - Implementation of IGDB used to interfacing XDS
52 httpCli *common.HTTPClient
53 ioSock *sio_client.Client
55 projects []xaapiv1.ProjectConfig
59 cbOnDisconnect func(error)
60 cbRead func(timestamp, stdout, stderr string)
61 cbInferiorRead func(timestamp, stdout, stderr string)
62 cbOnExit func(code int, err error)
65 // NewGdbXds creates a new instance of GdbXds
66 func NewGdbXds(log *logrus.Logger, args []string, env []string) *GdbXds {
69 ccmd: "exec $GDB", // var set by environment-setup-xxx script
74 xGdbPid: strconv.Itoa(os.Getpid()),
78 // SetConfig set additional config fields
79 func (g *GdbXds) SetConfig(name string, value interface{}) error {
82 g.agentURL = value.(string)
84 g.serverURL = value.(string)
86 g.prjID = value.(string)
88 g.sdkID = value.(string)
90 g.rPath = value.(string)
92 g.listPrj = value.(bool)
94 return fmt.Errorf("Unknown %s field", name)
99 // Init initializes gdb XDS
100 func (g *GdbXds) Init() (int, error) {
102 // Reset command ID (also used to enable sending of signals)
105 // Define HTTP and WS url
106 baseURL := g.agentURL
108 // Allow to only set port number
109 if match, _ := regexp.MatchString("^([0-9]+)$", baseURL); match {
110 baseURL = "http://localhost:" + g.agentURL
112 // Add http prefix if missing
113 if baseURL != "" && !strings.HasPrefix(g.agentURL, "http://") {
114 baseURL = "http://" + g.agentURL
117 // Create HTTP client
118 g.log.Infoln("Connect HTTP client on ", baseURL)
119 conf := common.HTTPClientConfig{
120 URLPrefix: "/api/v1",
121 HeaderClientKeyName: "Xds-Agent-Sid",
124 LogPrefix: "XDSAGENT: ",
125 LogLevel: common.HTTPLogLevelDebug,
127 c, err := common.HTTPNewClient(baseURL, conf)
129 errmsg := err.Error()
130 m, err := regexp.MatchString("Get http.?://", errmsg)
131 if (m && err == nil) || strings.Contains(errmsg, "Failed to get device ID") {
132 i := strings.LastIndex(errmsg, ":")
133 newErr := "Cannot connection to " + baseURL
135 newErr += " (" + strings.TrimSpace(errmsg[i+1:]) + ")"
137 newErr += " (" + strings.TrimSpace(errmsg) + ")"
141 return int(syscallEBADE), fmt.Errorf(errmsg)
144 g.httpCli.SetLogLevel(g.log.Level.String())
145 g.log.Infoln("HTTP session ID:", g.httpCli.GetClientID())
147 // First call to check that xds-agent and server are alive
148 ver := xaapiv1.XDSVersion{}
149 if err := g.httpCli.Get("/version", &ver); err != nil {
150 return int(syscallEBADE), err
152 g.log.Infoln("XDS agent & server version:", ver)
154 // Get current config and update connection to server when needed
155 xdsConf := xaapiv1.APIConfig{}
156 if err := g.httpCli.Get("/config", &xdsConf); err != nil {
157 return int(syscallEBADE), err
159 // FIXME: add multi-servers support
161 svrCfg := xdsConf.Servers[idx]
162 if g.serverURL != "" && (svrCfg.URL != g.serverURL || !svrCfg.Connected) {
163 svrCfg.URL = g.serverURL
164 svrCfg.ConnRetry = 10
165 newCfg := xaapiv1.APIConfig{}
166 if err := g.httpCli.Post("/config", xdsConf, &newCfg); err != nil {
167 return int(syscallEBADE), err
170 } else if !svrCfg.Connected {
171 return int(syscallEBADE), fmt.Errorf("XDS server not connected (url=%s)", svrCfg.URL)
174 // Get XDS projects list
176 if err := g.httpCli.HTTPGet("/projects", &data); err != nil {
177 return int(syscallEBADE), err
180 g.log.Infof("Result of /projects: %v", string(data[:]))
181 g.projects = []xaapiv1.ProjectConfig{}
182 errMar := json.Unmarshal(data, &g.projects)
184 g.log.Errorf("Cannot decode projects configuration: %s", errMar.Error())
187 // Check mandatory args
188 if g.prjID == "" || g.listPrj {
189 return g.printProjectsList()
192 // Create io Websocket client
193 g.log.Infoln("Connecting IO.socket client on ", baseURL)
195 opts := &sio_client.Options{
196 Transport: "websocket",
197 Header: make(map[string][]string),
199 opts.Header["XDS-AGENT-SID"] = []string{c.GetClientID()}
201 iosk, err := sio_client.NewClient(baseURL, opts)
203 e := fmt.Sprintf("IO.socket connection error: " + err.Error())
204 return int(syscall.ECONNABORTED), fmt.Errorf(e)
208 iosk.On("error", func(err error) {
209 if g.cbOnError != nil {
214 iosk.On("disconnection", func(err error) {
215 if g.cbOnDisconnect != nil {
216 g.cbOnDisconnect(err)
221 iosk.On(xaapiv1.ExecOutEvent, func(ev xaapiv1.ExecOutMsg) {
223 g.cbRead(ev.Timestamp, ev.Stdout, ev.Stderr)
228 if strings.Contains(stdout, "pid = ") {
229 re := regexp.MustCompile("pid = ([0-9]+)")
230 if res := re.FindAllStringSubmatch(stdout, -1); len(res) > 0 {
233 g.log.Errorf("SEB FOUND THREAD in '%s' => gdbPid=%s", stdout, gdbPid)
235 if gdbPid != "" && g.xGdbPid != "" && strings.Contains(stdout, gdbPid) {
236 g.log.Errorf("SEB THREAD REPLACE 1 stdout=%s", stdout)
237 stdout = strings.Replace(stdout, gdbPid, g.xGdbPid, -1)
238 g.log.Errorf("SEB THREAD REPLACE 2 stdout=%s", stdout)
241 g.cbRead(ev.Timestamp, stdout, ev.Stderr)
246 iosk.On(xaapiv1.ExecInferiorOutEvent, func(ev xaapiv1.ExecOutMsg) {
247 if g.cbInferiorRead != nil {
248 g.cbInferiorRead(ev.Timestamp, ev.Stdout, ev.Stderr)
252 iosk.On(xaapiv1.ExecExitEvent, func(ev xaapiv1.ExecExitMsg) {
253 if g.cbOnExit != nil {
254 g.cbOnExit(ev.Code, ev.Error)
258 // Monitor XDS server configuration changes (and specifically connected status)
259 iosk.On(xaapiv1.EVTServerConfig, func(ev xaapiv1.EventMsg) {
260 svrCfg, err := ev.DecodeServerCfg()
261 if err == nil && !svrCfg.Connected {
262 // TODO: should wait that server will be connected back
263 if g.cbOnExit != nil {
264 g.cbOnExit(-1, fmt.Errorf("XDS Server disconnected"))
266 fmt.Printf("XDS Server disconnected")
272 args := xaapiv1.EventRegisterArgs{Name: xaapiv1.EVTServerConfig}
273 if err := g.httpCli.Post("/events/register", args, nil); err != nil {
280 // Close frees allocated objects and close opened connections
281 func (g *GdbXds) Close() error {
282 g.cbOnDisconnect = nil
286 g.cbInferiorRead = nil
292 // Start sends a request to start remotely gdb within xds-server
293 func (g *GdbXds) Start(inferiorTTY bool) (int, error) {
295 var project *xaapiv1.ProjectConfig
297 // Retrieve the project definition
298 for _, f := range g.projects {
299 // check as prefix to support short/partial id name
300 if strings.HasPrefix(f.ID, g.prjID) {
306 // Auto setup rPath if needed
307 if g.rPath == "" && project != nil {
308 cwd, err := os.Getwd()
310 fldRp := project.ClientPath
311 if !strings.HasPrefix(fldRp, "/") {
314 log.Debugf("Try to auto-setup rPath: cwd=%s ; ClientPath=%s", cwd, fldRp)
315 if sp := strings.SplitAfter(cwd, fldRp); len(sp) == 2 {
316 g.rPath = strings.Trim(sp[1], "/")
317 g.log.Debugf("Auto-setup rPath to: '%s'", g.rPath)
322 // Enable workaround about inferior output with gdbserver connection
323 // except if XDS_GDBSERVER_OUTPUT_NOFIX is defined
324 _, gdbserverNoFix := os.LookupEnv("XDS_GDBSERVER_OUTPUT_NOFIX")
326 // SDK ID must be set else $GDB cannot be resolved
328 return int(syscall.EINVAL), fmt.Errorf("sdkid must be set")
331 args := xaapiv1.ExecArgs{
339 TTYGdbserverFix: !gdbserverNoFix,
340 CmdTimeout: -1, // no timeout, end when stdin close or command exited normally
343 g.log.Infof("POST %s/exec %v", g.agentURL, args)
344 res := xaapiv1.ExecResult{}
345 err = g.httpCli.Post("/exec", args, &res)
347 return int(syscall.EAGAIN), err
350 return int(syscallEBADE), fmt.Errorf("null CmdID")
357 // Cmd returns the command name
358 func (g *GdbXds) Cmd() string {
362 // Args returns the list of arguments
363 func (g *GdbXds) Args() []string {
367 // Env returns the list of environment variables
368 func (g *GdbXds) Env() []string {
372 // OnError is called on a WebSocket error
373 func (g *GdbXds) OnError(f func(error)) {
377 // OnDisconnect is called when WebSocket disconnection
378 func (g *GdbXds) OnDisconnect(f func(error)) {
382 // OnExit calls when exit event is received
383 func (g *GdbXds) OnExit(f func(code int, err error)) {
387 // Read calls when a message/string event is received on stdout or stderr
388 func (g *GdbXds) Read(f func(timestamp, stdout, stderr string)) {
392 // InferiorRead calls when a message/string event is received on stdout or stderr of the debugged program (IOW inferior)
393 func (g *GdbXds) InferiorRead(f func(timestamp, stdout, stderr string)) {
397 // Write writes message/string into gdb stdin
398 func (g *GdbXds) Write(args ...interface{}) error {
399 return g.ioSock.Emit(xaapiv1.ExecInEvent, args...)
402 // SendSignal is used to send a signal to remote process/gdb
403 func (g *GdbXds) SendSignal(sig os.Signal) error {
405 return fmt.Errorf("cmdID not set")
408 sigArg := xaapiv1.ExecSignalArgs{
410 Signal: sig.String(),
412 g.log.Debugf("POST /signal %v", sigArg)
413 return g.httpCli.Post("/signal", sigArg, nil)
416 //***** Private functions *****
418 func (g *GdbXds) printProjectsList() (int, error) {
419 writer := new(tabwriter.Writer)
420 writer.Init(os.Stdout, 0, 8, 0, '\t', 0)
422 if len(g.projects) > 0 {
423 fmt.Fprintln(writer, "List of existing projects (use: export XDS_PROJECT_ID=<< ID >>):")
424 fmt.Fprintln(writer, "ID \t Label")
425 for _, f := range g.projects {
426 fmt.Fprintf(writer, " %s \t %s\n", f.ID, f.Label)
430 // FIXME : support multiple servers
431 sdks := []xaapiv1.SDK{}
432 if err := g.httpCli.Get("/servers/0/sdks", &sdks); err != nil {
433 return int(syscallEBADE), err
435 fmt.Fprintln(writer, "\nList of installed cross SDKs (use: export XDS_SDK_ID=<< ID >>):")
436 fmt.Fprintln(writer, "ID \t Name")
437 for _, s := range sdks {
438 fmt.Fprintf(writer, " %s \t %s\n", s.ID, s.Name)
441 if len(g.projects) > 0 && len(sdks) > 0 {
442 fmt.Fprintln(writer, "")
443 fmt.Fprintln(writer, "For example: ")
444 fmt.Fprintf(writer, " XDS_PROJECT_ID=%s XDS_SDK_ID=%s %s -x myGdbConf.ini\n",
445 g.projects[0].ID[:8], sdks[0].ID[:8], AppName)
447 fmt.Fprintln(writer, "")
448 fmt.Fprintln(writer, "Or define settings within gdb configuration file (see help and :XDS-ENV: tag)")
451 return 0, fmt.Errorf(msg)