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/Message.hpp>
28 #include <anna/diameter/codec/functions.hpp>
29 #include <anna/diameter/helpers/base/functions.hpp>
32 #include <RealmNode.hpp>
33 #include <MyDiameterEntity.hpp>
34 #include <MyLocalServer.hpp>
35 #include <TestStep.hpp>
36 #include <Launcher.hpp>
37 #include <TestCase.hpp>
38 #include <TestManager.hpp>
39 #include <TestTimer.hpp>
44 void handle_sigchld(int sig) {
45 while (waitpid((pid_t)(-1 /* any child (the only) */), 0, WNOHANG|WNOWAIT) > 0) {}
48 void cmdRunOnThread (TestStepCmd *step, const std::string &cmd) {
51 step->setThreadRunning(true);
56 sa.sa_handler = &handle_sigchld;
57 sigemptyset(&sa.sa_mask);
58 sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
59 if (sigaction(SIGCHLD, &sa, 0) != -1) {
60 status = system(cmd.c_str());
63 FILE *fp = popen(cmd.c_str(), "r");
65 while(fgets(readbuf, sizeof(readbuf), fp))
66 step->appendOutput("\n");
67 step->appendOutput(readbuf);
78 // This can be implemented portably and somewhat more concisely with the signal function if you prefer:
79 // if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
86 char const * str = strerror_r(errno, buf, 256);
87 step->setErrorMsg(anna::functions::asString("errno = %d (%s)", errno, str));
90 step->setResultCode(WEXITSTATUS(status)); // rc = status >>= 8; // divide by 256
92 // TODO: terminate thread when deprecated (RT signal ?)
93 // TODO: mutex the step while setting data here !!
96 bool decodeMessage(const anna::DataBlock &message, anna::diameter::codec::Message *messageCodec) throw() {
98 if (message.isEmpty())
104 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
105 messageCodec = new anna::diameter::codec::Message(my_app.getCodecEngine());
108 messageCodec->decode(message);
110 catch (anna::RuntimeException &ex) {
121 ////////////////////////////////////////////////////////////////////////////////////////////////////////
123 ////////////////////////////////////////////////////////////////////////////////////////////////////////
124 void TestStep::initialize(TestCase *testCase) {
125 a_testCase = testCase;
127 a_type = Type::Unconfigured;
128 a_beginTimestamp = 0;
130 a_number = testCase->steps() + 1; // testCase is not NULL
133 const char* TestStep::asText(const Type::_v type)
135 static const char* text [] = { "Unconfigured", "Timeout", "Sendxml2e", "Sendxml2c", "Delay", "Wait", "Cmd" };
139 anna::xml::Node* TestStep::asXML(anna::xml::Node* parent) const
141 anna::xml::Node* result = parent->createChild("TestStep");
143 result->createAttribute("Number", a_number);
144 result->createAttribute("Type", asText(a_type));
145 result->createAttribute("Completed", (a_completed ? "yes":"no"));
148 std::string s_aux = a_beginTimestamp.asString();
149 // int deltaMs = (int)(a_beginTimestamp - a_testCase->getStartTimestamp());
150 // if (a_beginTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
151 result->createAttribute("BeginTimestamp", s_aux);
154 s_aux = a_endTimestamp.asString();
155 // deltaMs = (int)(a_endTimestamp - a_testCase->getStartTimestamp());
156 // if (a_endTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
157 result->createAttribute("EndTimestamp", s_aux);
162 std::string TestStep::asXMLString() const throw() {
163 anna::xml::Node root("root");
164 return anna::xml::Compiler().apply(asXML(&root));
167 bool TestStep::execute() throw() {
168 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));
169 setBeginTimestamp(anna::functions::millisecond());
173 void TestStep::complete() throw() {
174 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));
176 setEndTimestamp(anna::functions::millisecond());
180 void TestStep::reset() throw() {
181 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));
182 // type and testCase kept
184 a_beginTimestamp = 0;
189 void TestStep::next() throw() {
190 a_testCase->nextStep();
191 a_testCase->process();
195 ////////////////////////////////////////////////////////////////////////////////////////////////////////
197 ////////////////////////////////////////////////////////////////////////////////////////////////////////
198 anna::xml::Node* TestStepTimeout::asXML(anna::xml::Node* parent) const
200 anna::xml::Node* result = TestStep::asXML(parent); // end timestamp will be 0 if test finished OK
201 //parent->createChild("TestStepTimeout");
202 result->createAttribute("Timeout", a_timeout.asString());
207 bool TestStepTimeout::do_execute() throw() {
209 a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_timeout, TestTimer::Type::TimeLeft);
211 catch (anna::RuntimeException &ex) {
213 a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
214 a_testCase->setState(TestCase::State::Failed);
217 return true; // go next
220 void TestStepTimeout::do_complete() throw() {
221 int stepNumber = getNumber();
222 if (stepNumber == a_testCase->steps()) {
223 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)
224 a_testCase->setState(TestCase::State::Success);
226 else if (a_testCase->getState() == TestCase::State::InProgress) { // sure
227 a_testCase->addDebugSummaryHint(anna::functions::asString("Timeout expired (step number %d) before test case finished", stepNumber)); // before report (when set Failed state)
228 a_testCase->setState(TestCase::State::Failed);
234 void TestStepTimeout::do_reset() throw() {
235 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));
238 TestManager::instantiate().cancelTimer(a_timer);
240 catch (anna::RuntimeException &ex) {
244 //a_timeout = 0; THIS IS CONFIGURATION INFO
247 ////////////////////////////////////////////////////////////////////////////////////////////////////////
249 ////////////////////////////////////////////////////////////////////////////////////////////////////////
250 TestStepSendxml::~TestStepSendxml() {
251 delete a_messageCodec;
252 a_messageCodec = NULL;
255 anna::xml::Node* TestStepSendxml::asXML(anna::xml::Node* parent) const
257 anna::xml::Node* result = TestStep::asXML(parent);
258 //parent->createChild("TestStepSendxml");
259 std::string msg = "", xmlmsg = "";
262 if (TestManager::instantiate().getDumpHex()) {
263 if (a_message.isEmpty()) {
267 msg = "\n"; msg += a_message.asString(); msg += "\n";
271 if (decodeMessage(a_message, a_messageCodec)) {
273 xmlmsg += a_messageCodec->asXMLString();
277 if (msg != "") result->createAttribute("Message", msg);
278 if (xmlmsg != "") result->createAttribute("XMLMessage", xmlmsg);
279 result->createAttribute("Expired", (a_expired ? "yes":"no"));
280 if (a_waitForRequestStepNumber != -1)
281 result->createAttribute("WaitForRequestStepNumber", a_waitForRequestStepNumber);
286 bool TestStepSendxml::do_execute() throw() {
287 bool success = false;
288 std::string failReason, s_warn;
289 MyDiameterEntity *entity = a_realmNode->getEntity(); // by default
290 MyLocalServer *localServer = a_realmNode->getDiameterServer(); // by default
291 const TestStepWait *tsw = NULL;
293 // Create comm message:
294 anna::diameter::comm::Message *msg = a_realmNode->createCommMessage();
296 msg->setBody(a_message);
299 // Update sequence for answers:
300 if (a_waitForRequestStepNumber != -1) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
301 // Request which was received:
302 tsw = (const TestStepWait*)(a_testCase->getStep(a_waitForRequestStepNumber));
303 const anna::DataBlock &request = tsw->getMsgDataBlock();
304 anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(request);
305 anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(request);
307 anna::diameter::codec::functions::setHopByHop(a_message, hbh);
308 anna::diameter::codec::functions::setEndToEnd(a_message, ete);
310 // Check Session-Id for warning ...
311 std::string sessionIdAnswer = anna::diameter::helpers::base::functions::getSessionId(a_message);
312 std::string sessionIdRequest = anna::diameter::helpers::base::functions::getSessionId(request);
313 if (sessionIdRequest != sessionIdAnswer) {
314 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());
315 LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
316 a_testCase->addDebugSummaryHint(s_warn);
320 if (getType() == Type::Sendxml2e) {
321 anna::diameter::comm::ClientSession *usedClientSession = NULL;
323 if (tsw) { // is an answer for a received request on wait condition
324 anna::diameter::comm::ClientSession *clientSession = tsw->getClientSession();
326 /* response NULL (is an answer) */clientSession->send(msg);
328 usedClientSession = clientSession;
331 failReason = "Reference wait step didn't store a valid client session. Unable to send the message";
332 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
337 success = entity->send(msg);
338 anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
339 usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
342 failReason = "There is no diameter entity currently configured. Unable to send the message";
343 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
345 } // else (normal sending)
348 if(a_realmNode->logEnabled()) {
350 decodeMessage(a_message, a_messageCodec);
352 if (a_messageCodec) {
353 std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // shouldn't happen
354 a_realmNode->writeLogFile(*a_messageCodec, (success ? "sent2e" : "send2eError"), detail);
358 else if (getType() == Type::Sendxml2c) {
359 anna::diameter::comm::ServerSession *usedServerSession = NULL;
361 if (tsw) { // is an answer for a received request on wait condition
362 anna::diameter::comm::ServerSession *serverSession = tsw->getServerSession();
364 /* response NULL (is an answer) */serverSession->send(msg);
366 usedServerSession = serverSession;
369 failReason = "Reference wait step didn't store a valid server session. Unable to send the message";
370 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
375 success = localServer->send(msg);
376 usedServerSession = localServer->getLastUsedResource();
379 failReason = "There is no diameter local server currently configured. Unable to send the message";
380 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
382 } // else (normal sending)
385 if(a_realmNode->logEnabled()) {
387 decodeMessage(a_message, a_messageCodec);
389 if (a_messageCodec) {
390 std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // shouldn't happen
391 a_realmNode->writeLogFile(*a_messageCodec, (success ? "sent2c" : "send2cError"), detail);
396 } catch(anna::RuntimeException &ex) {
397 failReason = ex.asString();
401 a_realmNode->releaseCommMessage(msg);
404 a_testCase->addDebugSummaryHint(failReason); // before report (when set Failed state);
405 a_testCase->setState(TestCase::State::Failed);
411 return success; // go next if sent was OK
414 void TestStepSendxml::do_reset() throw() {
419 ////////////////////////////////////////////////////////////////////////////////////////////////////////
421 ////////////////////////////////////////////////////////////////////////////////////////////////////////
422 anna::xml::Node* TestStepDelay::asXML(anna::xml::Node* parent) const
424 anna::xml::Node* result = TestStep::asXML(parent);
425 //parent->createChild("TestStepDelay");
427 result->createAttribute("Delay", a_delay.asString());
432 bool TestStepDelay::do_execute() throw() {
434 a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_delay, TestTimer::Type::Delay);
436 catch (anna::RuntimeException &ex) {
438 a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
439 a_testCase->setState(TestCase::State::Failed);
442 return false; // don't go next (wait complete)
445 void TestStepDelay::do_complete() throw() {
447 next(); // next() invoked here because execute() is always false for delay and never advance the iterator
450 void TestStepDelay::do_reset() throw() {
452 TestManager::instantiate().cancelTimer(a_timer);
454 catch (anna::RuntimeException &ex) {
458 //a_delay = 0; THIS IS CONFIGURATION INFO
461 ////////////////////////////////////////////////////////////////////////////////////////////////////////
463 ////////////////////////////////////////////////////////////////////////////////////////////////////////
464 TestStepWait::~TestStepWait() {
465 delete a_messageCodec;
466 a_messageCodec = NULL;
469 void TestStepWait::setCondition(bool fromEntity,
470 const std::string &code, const std::string &bitR, const std::string &resultCode, const std::string &sessionId,
471 const std::string &hopByHop, const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw() {
473 a_condition.setReceivedFromEntity(fromEntity);
474 a_condition.setCode(code);
475 a_condition.setBitR(bitR);
476 a_condition.setResultCode(resultCode);
477 a_condition.setSessionId(sessionId);
478 a_condition.setHopByHop(hopByHop);
479 a_condition.setMsisdn(msisdn);
480 a_condition.setImsi(imsi);
481 a_condition.setServiceContextId(serviceContextId);
484 void TestStepWait::setCondition(bool fromEntity, const std::string ®exp) throw() {
486 a_condition.setReceivedFromEntity(fromEntity);
487 a_condition.setRegexp(regexp);
490 anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent) const
492 anna::xml::Node* result = TestStep::asXML(parent);
493 //parent->createChild("TestStepWait");
494 std::string msg = "", xmlmsg = "";
497 a_condition.asXML(result);
500 if (TestManager::instantiate().getDumpHex()) {
501 if (a_message.isEmpty()) {
505 msg = "\n"; msg += a_message.asString(); msg += "\n";
509 if (decodeMessage(a_message, a_messageCodec)) {
511 xmlmsg += a_messageCodec->asXMLString();
515 if (msg != "") result->createAttribute("MatchedMessage", msg);
516 if (xmlmsg != "") result->createAttribute("MatchedXMLMessage", xmlmsg);
521 bool TestStepWait::do_execute() throw() {
525 void TestStepWait::do_complete() throw() {
526 a_testCase->process(); // next() not invoked; we only want to reactivate the test case
529 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
530 if (a_condition.comply(db/*, matchSessionId*/)) {
531 //a_message = db; // store matched
532 a_message.assign(db);
540 void TestStepWait::do_reset() throw() {
542 a_clientSession = NULL;
543 a_serverSession = NULL;
546 ////////////////////////////////////////////////////////////////////////////////////////////////////////
548 ////////////////////////////////////////////////////////////////////////////////////////////////////////
549 anna::xml::Node* TestStepCmd::asXML(anna::xml::Node* parent) const
551 anna::xml::Node* result = TestStep::asXML(parent);
552 //parent->createChild("TestStepCmd");
554 result->createAttribute("Script", (a_script != "") ? a_script:"<no script>");
555 result->createAttribute("Parameters", (a_parameters != "") ? a_parameters:"<no parameters>");
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 cmd += getParameters();
572 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID)) != std::string::npos)
573 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID), anna::functions::asString(TestManager::instantiate().getPoolCycle()));
574 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID)) != std::string::npos)
575 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID), anna::functions::asString(a_testCase->getId()));
576 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID)) != std::string::npos)
577 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID), anna::functions::asString(getNumber()));
579 a_thread = std::thread(cmdRunOnThread, this, cmd);
583 return false; // don't go next (wait complete): If system function on thread stucks, then the reset test case will stuck here forever.
584 // We must implement a interrupt procedure for the thread on reset call... TODO !
587 void TestStepCmd::do_complete() throw() {
589 a_threadRunning = false;
590 if (a_threadDeprecated) {
591 a_threadDeprecated = false;
593 setErrorMsg(anna::functions::asString("Step %d deprecated due to previous reset for Test Case %llu", getNumber(), a_testCase->getId()));
594 a_testCase->setState(TestCase::State::Failed);
595 return; // ignore TODO: interrupt the thread to avoid execution of the script
598 if (getResultCode() != 0)
599 a_testCase->setState(TestCase::State::Failed);
601 next(); // next() invoked here because execute() is always false for delay and never advance the iterator
604 void TestStepCmd::do_reset() throw() {
606 if (a_threadRunning) {
607 std::string s_warn = anna::functions::asString("Thread still in progress: deprecating step %d for Test Case %llu", getNumber(), a_testCase->getId());
608 LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
609 a_threadDeprecated = true;