summaryrefslogtreecommitdiffstats
path: root/apps/uscxml-debug.cpp
blob: 5b9c989f40808da7829f9486116b348cd4f19a71 (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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#include "uscxml/config.h"
#include "uscxml/Interpreter.h"
#include "uscxml/DOMUtils.h"
#include "uscxml/UUID.h"
#include "uscxml/debug/SCXMLDotWriter.h"
#include <glog/logging.h>
#include <time.h> // mktime

#include <boost/algorithm/string.hpp>

#ifdef HAS_SIGNAL_H
#include <signal.h>
#endif

#ifdef HAS_EXECINFO_H
#include <execinfo.h>
#endif

#ifdef HAS_DLFCN_H
#include <dlfcn.h>
#endif

using namespace uscxml;

class Debugger : public HTTPServlet, public InterpreterMonitor, public google::LogSink {
public:
	class BreakPoint {
	public:

		enum When {
			UNDEF_WHEN, AFTER, BEFORE, ON
		};

		enum Subject {
			UNDEF_SUBJECT, STATE, TRANSITION, CONFIGURATION, EVENT
		};

		enum Action {
			UNDEF_ACTION, ENTER, EXIT
		};

		BreakPoint(const Data& data) {
			subject = UNDEF_SUBJECT;
			when    = UNDEF_WHEN;
			action  = UNDEF_ACTION;
			
			if (data.hasKey("action")) {
				if (false) {
				} else if (iequals(data["action"], "enter")) {
					action = ENTER;
				} else if (iequals(data["action"], "exit")) {
					action = EXIT;
				}
			}
			if (data.hasKey("time")) {
				if (false) {
				} else if (iequals(data["time"], "before")) {
					when = BEFORE;
				} else if (iequals(data["time"], "after")) {
					when = AFTER;
				} else if (iequals(data["time"], "on")) {
					when = ON;
				}
			}
			if (data.hasKey("subject")) {
				if (false) {
				} else if (iequals(data["subject"], "state")) {
					subject = STATE;
					if (data.hasKey("stateId"))
						state = data["stateId"].atom;
				} else if (iequals(data["subject"], "transition")) {
					subject = TRANSITION;
					if (data.hasKey("fromStateId"))
						fromState = data["fromStateId"].atom;
					if (data.hasKey("toStateId"))
						fromState = data["toStateId"].atom;
				} else if (iequals(data["subject"], "event")) {
					subject = EVENT;
					if (data.hasKey("eventName"))
						eventName = data["eventName"].atom;
				} else if (iequals(data["subject"], "configuration")) {
					subject = CONFIGURATION;
				} else if (iequals(data["subject"], "microstep")) {
					subject = CONFIGURATION;
				}
			}

			if (data.hasKey("condition")) {
				condition = data["condition"].atom;
			}
		}
		
		bool isValid() {
			return true;
		}
		
	protected:
		When when;
		Subject subject;
		Action action;
		
		std::string state;
		std::string toState;
		std::string fromState;
		std::string eventName;
		
		std::string condition;
		
	};
	
	class LogMessage {
	public:
		google::LogSeverity severity;
		std::string full_filename;
		std::string base_filename;
		int line;
		const struct ::tm* tm_time;
		std::string message;
		std::string formatted;
		
		Data toData() {
			Data data;
			data.compound["severity"] = severity;
			data.compound["fullFilename"] = Data(full_filename, Data::VERBATIM);
			data.compound["baseFilename"] = Data(base_filename, Data::VERBATIM);
			data.compound["line"] = line;
			data.compound["message"] = Data(message, Data::VERBATIM);
			data.compound["time"] = mktime((struct ::tm*)tm_time);
			data.compound["formatted"] = Data(formatted, Data::VERBATIM);
			return data;
		}
	};

	std::string _url;
	Interpreter _interpreter;
	HTTPServer::Request _debugReq;
	tthread::recursive_mutex _mutex;
	std::list<LogMessage> _logMessages;
	std::map<std::string, BreakPoint> _breakPoints;
	
	virtual ~Debugger() {
	}
	
	// callbacks from http requests
	
	void debug(const HTTPServer::Request& request) {
		tthread::lock_guard<tthread::recursive_mutex> lock(_mutex);

		// save request and run until we reach a breakpoint
		_debugReq = request;
		_interpreter.interpret();
	}
	
	void connect(const HTTPServer::Request& request) {
		Data replyData;
		replyData.compound["status"] = Data("success", Data::VERBATIM);
		returnData(request, replyData);
	}

	void disconnect(const HTTPServer::Request& request) {
		Data replyData;
		replyData.compound["status"] = Data("success", Data::VERBATIM);
		returnData(request, replyData);
	}

	void prepare(const HTTPServer::Request& request) {
		tthread::lock_guard<tthread::recursive_mutex> lock(_mutex);

		_interpreter = Interpreter::fromXML(request.data["content"].atom);

		Data replyData;
		if (_interpreter) {
			// register ourself as a monitor
			_interpreter.addMonitor(this);
			replyData.compound["status"] = Data("success", Data::VERBATIM);
		} else {
			replyData.compound["status"] = Data("failure", Data::VERBATIM);
		}
		returnData(request, replyData);
	}

	void addBreakPoint(const HTTPServer::Request& request) {
		BreakPoint breakPoint(request.data["content"]);
		Data replyData;
		if (breakPoint.isValid()) {
			replyData.compound["status"] = Data("success", Data::VERBATIM);
		} else {
			replyData.compound["status"] = Data("failure", Data::VERBATIM);
		}
		returnData(request, replyData);
	}
	
	// helpers
	
	void returnData(const HTTPServer::Request& request, Data replyData) {
		//always include latest log
		while(_logMessages.size() > 0) {
			replyData.compound["log"].array.push_back(_logMessages.front().toData());
			_logMessages.pop_front();
		}

		HTTPServer::Reply reply(request);
		reply.headers["Content-type"] = "application/json";
		reply.headers["Access-Control-Allow-Origin"] = "*";
		reply.content = Data::toJSON(replyData);
		HTTPServer::reply(reply);
	}
	
	bool isCORS(const HTTPServer::Request& request) {
		return (request.data["type"].atom == "options" &&
						request.data["header"].hasKey("Origin") &&
						request.data["header"].hasKey("Access-Control-Request-Method"));
	}
	
	void handleCORS(const HTTPServer::Request& request) {
		HTTPServer::Reply corsReply(request);
		if (request.data["header"].hasKey("Origin")) {
			corsReply.headers["Access-Control-Allow-Origin"] = request.data["header"]["Origin"].atom;
		} else {
			corsReply.headers["Access-Control-Allow-Origin"] = "*";
		}
		if (request.data["header"].hasKey("Access-Control-Request-Method"))
			corsReply.headers["Access-Control-Allow-Methods"] = request.data["header"]["Access-Control-Request-Method"].atom;
		if (request.data["header"].hasKey("Access-Control-Request-Headers"))
			corsReply.headers["Access-Control-Allow-Headers"] = request.data["header"]["Access-Control-Request-Headers"].atom;

//		std::cout << "CORS!" << std::endl << request << std::endl;
		HTTPServer::reply(corsReply);
	}
	
	// HTTPServlet
	
	bool httpRecvRequest(const HTTPServer::Request& request) {
		if (isCORS(request)) {
			handleCORS(request);
			return true;
		}
		
		std::cout << Data::toJSON(request.data) << std::endl;
		
		if (false) {
		} else if (boost::istarts_with(request.data["path"].atom, "/connect")) {
			connect(request);
		} else if (boost::istarts_with(request.data["path"].atom, "/disconnect")) {
			disconnect(request);
		} else if (boost::istarts_with(request.data["path"].atom, "/prepare")) {
			prepare(request);
		} else if (boost::istarts_with(request.data["path"].atom, "/debug")) {
			debug(request);
		} else if (boost::istarts_with(request.data["path"].atom, "/breakpoint/add")) {
			addBreakPoint(request);
		}
		return true;
	}
	void setURL(const std::string& url) {
		_url = url;
	}
		
	// InterpreterMonitor
	void onStableConfiguration(Interpreter interpreter) {
	}
	
	void beforeCompletion(Interpreter interpreter) {}
	void afterCompletion(Interpreter interpreter) {}
	void beforeMicroStep(Interpreter interpreter) {}
	void beforeTakingTransitions(Interpreter interpreter, const Arabica::XPath::NodeSet<std::string>& transitions) {}
	void beforeEnteringStates(Interpreter interpreter, const Arabica::XPath::NodeSet<std::string>& statesToEnter) {}
	void afterEnteringStates(Interpreter interpreter) {}
	void beforeExitingStates(Interpreter interpreter, const Arabica::XPath::NodeSet<std::string>& statesToExit) {}
	void afterExitingStates(Interpreter interpreter) {}

	// google::LogSink
	
  virtual void send(google::LogSeverity severity, const char* full_filename,
                    const char* base_filename, int line,
                    const struct ::tm* tm_time,
                    const char* message, size_t message_len) {
		
		tthread::lock_guard<tthread::recursive_mutex> lock(_mutex);

		LogMessage msg;
		msg.severity = severity;
		msg.full_filename = full_filename;
		msg.base_filename = base_filename;
		msg.line = line;
		msg.tm_time = tm_time;
		msg.message = std::string(message, message_len);
		msg.formatted = ToString(severity, base_filename, line, tm_time, message, message_len);
		
		_logMessages.push_back(msg);
	}
		
};


int main(int argc, char** argv) {
	using namespace uscxml;

	InterpreterOptions options = InterpreterOptions::fromCmdLine(argc, argv);
	Debugger debugger;

	// setup logging
	google::InitGoogleLogging(argv[0]);
	google::AddLogSink(&debugger);

	// setup HTTP server
	HTTPServer::getInstance(18088, 18089, NULL);


	HTTPServer::getInstance()->registerServlet("/", &debugger);

	while(true)
		tthread::this_thread::sleep_for(tthread::chrono::seconds(1));
	
	
	return EXIT_SUCCESS;
}