1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
14 #include <signal.h> // sigaction, sigemptyset, struct sigaction, SIGCHLD, SA_RESTART, SA_NOCLDSTOP
15 #include <stdio.h> // perror
16 #include <stdlib.h> // exit
17 #include <sys/wait.h> // waitpid, pid_t, WNOHANG
20 #include <anna/xml/Compiler.hpp>
21 #include <anna/core/util/Millisecond.hpp>
22 #include <anna/diameter.comm/Message.hpp>
23 #include <anna/core/tracing/Logger.hpp>
24 #include <anna/diameter/codec/functions.hpp>
25 #include <anna/diameter/helpers/base/functions.hpp>
28 #include <RealmNode.hpp>
29 #include <MyDiameterEntity.hpp>
30 #include <MyLocalServer.hpp>
31 #include <TestStep.hpp>
32 #include <Launcher.hpp>
33 #include <TestCase.hpp>
34 #include <TestManager.hpp>
35 #include <TestTimer.hpp>
40 void handle_sigchld(int sig) {
41 while (waitpid((pid_t)(-1 /* any child (the only) */), 0, WNOHANG|WNOWAIT) > 0) {}
44 void cmdRunOnThread (TestStepCmd *step, const std::string &cmd) {
47 step->setThreadRunning(true);
52 sa.sa_handler = &handle_sigchld;
53 sigemptyset(&sa.sa_mask);
54 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
55 if (sigaction(SIGCHLD, &sa, 0) != -1) {
56 status = system(cmd.c_str());
59 FILE *fp = popen(cmd.c_str(), "r");
61 while(fgets(readbuf, sizeof(readbuf), fp))
62 step->appendOutput("\n");
63 step->appendOutput(readbuf);
74 // This can be implemented portably and somewhat more concisely with the signal function if you prefer:
75 // if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
82 char const * str = strerror_r(errno, buf, 256);
83 step->setErrorMsg(anna::functions::asString("errno = %d (%s)", errno, str));
86 step->setResultCode(WEXITSTATUS(status)); // rc = status >>= 8; // divide by 256
88 // TODO: terminate thread when deprecated (RT signal ?)
89 // TODO: mutex the step while setting data here !!
94 ////////////////////////////////////////////////////////////////////////////////////////////////////////
96 ////////////////////////////////////////////////////////////////////////////////////////////////////////
97 void TestStep::initialize(TestCase *testCase) {
98 a_testCase = testCase;
100 a_type = Type::Unconfigured;
101 a_beginTimestamp = 0;
103 a_number = testCase->steps() + 1; // testCase is not NULL
106 const char* TestStep::asText(const Type::_v type)
108 static const char* text [] = { "Unconfigured", "Timeout", "Sendxml2e", "Sendxml2c", "Delay", "Wait", "Cmd" };
112 anna::xml::Node* TestStep::asXML(anna::xml::Node* parent) const
114 anna::xml::Node* result = parent->createChild("TestStep");
116 result->createAttribute("Number", a_number);
117 result->createAttribute("Type", asText(a_type));
118 result->createAttribute("Completed", (a_completed ? "yes":"no"));
121 std::string s_aux = a_beginTimestamp.asString();
122 // int deltaMs = (int)(a_beginTimestamp - a_testCase->getStartTimestamp());
123 // if (a_beginTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
124 result->createAttribute("BeginTimestamp", s_aux);
127 s_aux = a_endTimestamp.asString();
128 // deltaMs = (int)(a_endTimestamp - a_testCase->getStartTimestamp());
129 // if (a_endTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
130 result->createAttribute("EndTimestamp", s_aux);
135 std::string TestStep::asXMLString() const throw() {
136 anna::xml::Node root("root");
137 return anna::xml::Compiler().apply(asXML(&root));
140 bool TestStep::execute() throw() {
141 LOGDEBUG(anna::Logger::debug(anna::functions::asString("EXECUTING %s (step number %d) for Test Case %llu (%p) (%p)", asText(a_type), a_number, a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
142 setBeginTimestamp(anna::functions::millisecond());
146 void TestStep::complete() throw() {
147 LOGDEBUG(anna::Logger::debug(anna::functions::asString("COMPLETE %s (step number %d) for Test Case %llu (%p) (%p)", asText(a_type), a_number, a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
149 setEndTimestamp(anna::functions::millisecond());
153 void TestStep::reset() throw() {
154 LOGDEBUG(anna::Logger::debug(anna::functions::asString("RESET %s (step number %d) for Test Case %llu (%p) (%p)", asText(a_type), a_number, a_testCase->getId(), (TestCaseStep*)this, this), ANNA_FILE_LOCATION));
155 // type and testCase kept
157 a_beginTimestamp = 0;
162 void TestStep::next() throw() {
163 a_testCase->nextStep();
164 a_testCase->process();
168 ////////////////////////////////////////////////////////////////////////////////////////////////////////
170 ////////////////////////////////////////////////////////////////////////////////////////////////////////
171 anna::xml::Node* TestStepTimeout::asXML(anna::xml::Node* parent) const
173 anna::xml::Node* result = TestStep::asXML(parent); // end timestamp will be 0 if test finished OK
174 //parent->createChild("TestStepTimeout");
175 result->createAttribute("Timeout", a_timeout.asString());
180 bool TestStepTimeout::do_execute() throw() {
182 a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_timeout, TestTimer::Type::TimeLeft);
184 catch (anna::RuntimeException &ex) {
186 a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
187 a_testCase->setState(TestCase::State::Failed);
190 return true; // go next
193 void TestStepTimeout::do_complete() throw() {
194 int stepNumber = getNumber();
195 if (stepNumber == a_testCase->steps()) {
196 a_testCase->addDebugSummaryHint(anna::functions::asString("Timeout expired (step number %d) but it was the last test case step", stepNumber)); // before report (when set Failed state)
197 a_testCase->setState(TestCase::State::Success);
199 else if (a_testCase->getState() == TestCase::State::InProgress) { // sure
200 a_testCase->addDebugSummaryHint(anna::functions::asString("Timeout expired (step number %d) before test case finished", stepNumber)); // before report (when set Failed state)
201 a_testCase->setState(TestCase::State::Failed);
207 void TestStepTimeout::do_reset() throw() {
208 LOGDEBUG(anna::Logger::debug(anna::functions::asString("REXXXXXET %s for Test Case %llu (%p) (%p) (a_timer %p)", asText(a_type), a_testCase->getId(), (TestCaseStep*)this, this, a_timer), ANNA_FILE_LOCATION));
211 TestManager::instantiate().cancelTimer(a_timer);
213 catch (anna::RuntimeException &ex) {
217 //a_timeout = 0; THIS IS CONFIGURATION INFO
220 ////////////////////////////////////////////////////////////////////////////////////////////////////////
222 ////////////////////////////////////////////////////////////////////////////////////////////////////////
223 anna::xml::Node* TestStepSendxml::asXML(anna::xml::Node* parent) const
225 anna::xml::Node* result = TestStep::asXML(parent);
226 //parent->createChild("TestStepSendxml");
227 std::string msg = "", xmlmsg = "";
230 if (TestManager::instantiate().getDumpHex()) {
231 if (a_message.isEmpty()) {
235 msg = "\n"; msg += a_message.asString(); msg += "\n";
239 if (!a_message.isEmpty()) {
241 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
242 static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
243 codecMsg.decode(a_message);
244 xmlmsg = "\n"; xmlmsg += codecMsg.asXMLString(); xmlmsg += "\n";
246 catch (anna::RuntimeException &ex) {
251 if (msg != "") result->createAttribute("Message", msg);
252 if (xmlmsg != "") result->createAttribute("XMLMessage", xmlmsg);
253 result->createAttribute("Expired", (a_expired ? "yes":"no"));
254 if (a_waitForRequestStepNumber != -1)
255 result->createAttribute("WaitForRequestStepNumber", a_waitForRequestStepNumber);
260 bool TestStepSendxml::do_execute() throw() {
261 anna::diameter::comm::Message *msg = a_realmNode->createCommMessage();
262 bool success = false;
263 std::string failReason, s_warn;
266 // Update sequence for answers:
267 if (a_waitForRequestStepNumber != -1) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
268 // Request which was received:
269 const TestStepWait *tsw = (const TestStepWait*)(a_testCase->getStep(a_waitForRequestStepNumber));
270 const anna::DataBlock &request = tsw->getMsgDataBlock();
271 anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(request);
272 anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(request);
274 anna::diameter::codec::functions::setHopByHop(a_message, hbh);
275 anna::diameter::codec::functions::setEndToEnd(a_message, ete);
277 // Check Session-Id for warning ...
278 std::string sessionIdAnswer = anna::diameter::helpers::base::functions::getSessionId(a_message);
279 std::string sessionIdRequest = anna::diameter::helpers::base::functions::getSessionId(request);
280 if (sessionIdRequest != sessionIdAnswer) {
281 s_warn = anna::functions::asString("Sending an answer which Session-Id (%s) is different than supposed corresponding request (%s)", sessionIdAnswer.c_str(), sessionIdRequest.c_str());
282 LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
283 a_testCase->addDebugSummaryHint(s_warn);
287 if (getType() == Type::Sendxml2e) {
288 MyDiameterEntity *entity = a_realmNode->getEntity();
291 msg->setBody(a_message);
292 /* response = NULL =*/entity->send(msg);
296 failReason = "There is no diameter entity currently configured. Unable to send the message";
297 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
300 else if (getType() == Type::Sendxml2c) {
301 MyLocalServer *localServer = a_realmNode->getDiameterServer();
304 msg->setBody(a_message);
305 /* response = NULL =*/localServer->send(msg);
309 failReason = "There is no diameter local server currently configured. Unable to send the message";
310 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
313 } catch(anna::RuntimeException &ex) {
314 failReason = ex.asString();
318 a_realmNode->releaseCommMessage(msg);
321 a_testCase->addDebugSummaryHint(failReason); // before report (when set Failed state);
322 a_testCase->setState(TestCase::State::Failed);
328 return success; // go next if sent was OK
331 void TestStepSendxml::do_reset() throw() {
336 ////////////////////////////////////////////////////////////////////////////////////////////////////////
338 ////////////////////////////////////////////////////////////////////////////////////////////////////////
339 anna::xml::Node* TestStepDelay::asXML(anna::xml::Node* parent) const
341 anna::xml::Node* result = TestStep::asXML(parent);
342 //parent->createChild("TestStepDelay");
344 result->createAttribute("Delay", a_delay.asString());
349 bool TestStepDelay::do_execute() throw() {
351 a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_delay, TestTimer::Type::Delay);
353 catch (anna::RuntimeException &ex) {
355 a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
356 a_testCase->setState(TestCase::State::Failed);
359 return false; // don't go next (wait complete)
362 void TestStepDelay::do_complete() throw() {
364 next(); // next() invoked here because execute() is always false for delay and never advance the iterator
367 void TestStepDelay::do_reset() throw() {
369 TestManager::instantiate().cancelTimer(a_timer);
371 catch (anna::RuntimeException &ex) {
375 //a_delay = 0; THIS IS CONFIGURATION INFO
378 ////////////////////////////////////////////////////////////////////////////////////////////////////////
380 ////////////////////////////////////////////////////////////////////////////////////////////////////////
381 void TestStepWait::setCondition(bool fromEntity,
382 const std::string &code, const std::string &bitR, const std::string &resultCode, const std::string &sessionId,
383 const std::string &hopByHop, const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw() {
385 a_condition.setReceivedFromEntity(fromEntity);
386 a_condition.setCode(code);
387 a_condition.setBitR(bitR);
388 a_condition.setResultCode(resultCode);
389 a_condition.setSessionId(sessionId);
390 a_condition.setHopByHop(hopByHop);
391 a_condition.setMsisdn(msisdn);
392 a_condition.setImsi(imsi);
393 a_condition.setServiceContextId(serviceContextId);
396 void TestStepWait::setCondition(bool fromEntity, const std::string ®exp) throw() {
398 a_condition.setReceivedFromEntity(fromEntity);
399 a_condition.setRegexp(regexp);
402 anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent) const
404 anna::xml::Node* result = TestStep::asXML(parent);
405 //parent->createChild("TestStepWait");
406 std::string msg = "", xmlmsg = "";
409 a_condition.asXML(result);
412 if (TestManager::instantiate().getDumpHex()) {
413 if (a_message.isEmpty()) {
417 msg = "\n"; msg += a_message.asString(); msg += "\n";
421 if (!a_message.isEmpty()) {
423 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
424 static anna::diameter::codec::Message codecMsg(my_app.getCodecEngine());
425 codecMsg.decode(a_message);
426 xmlmsg = "\n"; xmlmsg += codecMsg.asXMLString(); xmlmsg += "\n";
428 catch (anna::RuntimeException &ex) {
433 if (msg != "") result->createAttribute("MatchedMessage", msg);
434 if (xmlmsg != "") result->createAttribute("MatchedXMLMessage", xmlmsg);
439 bool TestStepWait::do_execute() throw() {
443 void TestStepWait::do_complete() throw() {
444 a_testCase->process(); // next() not invoked; we only want to reactivate the test case
447 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
448 if (a_condition.comply(db/*, matchSessionId*/)) {
449 a_message = db; // store matched
457 void TestStepWait::do_reset() throw() {
459 a_clientSession = NULL;
460 a_serverSession = NULL;
463 ////////////////////////////////////////////////////////////////////////////////////////////////////////
465 ////////////////////////////////////////////////////////////////////////////////////////////////////////
466 anna::xml::Node* TestStepCmd::asXML(anna::xml::Node* parent) const
468 anna::xml::Node* result = TestStep::asXML(parent);
469 //parent->createChild("TestStepCmd");
471 result->createAttribute("Script", (a_script != "") ? a_script:"<no script>");
472 result->createAttribute("Parameters", (a_parameters != "") ? a_parameters:"<no parameters>");
473 if (a_errorMsg != "") result->createAttribute("ErrorMessage", a_errorMsg);
474 if (!a_threadRunning && a_resultCode != -2) {
475 result->createAttribute("ResultCode", a_resultCode);
476 //if (a_output != "") result->createAttribute("Output", a_output);
482 bool TestStepCmd::do_execute() throw() {
483 if (!a_threadRunning /* || a_threadDeprecated DO NOT WANT TO OVERLAP ... */) {
484 // Special tags to replace:
485 std::string cmd = getScript();
487 cmd += getParameters();
489 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID)) != std::string::npos)
490 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID), anna::functions::asString(TestManager::instantiate().getPoolCycle()));
491 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID)) != std::string::npos)
492 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID), anna::functions::asString(a_testCase->getId()));
493 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID)) != std::string::npos)
494 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID), anna::functions::asString(getNumber()));
496 a_thread = std::thread(cmdRunOnThread, this, cmd);
500 return false; // don't go next (wait complete): If system function on thread stucks, then the reset test case will stuck here forever.
501 // We must implement a interrupt procedure for the thread on reset call... TODO !
504 void TestStepCmd::do_complete() throw() {
506 a_threadRunning = false;
507 if (a_threadDeprecated) {
508 a_threadDeprecated = false;
510 setErrorMsg(anna::functions::asString("Step %d deprecated due to previous reset for Test Case %llu", getNumber(), a_testCase->getId()));
511 a_testCase->setState(TestCase::State::Failed);
512 return; // ignore TODO: interrupt the thread to avoid execution of the script
515 if (getResultCode() != 0)
516 a_testCase->setState(TestCase::State::Failed);
518 next(); // next() invoked here because execute() is always false for delay and never advance the iterator
521 void TestStepCmd::do_reset() throw() {
523 if (a_threadRunning) {
524 std::string s_warn = anna::functions::asString("Thread still in progress: deprecating step %d for Test Case %llu", getNumber(), a_testCase->getId());
525 LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
526 a_threadDeprecated = true;