aboutsummaryrefslogtreecommitdiffstats
path: root/lib/agent/apiv1-exec.go
blob: 2f38b63db58b75bdda76312e172a8398f4fd16ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/*
 * Copyright (C) 2017 "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 agent

import (
	"net/http"

	"github.com/franciscocpg/reflectme"
	"github.com/gin-gonic/gin"
	"github.com/iotbzh/xds-agent/lib/xaapiv1"
	common "github.com/iotbzh/xds-common/golib"
	"github.com/iotbzh/xds-server/lib/xsapiv1"
	uuid "github.com/satori/go.uuid"
)

// ExecCmd executes remotely a command
func (s *APIService) execCmd(c *gin.Context) {

	args := xaapiv1.ExecArgs{}
	if err := c.BindJSON(&args); err != nil {
		s.Log.Warningf("/exec invalid args, err=%v", err)
		common.APIError(c, "Invalid arguments")
		return
	}

	// First get Project ID to retrieve Server ID and send command to right server
	iid := c.Param("id")
	if iid == "" {
		iid = args.ID
	}
	id, err := s.projects.ResolveID(iid)
	if err != nil {
		common.APIError(c, err.Error())
		return
	}
	prj := s.projects.Get(id)
	if prj == nil {
		common.APIError(c, "Unknown id")
		return
	}

	svr := (*prj).GetServer()
	if svr == nil {
		common.APIError(c, "Cannot identify XDS Server")
		return
	}

	// Retrieve session info
	sess := s.sessions.Get(c)
	if sess == nil {
		common.APIError(c, "Unknown sessions")
		return
	}
	sock := sess.IOSocket
	if sock == nil {
		common.APIError(c, "Websocket not established")
		return
	}

	// Forward input events from client to XDSServer through WS
	// TODO use XDSServer events names definition
	evtInList := []string{
		xaapiv1.ExecInEvent,
		xaapiv1.ExecInferiorInEvent,
	}
	for _, evName := range evtInList {
		evN := evName
		err := (*sock).On(evN, func(stdin string) {
			if s.LogLevelSilly {
				s.Log.Debugf("EXEC EVENT IN (%s) <<%v>>", evN, stdin)
			}
			svr.EventEmit(evN, stdin)
		})
		if err != nil {
			msgErr := "Error while registering WS for " + evN + " event"
			s.Log.Errorf(msgErr, ", err: %v", err)
			common.APIError(c, msgErr)
			return
		}
	}

	// Forward output events from XDSServer to client through WS
	// TODO use XDSServer events names definition
	var fwdFuncID []uuid.UUID
	evtOutList := []string{
		xaapiv1.ExecOutEvent,
		xaapiv1.ExecInferiorOutEvent,
	}
	for _, evName := range evtOutList {
		evN := evName
		fwdFunc := func(pData interface{}, evData interface{}) error {
			sid := pData.(string)
			// 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)", evN, sid)
				return nil
			}

			// Add sessionID to event Data
			reflectme.SetField(evData, "sessionID", sid)

			if s.LogLevelSilly {
				s.Log.Debugf("EXEC EVENT OUT (%s) <<%v>>", evN, evData)
			}

			// Forward event to Client/Dashboard
			(*so).Emit(evN, evData)
			return nil
		}
		id, err := svr.EventOn(evN, sess.ID, fwdFunc)
		if err != nil {
			common.APIError(c, err.Error())
			return
		}
		fwdFuncID = append(fwdFuncID, id)
	}

	// Handle Exit event separately to cleanup registered listener
	var exitFuncID uuid.UUID
	exitFunc := func(privD interface{}, evData interface{}) error {
		evN := xaapiv1.ExecExitEvent

		pData := privD.(map[string]string)
		sid := pData["sessID"]
		prjID := pData["prjID"]

		// Add sessionID to event Data
		reflectme.SetField(evData, "sessionID", sid)

		// IO socket can be nil when disconnected
		so := s.sessions.IOSocketGet(sid)
		if so != nil {
			(*so).Emit(evN, evData)
		} else {
			s.Log.Infof("%s not emitted: WS closed (sid:%s)", evN, sid)
		}

		prj := s.projects.Get(prjID)
		if prj != nil {
			evD := evData.(map[string]interface{})
			cmdIDData, cmdIDExist := evD["cmdID"]
			svr := (*prj).GetServer()
			if svr != nil && cmdIDExist {
				svr.CommandDelete(cmdIDData.(string))
			} else {
				s.Log.Infof("%s: cannot retrieve server for sid=%s, prjID=%s, evD=%v", evN, sid, prjID, evD)
			}
		} else {
			s.Log.Infof("%s: cannot retrieve project for sid=%s, prjID=%s", evN, sid, prjID)
		}

		// cleanup listener
		for i, evName := range evtOutList {
			svr.EventOff(evName, fwdFuncID[i])
		}
		svr.EventOff(evN, exitFuncID)

		return nil
	}

	prjCfg := (*prj).GetProject()
	privData := map[string]string{"sessID": sess.ID, "prjID": prjCfg.ID}
	exitFuncID, err = svr.EventOn(xaapiv1.ExecExitEvent, privData, exitFunc)
	if err != nil {
		common.APIError(c, err.Error())
		return
	}

	// Forward back command to right server
	res := xsapiv1.ExecResult{}
	xsArgs := &xsapiv1.ExecArgs{
		ID:              args.ID,
		SdkID:           args.SdkID,
		CmdID:           args.CmdID,
		Cmd:             args.Cmd,
		Args:            args.Args,
		Env:             args.Env,
		RPath:           args.RPath,
		TTY:             args.TTY,
		TTYGdbserverFix: args.TTYGdbserverFix,
		ExitImmediate:   args.ExitImmediate,
		CmdTimeout:      args.CmdTimeout,
	}
	if err := svr.CommandExec(xsArgs, &res); err != nil {
		common.APIError(c, err.Error())
		return
	}

	// Add command to running commands list
	if err := svr.CommandAdd(res.CmdID, xsArgs); err != nil {
		common.APIError(c, err.Error())
		return
	}

	c.JSON(http.StatusOK, xaapiv1.ExecResult{Status: res.Status, CmdID: res.CmdID})
}

// execSignalCmd executes remotely the signal command
func (s *APIService) execSignalCmd(c *gin.Context) {

	args := xaapiv1.ExecSignalArgs{}
	if err := c.BindJSON(&args); err != nil {
		s.Log.Warningf("/signal invalid args, err=%v", err)
		common.APIError(c, "Invalid arguments")
		return
	}

	// Retrieve on which xds-server the command is running
	var svr *XdsServer
	var dataCmd interface{}
	for _, svr = range s.xdsServers {
		dataCmd = svr.CommandGet(args.CmdID)
		if dataCmd != nil {
			break
		}
	}
	if dataCmd == nil {
		common.APIError(c, "Cannot retrieve XDS Server for this cmdID")
		return
	}

	// Forward back command to right server
	res := xsapiv1.ExecSigResult{}
	xsArgs := &xsapiv1.ExecSignalArgs{
		CmdID:  args.CmdID,
		Signal: args.Signal,
	}
	if err := svr.CommandSignal(xsArgs, &res); err != nil {
		common.APIError(c, err.Error())
		return
	}

	c.JSON(http.StatusOK, xaapiv1.ExecSignalResult{Status: res.Status, CmdID: res.CmdID})
}