summaryrefslogtreecommitdiffstats
path: root/test/src/test-w3c.cpp
blob: aa2bff5aa04ee0445f123fb975ebe3138ecc5f9c (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
// I feel dirty, but we need to access the datamodel timer
// #define protected public

#include "uscxml/config.h"

#ifdef APPLE
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <pthread.h>
#endif

#include "uscxml/Common.h"
#include "uscxml/Convenience.h"

#ifdef BUILD_PROFILING
// get access to the datamodel - this causes strange issues with MSVC depending on include order
// may be better to ifndef all protected: and private: stanzas for profiling?
#define protected public
#include "uscxml/Interpreter.h"
#undef protected
# endif


#include "uscxml/DOMUtils.h"
#include "uscxml/concurrency/Timer.h"

#include "uscxml/Factory.h"
#include "uscxml/server/HTTPServer.h"

#include "uscxml/transform/ChartToFlatSCXML.h"
#include <glog/logging.h>
#include <boost/algorithm/string.hpp>

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

#ifdef BUILD_PROFILING
#   include "uscxml/plugins/DataModel.h"
# endif

#ifdef _WIN32
#include "XGetopt.h"
#include "XGetopt.cpp"
#endif

static bool withFlattening = false;
static double delayFactor = 1;
static size_t benchmarkRuns = 1;
static std::string documentURI;

int retCode = EXIT_FAILURE;
uscxml::Interpreter interpreter;

void printUsageAndExit(const char* progName) {
	// remove path from program name
	std::string progStr(progName);
	if (progStr.find_last_of(PATH_SEPERATOR) != std::string::npos) {
		progStr = progStr.substr(progStr.find_last_of(PATH_SEPERATOR) + 1, progStr.length() - (progStr.find_last_of(PATH_SEPERATOR) + 1));
	}

	printf("%s version " USCXML_VERSION " (" CMAKE_BUILD_TYPE " build - " CMAKE_COMPILER_STRING ")\n", progStr.c_str());
	printf("Usage\n");
	printf("\t%s", progStr.c_str());
	printf(" [-f] [-dN] [-bN]");
#ifdef BUILD_AS_PLUGINS
	printf(" [-p pluginPath]");
#endif
	printf(" URL");
	printf("\n");
	printf("Options\n");
	printf("\t-f             : flatten to SCXML state-machine\n");
	printf("\t-d FACTOR      : delay factor\n");
	printf("\t-b ITERATIONS  : benchmark with number of runs\n");
	printf("\n");
	exit(1);
}

class W3CStatusMonitor : public uscxml::InterpreterMonitor {

	void beforeCompletion(uscxml::Interpreter tmp) {
		if (interpreter.getConfiguration().size() == 1 && interpreter.isInState("pass")) {
#ifndef BUILD_PROFILING
            std::cout << "TEST SUCCEEDED" << std::endl;
#endif
			retCode = EXIT_SUCCESS;
			return;
		}
#ifndef BUILD_PROFILING
		std::cout << "TEST FAILED" << std::endl;
#endif
        retCode = EXIT_FAILURE;
    }
};

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

#ifdef APPLE
    mach_timebase_info_data_t timebase_info;
    mach_timebase_info(&timebase_info);
    
    const uint64_t NANOS_PER_MSEC = 1000000ULL;
    double clock2abs = ((double)timebase_info.denom / (double)timebase_info.numer) * NANOS_PER_MSEC;
    
    thread_time_constraint_policy_data_t policy;
    policy.period      = 0;
    policy.computation = (uint32_t)(5 * clock2abs); // 5 ms of work
    policy.constraint  = (uint32_t)(10 * clock2abs);
    policy.preemptible = FALSE;
    
    int kr = thread_policy_set(pthread_mach_thread_np(pthread_self()),
                               THREAD_TIME_CONSTRAINT_POLICY,
                               (thread_policy_t)&policy,
                               THREAD_TIME_CONSTRAINT_POLICY_COUNT);
    if (kr != KERN_SUCCESS) {
        mach_error("thread_policy_set:", kr);
        exit(1);
    }
#endif

	try {

#if defined(HAS_SIGNAL_H) && !defined(WIN32)
		signal(SIGPIPE, SIG_IGN);
#endif

		if (argc < 2) {
			exit(EXIT_FAILURE);
		}

		google::InitGoogleLogging(argv[0]);

		HTTPServer::getInstance(32954, 32955, NULL); // bind to some random tcp sockets for ioprocessor tests

		char* dfEnv = getenv("USCXML_DELAY_FACTOR");
		if (dfEnv) {
			delayFactor = strTo<double>(dfEnv);
		}

        const char* envBenchmarkRuns = getenv("USCXML_BENCHMARK_ITERATIONS");
        if (envBenchmarkRuns != NULL) {
            benchmarkRuns = strTo<size_t>(envBenchmarkRuns);
            google::SetStderrLogging(3);
        } else {
            google::LogToStderr();
        }

		int option;
		while ((option = getopt(argc, argv, "fd:b:")) != -1) {
			switch(option) {
			case 'f':
				withFlattening = true;
				break;
			case 'd':
				delayFactor = strTo<double>(optarg);
				break;
			case 'b':
				benchmarkRuns = strTo<size_t>(optarg);
				break;
			default:
				break;
			}
		}

		documentURI = argv[optind];

		LOG(INFO) << "Processing " << documentURI << (withFlattening ? " FSM converted" : "") << (delayFactor ? "" : " with delays *= " + toStr(delayFactor)) << (benchmarkRuns > 0 ? " for " + toStr(benchmarkRuns) + " benchmarks" : "");
		if (withFlattening) {
			interpreter = Interpreter::fromURL(documentURI);
			Transformer flattener = ChartToFlatSCXML::transform(interpreter);
			interpreter = flattener;
//			std::cout << interpreter.getDocument() << std::endl;
		} else {
			interpreter = Interpreter::fromURL(documentURI);
		}

		if (delayFactor != 1) {
			Arabica::DOM::Document<std::string> document = interpreter.getDocument();
			Arabica::DOM::Element<std::string> root = document.getDocumentElement();
			Arabica::XPath::NodeSet<std::string> sends = InterpreterImpl::filterChildElements(interpreter.getNameSpaceInfo().xmlNSPrefix + "send", root, true);

			for (int i = 0; i < sends.size(); i++) {
				Arabica::DOM::Element<std::string> send = Arabica::DOM::Element<std::string>(sends[i]);
				if (HAS_ATTR(send, "delay")) {
					NumAttr delay(ATTR(send, "delay"));
					int value = strTo<int>(delay.value);
					if (delay.unit == "s")
						value *= 1000;
					value *= delayFactor;
					send.setAttribute("delay", toStr(value) + "ms");
					std::cout << ATTR(send, "delay") << std::endl;
				} else if (HAS_ATTR(send, "delayexpr")) {
					std::string delayExpr = ATTR(send, "delayexpr");
					send.setAttribute("delayexpr",
					                  "(" + delayExpr + ".indexOf('ms', " + delayExpr + ".length - 2) !== -1 ? "
					                  "(" + delayExpr + ".slice(0,-2) * " + toStr(delayFactor) + ") + \"ms\" : "
					                  "(" + delayExpr + ".slice(0,-1) * 1000 * " + toStr(delayFactor) + ") + \"ms\")");
					std::cout << ATTR(send, "delayexpr") << std::endl;
				}
			}
			std::list<InterpreterIssue> issues = interpreter.validate();
			for (std::list<InterpreterIssue>::iterator issueIter = issues.begin(); issueIter != issues.end(); issueIter++) {
				std::cout << *issueIter << std::endl;
			}
		}

		if (interpreter) {
			W3CStatusMonitor* vm = new W3CStatusMonitor();
			interpreter.addMonitor(vm);

            LOG(INFO) << "Benchmarking " << documentURI << (withFlattening ? " FSM converted" : "") << (delayFactor ? "" : " with delays *= " + toStr(delayFactor));

            size_t remainingRuns = benchmarkRuns;
            size_t microSteps = 0;

            Timer tTotal;
            tTotal.start();

            double avg = 0;
#ifdef BUILD_PROFILING
            double avgDm = 0;
            double avgStep = 0;
#endif

            while(remainingRuns-- > 0) {
                Timer t;
                microSteps = 0;

                InterpreterState state = interpreter.getState();

                for(;;) {
                    state = interpreter.step(true);
                    microSteps++;
                    if (state == USCXML_INITIALIZED) {
                        t.start();
                    } else if (state == USCXML_FINISHED) {
#ifdef BUILD_PROFILING
                        avgDm += interpreter._impl->_dataModel.timer.elapsed;
                        interpreter._impl->_dataModel.timer.reset();
                        avgStep += interpreter.timer.elapsed;
#endif
                    }
                    if (state < 0)
                        break;
                }
                assert(retCode == EXIT_SUCCESS);
                t.stop();
                avg += t.elapsed;
                interpreter.reset();
                std::cout << "." << std::flush;
            }
            
            tTotal.stop();
            
            std::cout << benchmarkRuns << " iterations" << std::endl;
            std::cout << tTotal.elapsed * 1000.0 << " ms in total" << std::endl;
            std::cout << (avg * 1000.0) / (double)benchmarkRuns << " ms per execution" << std::endl;
            std::cout << microSteps << " microsteps per iteration" << std::endl;
            std::cout << (avg * 1000.0) / ((double)benchmarkRuns * (double)microSteps) << " ms per microstep" << std::endl;
#ifdef BUILD_PROFILING
            std::cout << (avgDm * 1000.0) / (double)benchmarkRuns << " ms in datamodel" << std::endl;
            std::cout << ((avg - avgDm) * 1000.0) / ((double)benchmarkRuns * (double)microSteps) << " ms per microstep \\wo datamodel" << std::endl;
#endif
		}
	} catch(Event e) {
		std::cout << e << std::endl;
	} catch(std::exception e) {
		std::cout << e.what() << std::endl;
	}
	return retCode;
}