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.decode(message);
104 catch (anna::RuntimeException &ex) {
114 ////////////////////////////////////////////////////////////////////////////////////////////////////////
116 ////////////////////////////////////////////////////////////////////////////////////////////////////////
117 void TestStep::initialize(TestCase *testCase) {
118 a_testCase = testCase;
120 a_type = Type::Unconfigured;
121 a_beginTimestamp = 0;
123 a_number = testCase->steps() + 1; // testCase is not NULL
126 bool TestStep::decodeMessage() throw() {
127 if (a_messageCodec) return true;
128 a_messageCodec = new anna::diameter::codec::Message;
129 if (::decodeMessage(a_message, *a_messageCodec)) return true;
131 delete a_messageCodec;
132 a_messageCodec = NULL;
136 const char* TestStep::asText(const Type::_v type)
138 static const char* text [] = { "Unconfigured", "Timeout", "Sendxml2e", "Sendxml2c", "Delay", "Wait", "Cmd" };
142 anna::xml::Node* TestStep::asXML(anna::xml::Node* parent)
144 anna::xml::Node* result = parent->createChild("TestStep");
146 result->createAttribute("Number", a_number);
147 result->createAttribute("Type", asText(a_type));
148 result->createAttribute("Completed", (a_completed ? "yes":"no"));
151 std::string s_aux = a_beginTimestamp.asString();
152 // int deltaMs = (int)(a_beginTimestamp - a_testCase->getStartTimestamp());
153 // if (a_beginTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
154 result->createAttribute("BeginTimestamp", s_aux);
157 s_aux = a_endTimestamp.asString();
158 // deltaMs = (int)(a_endTimestamp - a_testCase->getStartTimestamp());
159 // if (a_endTimestamp != 0 && deltaMs > 0) s_aux += anna::functions::asString(" [%.3f]", deltaMs/1000.0);
160 result->createAttribute("EndTimestamp", s_aux);
165 std::string TestStep::asXMLString() throw() {
166 anna::xml::Node root("root");
167 return anna::xml::Compiler().apply(asXML(&root));
170 bool TestStep::execute() throw() {
171 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));
172 setBeginTimestamp(anna::functions::millisecond());
176 void TestStep::complete() throw() {
177 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));
179 setEndTimestamp(anna::functions::millisecond());
183 void TestStep::reset() throw() {
184 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));
185 // type and testCase kept
187 a_beginTimestamp = 0;
192 void TestStep::next() throw() {
193 a_testCase->nextStep();
194 a_testCase->process();
198 ////////////////////////////////////////////////////////////////////////////////////////////////////////
200 ////////////////////////////////////////////////////////////////////////////////////////////////////////
201 anna::xml::Node* TestStepTimeout::asXML(anna::xml::Node* parent)
203 anna::xml::Node* result = TestStep::asXML(parent); // end timestamp will be 0 if test finished OK
204 //parent->createChild("TestStepTimeout");
205 result->createAttribute("Timeout", a_timeout.asString());
210 bool TestStepTimeout::do_execute() throw() {
212 a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_timeout, TestTimer::Type::TimeLeft);
214 catch (anna::RuntimeException &ex) {
216 a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
217 a_testCase->setState(TestCase::State::Failed);
220 return true; // go next
223 void TestStepTimeout::do_complete() throw() {
224 int stepNumber = getNumber();
225 if (stepNumber == a_testCase->steps()) {
226 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)
227 a_testCase->setState(TestCase::State::Success);
229 else if (a_testCase->getState() == TestCase::State::InProgress) { // sure
230 a_testCase->addDebugSummaryHint(anna::functions::asString("Timeout expired (step number %d) before test case finished", stepNumber)); // before report (when set Failed state)
231 a_testCase->setState(TestCase::State::Failed);
237 void TestStepTimeout::do_reset() throw() {
238 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));
241 TestManager::instantiate().cancelTimer(a_timer);
243 catch (anna::RuntimeException &ex) {
247 //a_timeout = 0; THIS IS CONFIGURATION INFO
250 ////////////////////////////////////////////////////////////////////////////////////////////////////////
252 ////////////////////////////////////////////////////////////////////////////////////////////////////////
253 anna::xml::Node* TestStepSendxml::asXML(anna::xml::Node* parent)
255 anna::xml::Node* result = TestStep::asXML(parent);
256 //parent->createChild("TestStepSendxml");
257 std::string msg = "", xmlmsg = "";
260 if (TestManager::instantiate().getDumpHex()) {
261 if (a_message.isEmpty()) {
265 msg = "\n"; msg += a_message.asString(); msg += "\n";
269 if (decodeMessage()) {
271 xmlmsg += a_messageCodec->asXMLString();
275 if (msg != "") result->createAttribute("Message", msg);
276 if (xmlmsg != "") result->createAttribute("XMLMessage", xmlmsg);
277 result->createAttribute("Expired", (a_expired ? "yes":"no"));
278 if (a_waitForRequestStepNumber != -1)
279 result->createAttribute("WaitForRequestStepNumber", a_waitForRequestStepNumber);
284 bool TestStepSendxml::do_execute() throw() {
285 bool success = false;
286 std::string failReason, s_warn;
287 MyDiameterEntity *entity = a_realmNode->getEntity(); // by default
288 MyLocalServer *localServer = a_realmNode->getDiameterServer(); // by default
289 const TestStepWait *tsw = NULL;
291 // Create comm message:
292 anna::diameter::comm::Message *msg = a_realmNode->createCommMessage();
294 msg->setBody(a_message);
297 // Update sequence for answers:
298 if (a_waitForRequestStepNumber != -1) { // is an answer: try to copy sequence information; alert about Session-Id discrepance
299 // Request which was received:
300 tsw = (const TestStepWait*)(a_testCase->getStep(a_waitForRequestStepNumber));
301 const anna::DataBlock &request = tsw->getMsgDataBlock();
302 anna::diameter::HopByHop hbh = anna::diameter::codec::functions::getHopByHop(request);
303 anna::diameter::EndToEnd ete = anna::diameter::codec::functions::getEndToEnd(request);
305 anna::diameter::codec::functions::setHopByHop(a_message, hbh);
306 anna::diameter::codec::functions::setEndToEnd(a_message, ete);
308 // Check Session-Id for warning ...
309 std::string sessionIdAnswer = anna::diameter::helpers::base::functions::getSessionId(a_message);
310 std::string sessionIdRequest = anna::diameter::helpers::base::functions::getSessionId(request);
311 if (sessionIdRequest != sessionIdAnswer) {
312 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());
313 LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
314 a_testCase->addDebugSummaryHint(s_warn);
318 if (getType() == Type::Sendxml2e) {
319 anna::diameter::comm::ClientSession *usedClientSession = NULL;
321 if (tsw) { // is an answer for a received request on wait condition
322 anna::diameter::comm::ClientSession *clientSession = tsw->getClientSession();
324 /* response NULL (is an answer) */clientSession->send(msg);
326 usedClientSession = clientSession;
329 failReason = "Reference wait step didn't store a valid client session. Unable to send the message";
330 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
335 success = entity->send(msg);
336 anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
337 usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
340 failReason = "There is no diameter entity currently configured. Unable to send the message";
341 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
343 } // else (normal sending)
346 if(a_realmNode->logEnabled()) {
347 if (decodeMessage()) {
348 std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // shouldn't happen
349 a_realmNode->writeLogFile(*a_messageCodec, (success ? "sent2e" : "send2eError"), detail);
353 else if (getType() == Type::Sendxml2c) {
354 anna::diameter::comm::ServerSession *usedServerSession = NULL;
356 if (tsw) { // is an answer for a received request on wait condition
357 anna::diameter::comm::ServerSession *serverSession = tsw->getServerSession();
359 /* response NULL (is an answer) */serverSession->send(msg);
361 usedServerSession = serverSession;
364 failReason = "Reference wait step didn't store a valid server session. Unable to send the message";
365 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
370 success = localServer->send(msg);
371 usedServerSession = localServer->getLastUsedResource();
374 failReason = "There is no diameter local server currently configured. Unable to send the message";
375 LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
377 } // else (normal sending)
380 if(a_realmNode->logEnabled()) {
381 if (decodeMessage()) {
382 std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // shouldn't happen
383 a_realmNode->writeLogFile(*a_messageCodec, (success ? "sent2c" : "send2cError"), detail);
388 } catch(anna::RuntimeException &ex) {
389 failReason = ex.asString();
393 a_realmNode->releaseCommMessage(msg);
396 a_testCase->addDebugSummaryHint(failReason); // before report (when set Failed state);
397 a_testCase->setState(TestCase::State::Failed);
403 return success; // go next if sent was OK
406 void TestStepSendxml::do_reset() throw() {
409 //a_messageAlreadyDecoded = false;
412 ////////////////////////////////////////////////////////////////////////////////////////////////////////
414 ////////////////////////////////////////////////////////////////////////////////////////////////////////
415 anna::xml::Node* TestStepDelay::asXML(anna::xml::Node* parent)
417 anna::xml::Node* result = TestStep::asXML(parent);
418 //parent->createChild("TestStepDelay");
420 result->createAttribute("Delay", a_delay.asString());
425 bool TestStepDelay::do_execute() throw() {
427 a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_delay, TestTimer::Type::Delay);
429 catch (anna::RuntimeException &ex) {
431 a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
432 a_testCase->setState(TestCase::State::Failed);
435 return false; // don't go next (wait complete)
438 void TestStepDelay::do_complete() throw() {
440 next(); // next() invoked here because execute() is always false for delay and never advance the iterator
443 void TestStepDelay::do_reset() throw() {
445 TestManager::instantiate().cancelTimer(a_timer);
447 catch (anna::RuntimeException &ex) {
451 //a_delay = 0; THIS IS CONFIGURATION INFO
454 ////////////////////////////////////////////////////////////////////////////////////////////////////////
456 ////////////////////////////////////////////////////////////////////////////////////////////////////////
457 void TestStepWait::setCondition(bool fromEntity,
458 const std::string &code, const std::string &bitR, const std::string &hopByHop, const std::string &applicationId,
459 const std::string &sessionId, const std::string &resultCode,
460 const std::string &msisdn, const std::string &imsi, const std::string &serviceContextId) throw() {
462 a_condition.setReceivedFromEntity(fromEntity);
463 a_condition.setCode(code);
464 a_condition.setBitR(bitR);
465 a_condition.setResultCode(resultCode);
466 a_condition.setSessionId(sessionId);
467 a_condition.setHopByHop(hopByHop);
468 a_condition.setMsisdn(msisdn);
469 a_condition.setImsi(imsi);
470 a_condition.setServiceContextId(serviceContextId);
473 void TestStepWait::setCondition(bool fromEntity, const std::string ®exp) throw() {
475 a_condition.setReceivedFromEntity(fromEntity);
476 a_condition.setRegexp(regexp);
479 anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent)
481 anna::xml::Node* result = TestStep::asXML(parent);
482 //parent->createChild("TestStepWait");
483 std::string msg = "", xmlmsg = "";
486 a_condition.asXML(result);
489 if (TestManager::instantiate().getDumpHex()) {
490 if (a_message.isEmpty()) {
494 msg = "\n"; msg += a_message.asString(); msg += "\n";
498 if (decodeMessage()) {
500 xmlmsg += a_messageCodec->asXMLString();
504 if (msg != "") result->createAttribute("MatchedMessage", msg);
505 if (xmlmsg != "") result->createAttribute("MatchedXMLMessage", xmlmsg);
510 bool TestStepWait::do_execute() throw() {
514 void TestStepWait::do_complete() throw() {
515 //a_testCase->process(); // next() not invoked; we only want to reactivate the test case
516 // avoid stack overflow: we will process the test case externally when incoming message is fulfilled (TestCase.cpp), and TestManager is noticed
519 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
520 if (a_condition.comply(db/*, matchSessionId*/)) {
521 a_message = db; // store matched
529 void TestStepWait::do_reset() throw() {
531 a_clientSession = NULL;
532 a_serverSession = NULL;
535 ////////////////////////////////////////////////////////////////////////////////////////////////////////
537 ////////////////////////////////////////////////////////////////////////////////////////////////////////
538 anna::xml::Node* TestStepCmd::asXML(anna::xml::Node* parent)
540 anna::xml::Node* result = TestStep::asXML(parent);
541 //parent->createChild("TestStepCmd");
543 result->createAttribute("Script", (a_script != "") ? a_script:"<no script>");
544 result->createAttribute("Parameters", (a_parameters != "") ? a_parameters:"<no parameters>");
545 if (a_errorMsg != "") result->createAttribute("ErrorMessage", a_errorMsg);
546 if (!a_threadRunning && a_resultCode != -2) {
547 result->createAttribute("ResultCode", a_resultCode);
548 //if (a_output != "") result->createAttribute("Output", a_output);
554 bool TestStepCmd::do_execute() throw() {
555 if (!a_threadRunning /* || a_threadDeprecated DO NOT WANT TO OVERLAP ... */) {
556 // Special tags to replace:
557 std::string cmd = getScript();
559 cmd += getParameters();
561 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID)) != std::string::npos)
562 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__CYCLE_ID), anna::functions::asString(TestManager::instantiate().getPoolCycle()));
563 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID)) != std::string::npos)
564 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTCASE_ID), anna::functions::asString(a_testCase->getId()));
565 while ((index = cmd.find(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID)) != std::string::npos)
566 cmd.replace(index, strlen(SH_COMMAND_TAG_FOR_REPLACE__TESTSTEP_ID), anna::functions::asString(getNumber()));
568 a_thread = std::thread(cmdRunOnThread, this, cmd);
572 return false; // don't go next (wait complete): If system function on thread stucks, then the reset test case will stuck here forever.
573 // We must implement a interrupt procedure for the thread on reset call... TODO !
576 void TestStepCmd::do_complete() throw() {
578 a_threadRunning = false;
579 if (a_threadDeprecated) {
580 a_threadDeprecated = false;
582 setErrorMsg(anna::functions::asString("Step %d deprecated due to previous reset for Test Case %llu", getNumber(), a_testCase->getId()));
583 a_testCase->setState(TestCase::State::Failed);
584 return; // ignore TODO: interrupt the thread to avoid execution of the script
587 if (getResultCode() != 0)
588 a_testCase->setState(TestCase::State::Failed);
590 next(); // next() invoked here because execute() is always false for delay and never advance the iterator
593 void TestStepCmd::do_reset() throw() {
595 if (a_threadRunning) {
596 std::string s_warn = anna::functions::asString("Thread still in progress: deprecating step %d for Test Case %llu", getNumber(), a_testCase->getId());
597 LOGWARNING(anna::Logger::warning(s_warn, ANNA_FILE_LOCATION));
598 a_threadDeprecated = true;