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/diameter.comm/ClientSession.hpp>
24 #include <anna/diameter.comm/ServerSession.hpp>
25 #include <anna/diameter.comm/Server.hpp>
26 #include <anna/core/tracing/Logger.hpp>
27 #include <anna/diameter/codec/functions.hpp>
28 #include <anna/diameter/helpers/base/functions.hpp>
31 #include <RealmNode.hpp>
32 #include <MyDiameterEntity.hpp>
33 #include <MyLocalServer.hpp>
34 #include <TestStep.hpp>
35 #include <TestCase.hpp>
36 #include <TestManager.hpp>
37 #include <TestTimer.hpp>
38 #include <Launcher.hpp>
43 void handle_sigchld(int sig) {
44 while (waitpid((pid_t)(-1 /* any child (the only) */), 0, WNOHANG|WNOWAIT) > 0) {}
47 void cmdRunOnThread (TestStepCmd *step, const std::string &cmd) {
50 step->setThreadRunning(true);
55 sa.sa_handler = &handle_sigchld;
56 sigemptyset(&sa.sa_mask);
57 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
58 if (sigaction(SIGCHLD, &sa, 0) != -1) {
59 status = system(cmd.c_str());
62 FILE *fp = popen(cmd.c_str(), "r");
64 while(fgets(readbuf, sizeof(readbuf), fp))
65 step->appendOutput("\n");
66 step->appendOutput(readbuf);
77 // This can be implemented portably and somewhat more concisely with the signal function if you prefer:
78 // if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
85 char const * str = strerror_r(errno, buf, 256);
86 step->setErrorMsg(anna::functions::asString("errno = %d (%s)", errno, str));
89 step->setResultCode(WEXITSTATUS(status)); // rc = status >>= 8; // divide by 256
91 // TODO: terminate thread when deprecated (RT signal ?)
92 // TODO: mutex the step while setting data here !!
95 bool decodeMessage(const anna::DataBlock &message, anna::diameter::codec::Message &messageCodec) throw() {
97 if (message.isEmpty())
102 messageCodec.setEngine(NULL); // perhaps we will need another codec engine ...
103 messageCodec.decode(message);
105 catch (anna::RuntimeException &ex) {
115 ////////////////////////////////////////////////////////////////////////////////////////////////////////
117 ////////////////////////////////////////////////////////////////////////////////////////////////////////
118 void TestStep::initialize(TestCase *testCase) {
119 a_testCase = testCase;
121 a_type = Type::Unconfigured;
122 a_beginTimestamp = 0;
124 a_number = testCase->steps() + 1; // testCase is not NULL
127 bool TestStep::decodeMessage() throw() {
128 if (a_messageCodec) return true;
129 a_messageCodec = new anna::diameter::codec::Message;
130 if (::decodeMessage(a_message, *a_messageCodec)) return true;
132 delete a_messageCodec;
133 a_messageCodec = NULL;
137 const char* TestStep::asText(const Type::_v type)
139 static const char* text [] = { "Unconfigured", "Timeout", "Sendxml2e", "Sendxml2c", "Delay", "Wait", "Command" };
143 anna::xml::Node* TestStep::asXML(anna::xml::Node* parent)
145 anna::xml::Node* result = parent->createChild("TestStep");
147 result->createAttribute("Number", a_number);
148 result->createAttribute("Type", asText(a_type));
149 result->createAttribute("Completed", (a_completed ? "yes":"no"));
152 std::string s_aux = a_beginTimestamp.asString();
153 // int deltaMs = (int)(a_beginTimestamp - a_testCase->getStartTimestamp());
154 // if (a_beginTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
155 result->createAttribute("BeginTimestamp", s_aux);
158 s_aux = a_endTimestamp.asString();
159 // deltaMs = (int)(a_endTimestamp - a_testCase->getStartTimestamp());
160 // if (a_endTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
161 result->createAttribute("EndTimestamp", s_aux);
166 std::string TestStep::asXMLString() throw() {
167 anna::xml::Node root("root");
168 return anna::xml::Compiler().apply(asXML(&root));
171 bool TestStep::execute() throw() {
173 int ia = a_testCase->interactiveAmount();
175 if (ia == 0) return false;
176 a_testCase->interactiveExecution();
177 LOGDEBUG(anna::Logger::debug("Interactive execution ...", ANNA_FILE_LOCATION));
178 if (a_executed) return false; // avoid repeating (this implies amount consumption)
181 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));
182 setBeginTimestamp(anna::functions::millisecond());
187 void TestStep::complete() throw() {
188 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));
190 setEndTimestamp(anna::functions::millisecond());
194 void TestStep::reset() throw() {
195 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));
196 // type and testCase kept
199 a_beginTimestamp = 0;
204 void TestStep::next() throw() {
205 a_testCase->nextStep();
206 a_testCase->process();
210 ////////////////////////////////////////////////////////////////////////////////////////////////////////
212 ////////////////////////////////////////////////////////////////////////////////////////////////////////
213 anna::xml::Node* TestStepTimeout::asXML(anna::xml::Node* parent)
215 anna::xml::Node* result = TestStep::asXML(parent); // end timestamp will be 0 if test finished OK
216 //parent->createChild("TestStepTimeout");
217 result->createAttribute("Timeout", a_timeout.asString());
222 bool TestStepTimeout::do_execute() throw() {
224 a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_timeout, TestTimer::Type::TimeLeft);
226 catch (anna::RuntimeException &ex) {
228 a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
229 a_testCase->setState(TestCase::State::Failed);
232 return true; // go next
235 void TestStepTimeout::do_complete() throw() {
236 int stepNumber = getNumber();
237 if (stepNumber == a_testCase->steps()) {
238 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)
239 a_testCase->setState(TestCase::State::Success);
241 else if (a_testCase->getState() == TestCase::State::InProgress) { // sure
242 a_testCase->addDebugSummaryHint(anna::functions::asString("Timeout expired (step number %d) before test case finished", stepNumber)); // before report (when set Failed state)
243 a_testCase->setState(TestCase::State::Failed);
249 void TestStepTimeout::do_reset() throw() {
250 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));
253 TestManager::instantiate().cancelTimer(a_timer);
255 catch (anna::RuntimeException &ex) {
259 //a_timeout = 0; THIS IS CONFIGURATION INFO
262 ////////////////////////////////////////////////////////////////////////////////////////////////////////
264 ////////////////////////////////////////////////////////////////////////////////////////////////////////
265 anna::xml::Node* TestStepSendxml::asXML(anna::xml::Node* parent)
267 anna::xml::Node* result = TestStep::asXML(parent);
268 //parent->createChild("TestStepSendxml");
269 std::string msg = "", xmlmsg = "";
272 if (TestManager::instantiate().getDumpHex()) {
273 if (a_message.isEmpty()) {
277 msg = "\n"; msg += a_message.asString(); msg += "\n";
281 if (decodeMessage()) {
283 xmlmsg += a_messageCodec->asXMLString();
287 if (msg != "") result->createAttribute("Message", msg);
288 if (xmlmsg != "") result->createAttribute("XMLMessage", xmlmsg);
289 result->createAttribute("Expired", (a_expired ? "yes":"no"));
290 if (a_waitForRequestStepNumber != -1)
291 result->createAttribute("WaitForRequestStepNumber", a_waitForRequestStepNumber);
296 bool TestStepSendxml::do_execute() throw() {
297 bool success = false;
298 std::string failReason, s_warn;
299 MyDiameterEntity *entity = a_realmNode->getEntity(); // by default
300 MyLocalServer *localServer = a_realmNode->getDiameterServer(); // by default
301 const TestStepWait *tsw = NULL;
303 // Create comm message:
304 anna::diameter::comm::Message *msg = a_realmNode->createCommMessage();
306 msg->setBody(a_message);
309 // Update sequence for answers:
310 if (a_waitForRequestStepNumber != -1) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
311 // Request which was received:
312 tsw = (const TestStepWait*)(a_testCase->getStep(a_waitForRequestStepNumber));
313 const anna::DataBlock &request = tsw->getMsgDataBlock();
314 anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(request);
315 anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(request);
317 anna::diameter::codec::functions::setHopByHop(a_message, hbh);
318 anna::diameter::codec::functions::setEndToEnd(a_message, ete);
320 // Check Session-Id for warning ...
321 std::string sessionIdAnswer = anna::diameter::helpers::base::functions::getSessionId(a_message);
322 std::string sessionIdRequest = anna::diameter::helpers::base::functions::getSessionId(request);
323 if (sessionIdRequest != sessionIdAnswer) {
324 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());
325 LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
326 a_testCase->addDebugSummaryHint(s_warn);
330 if (getType() == Type::Sendxml2e) {
331 anna::diameter::comm::ClientSession *usedClientSession = NULL;
333 if (tsw) { // is an answer for a received request on wait condition
334 anna::diameter::comm::ClientSession *clientSession = tsw->getClientSession();
336 /* response NULL (is an answer) */clientSession->send(msg);
338 usedClientSession = clientSession;
341 failReason = "Reference wait step didn't store a valid client session. Unable to send the message";
342 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
347 success = entity->send(msg);
348 anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
349 usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
352 failReason = "There is no diameter entity currently configured. Unable to send the message";
353 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
355 } // else (normal sending)
358 if(a_realmNode->logEnabled()) {
359 if (decodeMessage()) {
360 std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // shouldn't happen
361 a_realmNode->writeLogFile(*a_messageCodec, (success ? "sent2e" : "send2eError"), detail);
365 else if (getType() == Type::Sendxml2c) {
366 anna::diameter::comm::ServerSession *usedServerSession = NULL;
368 if (tsw) { // is an answer for a received request on wait condition
369 anna::diameter::comm::ServerSession *serverSession = tsw->getServerSession();
371 /* response NULL (is an answer) */serverSession->send(msg);
373 usedServerSession = serverSession;
376 failReason = "Reference wait step didn't store a valid server session. Unable to send the message";
377 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
382 success = localServer->send(msg);
383 usedServerSession = localServer->getLastUsedResource();
386 failReason = "There is no diameter local server currently configured. Unable to send the message";
387 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
389 } // else (normal sending)
392 if(a_realmNode->logEnabled()) {
393 if (decodeMessage()) {
394 std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // shouldn't happen
395 a_realmNode->writeLogFile(*a_messageCodec, (success ? "sent2c" : "send2cError"), detail);
400 } catch(anna::RuntimeException &ex) {
401 failReason = ex.asString();
405 a_realmNode->releaseCommMessage(msg);
408 a_testCase->addDebugSummaryHint(failReason); // before report (when set Failed state);
409 a_testCase->setState(TestCase::State::Failed);
415 return success; // go next if sent was OK
418 void TestStepSendxml::do_reset() throw() {
421 //a_messageAlreadyDecoded = false;
424 ////////////////////////////////////////////////////////////////////////////////////////////////////////
426 ////////////////////////////////////////////////////////////////////////////////////////////////////////
427 anna::xml::Node* TestStepDelay::asXML(anna::xml::Node* parent)
429 anna::xml::Node* result = TestStep::asXML(parent);
430 //parent->createChild("TestStepDelay");
432 result->createAttribute("Delay", a_delay.asString());
437 bool TestStepDelay::do_execute() throw() {
439 a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_delay, TestTimer::Type::Delay);
441 catch (anna::RuntimeException &ex) {
443 a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
444 a_testCase->setState(TestCase::State::Failed);
447 return false; // don't go next (wait complete)
450 void TestStepDelay::do_complete() throw() {
452 next(); // next() invoked here because execute() is always false for delay and never advance the iterator
455 void TestStepDelay::do_reset() throw() {
457 TestManager::instantiate().cancelTimer(a_timer);
459 catch (anna::RuntimeException &ex) {
463 //a_delay = 0; THIS IS CONFIGURATION INFO
466 ////////////////////////////////////////////////////////////////////////////////////////////////////////
468 ////////////////////////////////////////////////////////////////////////////////////////////////////////
469 void TestStepWait::setCondition(bool fromEntity,
470 const std::string &code, const std::string &bitR, const std::string &hopByHop, const std::string &applicationId,
471 const std::string &sessionId, const std::string &resultCode,
472 const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw() {
474 a_condition.setReceivedFromEntity(fromEntity);
475 a_condition.setCode(code);
476 a_condition.setBitR(bitR);
477 a_condition.setResultCode(resultCode);
478 a_condition.setSessionId(sessionId);
479 a_condition.setHopByHop(hopByHop);
480 a_condition.setMsisdn(msisdn);
481 a_condition.setImsi(imsi);
482 a_condition.setServiceContextId(serviceContextId);
485 void TestStepWait::setCondition(bool fromEntity, const std::string ®exp) throw() {
487 a_condition.setReceivedFromEntity(fromEntity);
488 a_condition.setRegexp(regexp);
491 anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent)
493 anna::xml::Node* result = TestStep::asXML(parent);
494 //parent->createChild("TestStepWait");
495 std::string msg = "", xmlmsg = "";
498 a_condition.asXML(result);
501 if (TestManager::instantiate().getDumpHex()) {
502 if (a_message.isEmpty()) {
506 msg = "\n"; msg += a_message.asString(); msg += "\n";
510 if (decodeMessage()) {
512 xmlmsg += a_messageCodec->asXMLString();
516 if (msg != "") result->createAttribute("MatchedMessage", msg);
517 if (xmlmsg != "") result->createAttribute("MatchedXMLMessage", xmlmsg);
522 bool TestStepWait::do_execute() throw() {
526 void TestStepWait::do_complete() throw() {
527 //a_testCase->process(); // next() not invoked; we only want to reactivate the test case
528 // avoid stack overflow: we will process the test case externally when incoming message is fulfilled (TestCase.cpp), and TestManager is noticed
531 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
532 if (a_condition.comply(db/*, matchSessionId*/)) {
533 a_message = db; // store matched
541 void TestStepWait::do_reset() throw() {
543 a_clientSession = NULL;
544 a_serverSession = NULL;
547 ////////////////////////////////////////////////////////////////////////////////////////////////////////
549 ////////////////////////////////////////////////////////////////////////////////////////////////////////
550 anna::xml::Node* TestStepCmd::asXML(anna::xml::Node* parent)
552 anna::xml::Node* result = TestStep::asXML(parent);
553 //parent->createChild("TestStepCmd");
555 result->createAttribute("Script", (a_script != "") ? a_script:"<no script>");
556 if (a_errorMsg != "") result->createAttribute("ErrorMessage", a_errorMsg);
557 if (!a_threadRunning && a_resultCode != -2) {
558 result->createAttribute("ResultCode", a_resultCode);
559 //if (a_output != "") result->createAttribute("Output", a_output);
565 bool TestStepCmd::do_execute() throw() {
566 if (!a_threadRunning /* || a_threadDeprecated DO NOT WANT TO OVERLAP ... */) {
567 // Special tags to replace:
568 std::string cmd = getScript();
570 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID)) != std::string::npos)
571 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID), anna::functions::asString(TestManager::instantiate().getPoolCycle()));
572 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID)) != std::string::npos)
573 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID), anna::functions::asString(a_testCase->getId()));
574 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID)) != std::string::npos)
575 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID), anna::functions::asString(getNumber()));
577 a_thread = std::thread(cmdRunOnThread, this, cmd);
581 return false; // don't go next (wait complete): If system function on thread stucks, then the reset test case will stuck here forever.
582 // We must implement a interrupt procedure for the thread on reset call... TODO !
585 void TestStepCmd::do_complete() throw() {
587 a_threadRunning = false;
588 if (a_threadDeprecated) {
589 a_threadDeprecated = false;
591 setErrorMsg(anna::functions::asString("Step %d deprecated due to previous reset for Test Case %llu", getNumber(), a_testCase->getId()));
592 a_testCase->setState(TestCase::State::Failed);
593 return; // ignore TODO: interrupt the thread to avoid execution of the script
596 if (getResultCode() != 0)
597 a_testCase->setState(TestCase::State::Failed);
599 next(); // next() invoked here because execute() is always false for delay and never advance the iterator
602 void TestStepCmd::do_reset() throw() {
604 if (a_threadRunning) {
605 std::string s_warn = anna::functions::asString("Thread still in progress: deprecating step %d for Test Case %llu", getNumber(), a_testCase->getId());
606 LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
607 a_threadDeprecated = true;