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 <sys/types.h>
25 #include <anna/xml/Compiler.hpp>
26 #include <anna/core/util/Millisecond.hpp>
27 #include <anna/diameter.comm/Message.hpp>
28 #include <anna/diameter.comm/ClientSession.hpp>
29 #include <anna/diameter.comm/ServerSession.hpp>
30 #include <anna/diameter.comm/Server.hpp>
31 #include <anna/core/tracing/Logger.hpp>
32 #include <anna/diameter/codec/functions.hpp>
33 #include <anna/diameter/helpers/base/functions.hpp>
36 #include <OriginHost.hpp>
37 #include <MyDiameterEntity.hpp>
38 #include <MyLocalServer.hpp>
39 #include <TestStep.hpp>
40 #include <TestCase.hpp>
41 #include <TestManager.hpp>
42 #include <TestTimer.hpp>
43 #include <Launcher.hpp>
48 void handle_sigchld(int sig) {
49 while (waitpid((pid_t)(-1 /* any child (the only) */), 0, WNOHANG|WNOWAIT) > 0) {}
52 void cmdRunOnThread (TestStepCmd *step, const std::string &cmd) {
55 step->setThreadRunning(true);
60 sa.sa_handler = &handle_sigchld;
61 sigemptyset(&sa.sa_mask);
62 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
63 if (sigaction(SIGCHLD, &sa, 0) != -1) {
64 status = system(cmd.c_str());
67 FILE *fp = popen(cmd.c_str(), "r");
69 while(fgets(readbuf, sizeof(readbuf), fp))
70 step->appendOutput("\n");
71 step->appendOutput(readbuf);
82 // This can be implemented portably and somewhat more concisely with the signal function if you prefer:
83 // if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
90 char const * str = strerror_r(errno, buf, 256);
91 step->setErrorMsg(anna::functions::asString("errno = %d (%s)", errno, str));
94 step->setResultCode(WEXITSTATUS(status)); // rc = status >>= 8; // divide by 256
96 // TODO: terminate thread when deprecated (RT signal ?)
97 // TODO: mutex the step while setting data here !!
100 void cmdRunOnThreadWithFork (TestStepCmd *step, const std::string &cmd) {
103 step->setThreadRunning(true);
108 if ((cpid = fork()) < 0) {
109 step->setErrorMsg("Error in fork()");
111 else if (cpid == 0) {
113 status = system(cmd.c_str());
114 _exit(WEXITSTATUS(status));
118 step->setChildPid(cpid);
120 w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
123 if (WIFEXITED(status)) {
124 step->setResultCode(WEXITSTATUS(status)); // rc = status >>= 8; // divide by 256
127 else if (WIFSIGNALED(status)) {
128 step->setErrorMsg(anna::functions::asString("killed by signal %d", WTERMSIG(status)));
129 step->setResultCode(128 + WTERMSIG(status));
131 } else if (WIFSTOPPED(status)) {
132 step->setErrorMsg(anna::functions::asString("stopped by signal %d", WSTOPSIG(status)));
133 } else if (WIFCONTINUED(status)) {
134 step->setErrorMsg("continued");
138 step->setErrorMsg("waitpid error");
139 step->setResultCode(-1);
142 } while (!WIFEXITED(status) && !WIFSIGNALED(status));
148 bool decodeMessage(const anna::DataBlock &message, anna::diameter::codec::Message &messageCodec) throw() {
150 if (message.isEmpty())
155 messageCodec.clear();
156 messageCodec.decode(message);
158 catch (anna::RuntimeException &ex) {
168 ////////////////////////////////////////////////////////////////////////////////////////////////////////
170 ////////////////////////////////////////////////////////////////////////////////////////////////////////
171 void TestStep::initialize(TestCase *testCase) {
172 a_testCase = testCase;
174 a_type = Type::Unconfigured;
175 a_beginTimestamp = 0;
177 a_number = testCase->steps() + 1; // testCase is not NULL
180 bool TestStep::decodeMessage(bool trust) throw() {
181 if (a_messageCodec) return true;
182 a_messageCodec = new anna::diameter::codec::Message;
183 if (::decodeMessage(a_message, *a_messageCodec)) return true;
185 LOGDEBUG(anna::Logger::debug("Error DECODING, but trusting it ...", ANNA_FILE_LOCATION));
189 delete a_messageCodec;
190 a_messageCodec = NULL;
194 const char* TestStep::asText(const Type::_v type)
196 static const char* text [] = { "Unconfigured", "Timeout", "Sendxml2e", "Sendxml2c", "Delay", "Wait", "Command" };
200 anna::xml::Node* TestStep::asXML(anna::xml::Node* parent)
202 anna::xml::Node* result = parent->createChild("TestStep");
204 result->createAttribute("Number", a_number);
205 result->createAttribute("Type", asText(a_type));
206 result->createAttribute("Completed", (a_completed ? "yes":"no"));
209 std::string s_aux = a_beginTimestamp.asString();
210 // int deltaMs = (int)(a_beginTimestamp - a_testCase->getStartTimestamp());
211 // if (a_beginTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
212 result->createAttribute("BeginTimestamp", s_aux);
215 s_aux = a_endTimestamp.asString();
216 // deltaMs = (int)(a_endTimestamp - a_testCase->getStartTimestamp());
217 // if (a_endTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
218 result->createAttribute("EndTimestamp", s_aux);
223 std::string TestStep::asXMLString() throw() {
224 anna::xml::Node root("root");
225 return anna::xml::Compiler().apply(asXML(&root));
228 bool TestStep::execute() throw() {
230 int ia = a_testCase->interactiveAmount();
232 if (ia == 0) return false;
233 a_testCase->interactiveExecution();
234 LOGDEBUG(anna::Logger::debug("Interactive execution ...", ANNA_FILE_LOCATION));
235 if (a_executed) return false; // avoid repeating (this implies amount consumption)
238 LOGDEBUG(anna::Logger::debug(anna::functions::asString("EXECUTING %s (step number %d) for Test Case %llu (%p)", asText(a_type), a_number, a_testCase->getId(), this), ANNA_FILE_LOCATION));
239 setBeginTimestamp(anna::functions::millisecond());
244 void TestStep::complete() throw() {
245 LOGDEBUG(anna::Logger::debug(anna::functions::asString("COMPLETE %s (step number %d) for Test Case %llu (%p)", asText(a_type), a_number, a_testCase->getId(), this), ANNA_FILE_LOCATION));
247 setEndTimestamp(anna::functions::millisecond());
251 void TestStep::reset() throw() {
252 LOGDEBUG(anna::Logger::debug(anna::functions::asString("RESET %s (step number %d) for Test Case %llu (%p)", asText(a_type), a_number, a_testCase->getId(), this), ANNA_FILE_LOCATION));
253 // type and testCase kept
256 a_beginTimestamp = 0;
261 void TestStep::next() throw() {
262 a_testCase->nextStep();
263 a_testCase->process();
267 ////////////////////////////////////////////////////////////////////////////////////////////////////////
269 ////////////////////////////////////////////////////////////////////////////////////////////////////////
270 anna::xml::Node* TestStepTimeout::asXML(anna::xml::Node* parent)
272 anna::xml::Node* result = TestStep::asXML(parent); // end timestamp will be 0 if test finished OK
273 //parent->createChild("TestStepTimeout");
274 result->createAttribute("Timeout", a_timeout.asString());
279 bool TestStepTimeout::do_execute() throw() {
281 a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_timeout, TestTimer::Type::TimeLeft);
283 catch (anna::RuntimeException &ex) {
285 a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
286 a_testCase->setState(TestCase::State::Failed);
289 return true; // go next
292 void TestStepTimeout::do_complete() throw() {
293 int stepNumber = getNumber();
294 if (stepNumber == a_testCase->steps()) {
295 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)
296 a_testCase->setState(TestCase::State::Success);
298 else if (a_testCase->getState() == TestCase::State::InProgress) { // sure
299 a_testCase->addDebugSummaryHint(anna::functions::asString("Timeout expired (step number %d) before test case finished", stepNumber)); // before report (when set Failed state)
300 a_testCase->setState(TestCase::State::Failed);
306 void TestStepTimeout::do_reset() throw() {
308 TestManager::instantiate().cancelTimer(a_timer);
310 catch (anna::RuntimeException &ex) {
314 //a_timeout = 0; THIS IS CONFIGURATION INFO
317 ////////////////////////////////////////////////////////////////////////////////////////////////////////
319 ////////////////////////////////////////////////////////////////////////////////////////////////////////
320 anna::xml::Node* TestStepSendxml::asXML(anna::xml::Node* parent)
322 anna::xml::Node* result = TestStep::asXML(parent);
323 //parent->createChild("TestStepSendxml");
324 std::string msg = "", xmlmsg = "";
327 if (TestManager::instantiate().getDumpHex()) {
328 if (a_message.isEmpty()) {
332 msg = "\n"; msg += a_message.asString(); msg += "\n";
336 if (decodeMessage()) {
338 xmlmsg += a_messageCodec->asXMLString();
342 xmlmsg = "<unable to decode, check traces>";
345 if (msg != "") result->createAttribute("Message", msg);
346 if (xmlmsg != "") result->createAttribute("XMLMessage", xmlmsg);
347 result->createAttribute("Expired", (a_expired ? "yes":"no"));
348 if (a_waitForRequestStepNumber != -1)
349 result->createAttribute("WaitForRequestStepNumber", a_waitForRequestStepNumber);
354 bool TestStepSendxml::do_execute() throw() {
355 bool success = false;
356 std::string failReason, s_warn;
357 MyDiameterEntity *entity = a_originHost->getEntity(); // by default
358 MyLocalServer *localServer = a_originHost->getDiameterServer(); // by default
359 const TestStepWait *tsw = NULL;
361 // Create comm message:
362 anna::diameter::comm::Message *msg = a_originHost->createCommMessage();
364 msg->setBody(a_message);
367 // Update sequence for answers:
368 if (a_waitForRequestStepNumber != -1) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
369 // Request which was received:
370 tsw = static_cast<const TestStepWait*>(a_testCase->getStep(a_waitForRequestStepNumber));
372 const anna::DataBlock &request = tsw->getMsgDataBlock();
373 anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(request);
374 anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(request);
377 anna::diameter::codec::functions::setHopByHop(a_message, hbh);
378 anna::diameter::codec::functions::setEndToEnd(a_message, ete);
380 // Check Session-Id for warning ...
381 std::string sessionIdAnswer = anna::diameter::helpers::base::functions::getSessionId(a_message);
382 std::string sessionIdRequest = anna::diameter::helpers::base::functions::getSessionId(request);
384 if (sessionIdRequest != sessionIdAnswer) {
385 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());
386 LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
387 a_testCase->addDebugSummaryHint(s_warn);
391 if (getType() == Type::Sendxml2e) {
392 anna::diameter::comm::ClientSession *usedClientSession = NULL;
394 if (tsw) { // is an answer for a received request on wait condition
395 anna::diameter::comm::ClientSession *clientSession = tsw->getClientSession();
397 /* response NULL (is an answer) */clientSession->send(msg);
399 usedClientSession = clientSession;
402 failReason = "Reference wait step didn't store a valid client session. Unable to send the message";
403 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
408 success = entity->send(msg);
409 anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
410 usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
413 failReason = "There is no diameter entity currently configured. Unable to send the message";
414 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
416 } // else (normal sending)
419 if(a_originHost->logEnabled()) {
420 if (decodeMessage(true /* trust */)) {
421 std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // shouldn't happen
422 a_originHost->writeLogFile(*a_messageCodec, (success ? "sent2e" : "send2eError"), detail);
426 else if (getType() == Type::Sendxml2c) {
427 anna::diameter::comm::ServerSession *usedServerSession = NULL;
429 if (tsw) { // is an answer for a received request on wait condition
430 anna::diameter::comm::ServerSession *serverSession = tsw->getServerSession();
432 /* response NULL (is an answer) */serverSession->send(msg);
434 usedServerSession = serverSession;
437 failReason = "Reference wait step didn't store a valid server session. Unable to send the message";
438 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
443 success = localServer->send(msg);
444 usedServerSession = localServer->getLastUsedResource();
447 failReason = "There is no diameter local server currently configured. Unable to send the message";
448 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
450 } // else (normal sending)
453 if(a_originHost->logEnabled()) {
454 if (decodeMessage(true /* trust */)) {
455 std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // shouldn't happen
456 a_originHost->writeLogFile(*a_messageCodec, (success ? "sent2c" : "send2cError"), detail);
461 } catch(anna::RuntimeException &ex) {
462 failReason = ex.asString();
466 a_originHost->releaseCommMessage(msg);
469 a_testCase->addDebugSummaryHint(failReason); // before report (when set Failed state);
470 a_testCase->setState(TestCase::State::Failed);
476 return success; // go next if sent was OK
479 void TestStepSendxml::do_reset() throw() {
482 //a_messageAlreadyDecoded = false;
485 ////////////////////////////////////////////////////////////////////////////////////////////////////////
487 ////////////////////////////////////////////////////////////////////////////////////////////////////////
488 anna::xml::Node* TestStepDelay::asXML(anna::xml::Node* parent)
490 anna::xml::Node* result = TestStep::asXML(parent);
491 //parent->createChild("TestStepDelay");
493 result->createAttribute("Delay", ((a_delay == 0) ? "dummy step, no delay" : a_delay.asString()));
498 bool TestStepDelay::do_execute() throw() {
499 if (a_delay == 0) { complete(); return true; } // special case
501 a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_delay, TestTimer::Type::Delay);
503 catch (anna::RuntimeException &ex) {
505 a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
506 a_testCase->setState(TestCase::State::Failed);
509 return false; // don't go next (wait complete)
512 void TestStepDelay::do_complete() throw() {
513 if (a_delay == 0) return; // special case
515 next(); // next() invoked here because execute() is always false for delay and never advance the iterator
516 // TODO, avoid this recursion
519 void TestStepDelay::do_reset() throw() {
520 if (a_delay == 0) return; // special case
522 TestManager::instantiate().cancelTimer(a_timer);
524 catch (anna::RuntimeException &ex) {
528 //a_delay = 0; THIS IS CONFIGURATION INFO
531 ////////////////////////////////////////////////////////////////////////////////////////////////////////
533 ////////////////////////////////////////////////////////////////////////////////////////////////////////
534 void TestStepWait::setCondition(bool fromEntity,
535 const std::string &code, const std::string &bitR, const std::string &hopByHop, const std::string &applicationId,
536 const std::string &sessionId, const std::string &resultCode,
537 const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw() {
539 a_condition.setReceivedFromEntity(fromEntity);
540 a_condition.setCode(code);
541 a_condition.setBitR(bitR);
542 a_condition.setResultCode(resultCode);
543 a_condition.setSessionId(sessionId);
544 a_condition.setHopByHop(hopByHop);
545 a_condition.setMsisdn(msisdn);
546 a_condition.setImsi(imsi);
547 a_condition.setServiceContextId(serviceContextId);
550 void TestStepWait::setCondition(bool fromEntity, const std::string ®exp) throw() {
552 a_condition.setReceivedFromEntity(fromEntity);
553 a_condition.setRegexp(regexp);
556 anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent)
558 anna::xml::Node* result = TestStep::asXML(parent);
559 //parent->createChild("TestStepWait");
560 std::string msg = "", xmlmsg = "";
563 a_condition.asXML(result);
566 if (TestManager::instantiate().getDumpHex()) {
567 if (a_message.isEmpty()) {
571 msg = "\n"; msg += a_message.asString(); msg += "\n";
575 if (decodeMessage()) {
577 xmlmsg += a_messageCodec->asXMLString();
581 xmlmsg = "<unable to decode, check traces>";
584 if (msg != "") result->createAttribute("MatchedMessage", msg);
585 if (xmlmsg != "") result->createAttribute("MatchedXMLMessage", xmlmsg);
586 if (a_clientSession) result->createAttribute("ClientSessionOrigin", anna::functions::asString("%p", a_clientSession));
587 if (a_serverSession) result->createAttribute("ServerSessionOrigin", anna::functions::asString("%p", a_serverSession));
592 bool TestStepWait::do_execute() throw() {
596 void TestStepWait::do_complete() throw() {
597 //a_testCase->process(); // next() not invoked; we only want to reactivate the test case
598 // avoid stack overflow: we will process the test case externally when incoming message is fulfilled (TestCase.cpp), and TestManager is noticed
601 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
602 if (a_condition.comply(db/*, matchSessionId*/)) {
603 a_message = db; // store matched
611 void TestStepWait::do_reset() throw() {
613 a_clientSession = NULL;
614 a_serverSession = NULL;
617 ////////////////////////////////////////////////////////////////////////////////////////////////////////
619 ////////////////////////////////////////////////////////////////////////////////////////////////////////
620 anna::xml::Node* TestStepCmd::asXML(anna::xml::Node* parent)
622 anna::xml::Node* result = TestStep::asXML(parent);
623 //parent->createChild("TestStepCmd");
625 result->createAttribute("Script", (a_script != "") ? a_script:"<no script>");
626 if (a_errorMsg != "") result->createAttribute("ErrorMessage", a_errorMsg);
627 if (a_threadRunning) {
628 if (a_childPid != -1)
629 result->createAttribute("ChildPid", a_childPid);
632 if (a_resultCode != -2) {
633 result->createAttribute("ResultCode", a_resultCode);
634 //if (a_output != "") result->createAttribute("Output", a_output);
641 bool TestStepCmd::do_execute() throw() {
642 if (!a_threadRunning /* || a_threadDeprecated DO NOT WANT TO OVERLAP ... */) {
643 // Special tags to replace:
644 std::string cmd = getScript();
646 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID)) != std::string::npos)
647 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID), anna::functions::asString(TestManager::instantiate().getPoolCycle()));
648 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID)) != std::string::npos)
649 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID), anna::functions::asString(a_testCase->getId()));
650 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID)) != std::string::npos)
651 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID), anna::functions::asString(getNumber()));
653 a_thread = std::thread(cmdRunOnThread, this, cmd);
654 //a_thread = std::thread(cmdRunOnThreadWithFork, this, cmd);
659 return false; // don't go next (wait complete): If system function on thread stucks, then the reset test case will stuck here forever.
660 // We must implement a interrupt procedure for the thread on reset call... TODO !
663 void TestStepCmd::do_complete() throw() {
665 a_threadRunning = false;
666 if (a_threadDeprecated) {
667 a_threadDeprecated = false;
669 setErrorMsg(anna::functions::asString("Step %d deprecated due to previous reset for Test Case %llu", getNumber(), a_testCase->getId()));
670 a_testCase->setState(TestCase::State::Failed);
671 return; // ignore TODO: interrupt the thread to avoid execution of the script
674 if (getResultCode() != 0)
675 a_testCase->setState(TestCase::State::Failed);
677 next(); // next() invoked here because execute() is always false for delay and never advance the iterator
678 // TODO, avoid this recursion
681 void TestStepCmd::do_reset() throw() {
683 if (a_threadRunning) {
684 std::string s_warn = anna::functions::asString("Thread still in progress: deprecating step %d for Test Case %llu", getNumber(), a_testCase->getId());
685 LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
686 a_threadDeprecated = true;
688 // if (a_threadRunning) {
689 // std::string s_warn = anna::functions::asString("Thread still in progress: killing child pid %d within step %d for Test Case %llu", a_childPid, getNumber(), a_testCase->getId());
690 // LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
691 // kill (a_childPid, SIGKILL);