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.
30 "github.com/Sirupsen/logrus"
31 "github.com/iotbzh/xds-agent/lib/xaapiv1"
32 common "github.com/iotbzh/xds-common/golib"
33 sio_client "github.com/sebd71/go-socket.io-client"
36 // GdbXds - Implementation of IGDB used to interfacing XDS
51 httpCli *common.HTTPClient
52 ioSock *sio_client.Client
54 projects []xaapiv1.ProjectConfig
58 cbOnDisconnect func(error)
59 cbRead func(timestamp, stdout, stderr string)
60 cbInferiorRead func(timestamp, stdout, stderr string)
61 cbOnExit func(code int, err error)
64 // NewGdbXds creates a new instance of GdbXds
65 func NewGdbXds(log *logrus.Logger, args []string, env []string) *GdbXds {
68 ccmd: "exec $GDB", // var set by environment-setup-xxx script
73 xGdbPid: strconv.Itoa(os.Getpid()),
77 // SetConfig set additional config fields
78 func (g *GdbXds) SetConfig(name string, value interface{}) error {
81 g.agentURL = value.(string)
83 g.serverURL = value.(string)
85 g.prjID = value.(string)
87 g.sdkID = value.(string)
89 g.rPath = value.(string)
91 g.listPrj = value.(bool)
93 return fmt.Errorf("Unknown %s field", name)
98 // Init initializes gdb XDS
99 func (g *GdbXds) Init() (int, error) {
101 // Reset command ID (also used to enable sending of signals)
104 // Define HTTP and WS url
105 baseURL := g.agentURL
107 // Allow to only set port number
108 if match, _ := regexp.MatchString("^([0-9]+)$", baseURL); match {
109 baseURL = "http://localhost:" + g.agentURL
111 // Add http prefix if missing
112 if baseURL != "" && !strings.HasPrefix(g.agentURL, "http://") {
113 baseURL = "http://" + g.agentURL
116 // Create HTTP client
117 g.log.Infoln("Connect HTTP client on ", baseURL)
118 conf := common.HTTPClientConfig{
119 URLPrefix: "/api/v1",
120 HeaderClientKeyName: "Xds-Agent-Sid",
123 LogLevel: common.HTTPLogLevelWarning,
125 c, err := common.HTTPNewClient(baseURL, conf)
127 errmsg := err.Error()
128 if m, err := regexp.MatchString("Get http.?://", errmsg); m && err == nil {
129 i := strings.LastIndex(errmsg, ":")
130 errmsg = "Cannot connection to " + baseURL + errmsg[i:]
132 return int(syscallEBADE), fmt.Errorf(errmsg)
135 g.httpCli.SetLogLevel(g.log.Level.String())
136 g.log.Infoln("HTTP session ID:", g.httpCli.GetClientID())
138 // First call to check that xds-agent and server are alive
139 ver := xaapiv1.XDSVersion{}
140 if err := g.httpCli.Get("/version", &ver); err != nil {
141 return int(syscallEBADE), err
143 g.log.Infoln("XDS agent & server version:", ver)
145 // Get current config and update connection to server when needed
146 xdsConf := xaapiv1.APIConfig{}
147 if err := g.httpCli.Get("/config", &xdsConf); err != nil {
148 return int(syscallEBADE), err
150 // FIXME: add multi-servers support
152 svrCfg := xdsConf.Servers[idx]
153 if g.serverURL != "" && (svrCfg.URL != g.serverURL || !svrCfg.Connected) {
154 svrCfg.URL = g.serverURL
155 svrCfg.ConnRetry = 10
156 newCfg := xaapiv1.APIConfig{}
157 if err := g.httpCli.Post("/config", xdsConf, &newCfg); err != nil {
158 return int(syscallEBADE), err
161 } else if !svrCfg.Connected {
162 return int(syscallEBADE), fmt.Errorf("XDS server not connected (url=%s)", svrCfg.URL)
165 // Get XDS projects list
167 if err := g.httpCli.HTTPGet("/projects", &data); err != nil {
168 return int(syscallEBADE), err
171 g.log.Infof("Result of /projects: %v", string(data[:]))
172 g.projects = []xaapiv1.ProjectConfig{}
173 errMar := json.Unmarshal(data, &g.projects)
175 g.log.Errorf("Cannot decode projects configuration: %s", errMar.Error())
178 // Check mandatory args
179 if g.prjID == "" || g.listPrj {
180 return g.printProjectsList()
183 // Create io Websocket client
184 g.log.Infoln("Connecting IO.socket client on ", baseURL)
186 opts := &sio_client.Options{
187 Transport: "websocket",
188 Header: make(map[string][]string),
190 opts.Header["XDS-AGENT-SID"] = []string{c.GetClientID()}
192 iosk, err := sio_client.NewClient(baseURL, opts)
194 e := fmt.Sprintf("IO.socket connection error: " + err.Error())
195 return int(syscall.ECONNABORTED), fmt.Errorf(e)
199 iosk.On("error", func(err error) {
200 if g.cbOnError != nil {
205 iosk.On("disconnection", func(err error) {
206 if g.cbOnDisconnect != nil {
207 g.cbOnDisconnect(err)
212 iosk.On(xaapiv1.ExecOutEvent, func(ev xaapiv1.ExecOutMsg) {
214 g.cbRead(ev.Timestamp, ev.Stdout, ev.Stderr)
219 if strings.Contains(stdout, "pid = ") {
220 re := regexp.MustCompile("pid = ([0-9]+)")
221 if res := re.FindAllStringSubmatch(stdout, -1); len(res) > 0 {
224 g.log.Errorf("SEB FOUND THREAD in '%s' => gdbPid=%s", stdout, gdbPid)
226 if gdbPid != "" && g.xGdbPid != "" && strings.Contains(stdout, gdbPid) {
227 g.log.Errorf("SEB THREAD REPLACE 1 stdout=%s", stdout)
228 stdout = strings.Replace(stdout, gdbPid, g.xGdbPid, -1)
229 g.log.Errorf("SEB THREAD REPLACE 2 stdout=%s", stdout)
232 g.cbRead(ev.Timestamp, stdout, ev.Stderr)
237 iosk.On(xaapiv1.ExecInferiorOutEvent, func(ev xaapiv1.ExecOutMsg) {
238 if g.cbInferiorRead != nil {
239 g.cbInferiorRead(ev.Timestamp, ev.Stdout, ev.Stderr)
243 iosk.On(xaapiv1.ExecExitEvent, func(ev xaapiv1.ExecExitMsg) {
244 if g.cbOnExit != nil {
245 g.cbOnExit(ev.Code, ev.Error)
252 // Close frees allocated objects and close opened connections
253 func (g *GdbXds) Close() error {
254 g.cbOnDisconnect = nil
258 g.cbInferiorRead = nil
264 // Start sends a request to start remotely gdb within xds-server
265 func (g *GdbXds) Start(inferiorTTY bool) (int, error) {
267 var project *xaapiv1.ProjectConfig
269 // Retrieve the project definition
270 for _, f := range g.projects {
271 // check as prefix to support short/partial id name
272 if strings.HasPrefix(f.ID, g.prjID) {
278 // Auto setup rPath if needed
279 if g.rPath == "" && project != nil {
280 cwd, err := os.Getwd()
282 fldRp := project.ClientPath
283 if !strings.HasPrefix(fldRp, "/") {
286 log.Debugf("Try to auto-setup rPath: cwd=%s ; ClientPath=%s", cwd, fldRp)
287 if sp := strings.SplitAfter(cwd, fldRp); len(sp) == 2 {
288 g.rPath = strings.Trim(sp[1], "/")
289 g.log.Debugf("Auto-setup rPath to: '%s'", g.rPath)
294 // Enable workaround about inferior output with gdbserver connection
295 // except if XDS_GDBSERVER_OUTPUT_NOFIX is defined
296 _, gdbserverNoFix := os.LookupEnv("XDS_GDBSERVER_OUTPUT_NOFIX")
298 args := xaapiv1.ExecArgs{
306 TTYGdbserverFix: !gdbserverNoFix,
307 CmdTimeout: -1, // no timeout, end when stdin close or command exited normally
310 g.log.Infof("POST %s/exec %v", g.agentURL, args)
311 res := xaapiv1.ExecResult{}
312 err = g.httpCli.Post("/exec", args, &res)
314 return int(syscall.EAGAIN), err
317 return int(syscallEBADE), fmt.Errorf("null CmdID")
324 // Cmd returns the command name
325 func (g *GdbXds) Cmd() string {
329 // Args returns the list of arguments
330 func (g *GdbXds) Args() []string {
334 // Env returns the list of environment variables
335 func (g *GdbXds) Env() []string {
339 // OnError is called on a WebSocket error
340 func (g *GdbXds) OnError(f func(error)) {
344 // OnDisconnect is called when WebSocket disconnection
345 func (g *GdbXds) OnDisconnect(f func(error)) {
349 // OnExit calls when exit event is received
350 func (g *GdbXds) OnExit(f func(code int, err error)) {
354 // Read calls when a message/string event is received on stdout or stderr
355 func (g *GdbXds) Read(f func(timestamp, stdout, stderr string)) {
359 // InferiorRead calls when a message/string event is received on stdout or stderr of the debugged program (IOW inferior)
360 func (g *GdbXds) InferiorRead(f func(timestamp, stdout, stderr string)) {
364 // Write writes message/string into gdb stdin
365 func (g *GdbXds) Write(args ...interface{}) error {
366 return g.ioSock.Emit(xaapiv1.ExecInEvent, args...)
369 // SendSignal is used to send a signal to remote process/gdb
370 func (g *GdbXds) SendSignal(sig os.Signal) error {
372 return fmt.Errorf("cmdID not set")
375 sigArg := xaapiv1.ExecSignalArgs{
377 Signal: sig.String(),
379 g.log.Debugf("POST /signal %v", sigArg)
380 return g.httpCli.Post("/signal", sigArg, nil)
383 //***** Private functions *****
385 func (g *GdbXds) printProjectsList() (int, error) {
387 if len(g.projects) > 0 {
388 msg += "List of existing projects (use: export XDS_PROJECT_ID=<< ID >>): \n"
389 msg += " ID\t\t\t\t | Label"
390 for _, f := range g.projects {
391 msg += fmt.Sprintf("\n %s\t | %s", f.ID, f.Label)
392 if f.DefaultSdk != "" {
393 msg += fmt.Sprintf("\t(default SDK: %s)", f.DefaultSdk)
399 // FIXME : support multiple servers
400 sdks := []xaapiv1.SDK{}
401 if err := g.httpCli.Get("/servers/0/sdks", &sdks); err != nil {
402 return int(syscallEBADE), err
404 msg += "\nList of installed cross SDKs (use: export XDS_SDK_ID=<< ID >>): \n"
405 msg += " ID\t\t\t\t\t | NAME\n"
406 for _, s := range sdks {
407 msg += fmt.Sprintf(" %s\t | %s\n", s.ID, s.Name)
410 if len(g.projects) > 0 && len(sdks) > 0 {
411 msg += fmt.Sprintf("\n")
412 msg += fmt.Sprintf("For example: \n")
413 msg += fmt.Sprintf(" XDS_PROJECT_ID=%q XDS_SDK_ID=%q %s -x myGdbConf.ini\n",
414 g.projects[0].ID, sdks[0].ID, AppName)
417 return 0, fmt.Errorf(msg)