Hard refactoring. CodecEngine is associated to a unique stack.
[anna.git] / example / diameter / launcher / testing / TestStep.cpp
1 // ANNA - Anna is Not Nothingness Anymore                                                         //
2 //                                                                                                //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo                         //
4 //                                                                                                //
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 //
7
8
9 // Standard
10 #include <string>
11 #include <iostream>
12 #include <errno.h>
13
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
18
19 // Project
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>
29
30 // Process
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>
39
40
41 namespace {
42
43   void handle_sigchld(int sig) {
44     while (waitpid((pid_t)(-1 /* any child (the only) */), 0, WNOHANG|WNOWAIT) > 0) {}
45   }
46
47   void cmdRunOnThread (TestStepCmd *step, const std::string &cmd) {
48
49     // Thread running:
50     step->setThreadRunning(true);
51
52     int status = -2;
53
54     struct sigaction sa;
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());
60      /* POPEN version:
61       char readbuf[256];
62       FILE *fp = popen(cmd.c_str(), "r");
63       if (fp) {
64         while(fgets(readbuf, sizeof(readbuf), fp))
65           step->appendOutput("\n");
66           step->appendOutput(readbuf);
67           status = pclose(fp);
68       }
69       else {
70         status = -1;
71       }
72       */
73     }
74     else {
75       perror(0);
76     }
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) {
79     //   perror(0);
80     //   exit(1);
81     // }
82
83     if (status < 0) {
84       char buf[256];
85       char const * str = strerror_r(errno, buf, 256);
86       step->setErrorMsg(anna::functions::asString("errno = %d (%s)", errno, str));
87     }
88
89     step->setResultCode(WEXITSTATUS(status)); // rc = status >>= 8; // divide by 256
90     step->complete();
91     // TODO: terminate thread when deprecated (RT signal ?)
92     // TODO: mutex the step while setting data here !!
93   }
94
95   bool decodeMessage(const anna::DataBlock &message, anna::diameter::codec::Message &messageCodec) throw() {
96
97     if (message.isEmpty())
98       return false;
99
100     bool result = true;
101     try {
102       messageCodec.decode(message);
103     }
104     catch (anna::RuntimeException &ex) {
105       ex.trace();
106       result = false;
107     }
108
109     return result;
110   }
111 }
112
113
114 ////////////////////////////////////////////////////////////////////////////////////////////////////////
115 // TestStep
116 ////////////////////////////////////////////////////////////////////////////////////////////////////////
117 void TestStep::initialize(TestCase *testCase) {
118   a_testCase = testCase;
119   a_completed = false;
120   a_type = Type::Unconfigured;
121   a_beginTimestamp = 0;
122   a_endTimestamp = 0;
123   a_number = testCase->steps() + 1; // testCase is not NULL
124 }
125
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;
130
131   delete a_messageCodec;
132   a_messageCodec = NULL;
133   return false;
134 }
135
136 const char* TestStep::asText(const Type::_v type)
137 throw() {
138   static const char* text [] = { "Unconfigured", "Timeout", "Sendxml2e", "Sendxml2c", "Delay", "Wait", "Cmd" };
139   return text [type];
140 }
141
142 anna::xml::Node* TestStep::asXML(anna::xml::Node* parent)
143 throw() {
144   anna::xml::Node* result = parent->createChild("TestStep");
145
146   result->createAttribute("Number", a_number);
147   result->createAttribute("Type", asText(a_type));
148   result->createAttribute("Completed", (a_completed ? "yes":"no"));
149
150   // Begin
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);
155
156   // End
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);
161
162   return result;
163 }
164
165 std::string TestStep::asXMLString() throw() {
166   anna::xml::Node root("root");
167   return anna::xml::Compiler().apply(asXML(&root));
168 }
169
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());
173   return do_execute();
174 }
175
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));
178   a_completed = true;
179   setEndTimestamp(anna::functions::millisecond());
180   do_complete();
181 }
182
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
186   a_completed = false;
187   a_beginTimestamp = 0;
188   a_endTimestamp = 0;
189   do_reset();
190 }
191
192 void TestStep::next() throw() {
193   a_testCase->nextStep();
194   a_testCase->process();
195 }
196
197
198 ////////////////////////////////////////////////////////////////////////////////////////////////////////
199 // TestStepTimeout
200 ////////////////////////////////////////////////////////////////////////////////////////////////////////
201 anna::xml::Node* TestStepTimeout::asXML(anna::xml::Node* parent)
202 throw() {
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());
206
207   return result;
208 }
209
210 bool TestStepTimeout::do_execute() throw() {
211   try {
212     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_timeout, TestTimer::Type::TimeLeft);
213   }
214   catch (anna::RuntimeException &ex) {
215     ex.trace();
216     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
217     a_testCase->setState(TestCase::State::Failed);
218   }
219
220   return true; // go next
221 }
222
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);
228   }
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);
232   }
233
234   a_timer = NULL;
235 }
236
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));
239
240   try {
241     TestManager::instantiate().cancelTimer(a_timer);
242   }
243   catch (anna::RuntimeException &ex) {
244     ex.trace();
245   }
246   a_timer = NULL;
247   //a_timeout = 0; THIS IS CONFIGURATION INFO
248 }
249
250 ////////////////////////////////////////////////////////////////////////////////////////////////////////
251 // TestStepSendxml
252 ////////////////////////////////////////////////////////////////////////////////////////////////////////
253 anna::xml::Node* TestStepSendxml::asXML(anna::xml::Node* parent)
254 throw() {
255   anna::xml::Node* result = TestStep::asXML(parent);
256   //parent->createChild("TestStepSendxml");
257   std::string msg = "", xmlmsg = "";
258
259   // Message
260   if (TestManager::instantiate().getDumpHex()) {
261     if (a_message.isEmpty()) {
262       msg = "<empty>";
263     }
264     else {
265       msg = "\n"; msg += a_message.asString(); msg += "\n";
266     }
267   }
268
269   if (decodeMessage()) {
270     xmlmsg = "\n";
271     xmlmsg += a_messageCodec->asXMLString();
272     xmlmsg += "\n";
273   }
274
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);
280
281   return result;
282 }
283
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;
290
291   // Create comm message:
292   anna::diameter::comm::Message *msg = a_realmNode->createCommMessage();
293   //msg->clearBody();
294   msg->setBody(a_message);
295
296   try {
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);
304       // Update sequence:
305       anna::diameter::codec::functions::setHopByHop(a_message, hbh);
306       anna::diameter::codec::functions::setEndToEnd(a_message, ete);
307
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);
315       }
316     }
317
318     if (getType() == Type::Sendxml2e) {
319       anna::diameter::comm::ClientSession *usedClientSession = NULL;
320
321       if (tsw) { // is an answer for a received request on wait condition
322         anna::diameter::comm::ClientSession *clientSession = tsw->getClientSession();
323         if (clientSession) {
324           /* response NULL (is an answer) */clientSession->send(msg);
325           success = true;
326           usedClientSession = clientSession;
327         }
328         else {
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));
331         }
332       }
333       else {
334         if (entity) {
335           success = entity->send(msg);
336           anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
337           usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
338         }
339         else {
340           failReason = "There is no diameter entity currently configured. Unable to send the message";
341           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
342         }
343       } // else (normal sending)
344
345       // Detailed log:
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);
350         }
351       }
352     }
353     else if (getType() == Type::Sendxml2c) {
354       anna::diameter::comm::ServerSession *usedServerSession = NULL;
355
356       if (tsw) { // is an answer for a received request on wait condition
357         anna::diameter::comm::ServerSession *serverSession = tsw->getServerSession();
358         if (serverSession) {
359           /* response NULL (is an answer) */serverSession->send(msg);
360           success = true;
361           usedServerSession = serverSession;
362         }
363         else {
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));
366         }
367       }
368       else {
369         if (localServer) {
370           success = localServer->send(msg);
371           usedServerSession = localServer->getLastUsedResource();
372         }
373         else {
374           failReason = "There is no diameter local server currently configured. Unable to send the message";
375           LOGWARNING(anna::Logger::warning(failReason, ANNA_FILE_LOCATION));
376         }
377       } // else (normal sending)
378
379       // Detailed log:
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);
384         }
385       }
386     }
387
388   } catch(anna::RuntimeException &ex) {
389     failReason = ex.asString();
390   }
391
392   // release msg
393   a_realmNode->releaseCommMessage(msg);
394
395   if (!success) {
396     a_testCase->addDebugSummaryHint(failReason); // before report (when set Failed state);
397     a_testCase->setState(TestCase::State::Failed);
398   }
399   else {
400     complete();
401   }
402
403   return success; // go next if sent was OK
404 }
405
406 void TestStepSendxml::do_reset() throw() {
407   a_expired = false;
408   //a_message.clear();
409   //a_messageAlreadyDecoded = false;
410 }
411
412 ////////////////////////////////////////////////////////////////////////////////////////////////////////
413 // TestStepDelay
414 ////////////////////////////////////////////////////////////////////////////////////////////////////////
415 anna::xml::Node* TestStepDelay::asXML(anna::xml::Node* parent)
416 throw() {
417   anna::xml::Node* result = TestStep::asXML(parent);
418   //parent->createChild("TestStepDelay");
419
420   result->createAttribute("Delay", a_delay.asString());
421
422   return result;
423 }
424
425 bool TestStepDelay::do_execute() throw() {
426   try {
427     a_timer = TestManager::instantiate().createTimer((TestCaseStep*)this, a_delay, TestTimer::Type::Delay);
428   }
429   catch (anna::RuntimeException &ex) {
430     ex.trace();
431     a_testCase->addDebugSummaryHint(ex.asString()); // before report (when set Failed state)
432     a_testCase->setState(TestCase::State::Failed);
433   }
434
435   return false; // don't go next (wait complete)
436 }
437
438 void TestStepDelay::do_complete() throw() {
439   a_timer = NULL;
440   next(); // next() invoked here because execute() is always false for delay and never advance the iterator
441 }
442
443 void TestStepDelay::do_reset() throw() {
444   try {
445     TestManager::instantiate().cancelTimer(a_timer);
446   }
447   catch (anna::RuntimeException &ex) {
448     ex.trace();
449   }
450   a_timer = NULL;
451   //a_delay = 0; THIS IS CONFIGURATION INFO
452 }
453
454 ////////////////////////////////////////////////////////////////////////////////////////////////////////
455 // TestStepWait
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() {
461
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);
471 }
472
473 void TestStepWait::setCondition(bool fromEntity, const std::string &regexp) throw() {
474
475   a_condition.setReceivedFromEntity(fromEntity);
476   a_condition.setRegexp(regexp);
477 }
478
479 anna::xml::Node* TestStepWait::asXML(anna::xml::Node* parent)
480 throw() {
481   anna::xml::Node* result = TestStep::asXML(parent);
482   //parent->createChild("TestStepWait");
483   std::string msg = "", xmlmsg = "";
484
485   // Condition
486   a_condition.asXML(result);
487
488   // Message
489   if (TestManager::instantiate().getDumpHex()) {
490     if (a_message.isEmpty()) {
491       msg = "<empty>";
492     }
493     else {
494       msg = "\n"; msg += a_message.asString(); msg += "\n";
495     }
496   }
497
498   if (decodeMessage()) {
499     xmlmsg = "\n";
500     xmlmsg += a_messageCodec->asXMLString();
501     xmlmsg += "\n";
502   }
503
504   if (msg != "") result->createAttribute("MatchedMessage", msg);
505   if (xmlmsg != "") result->createAttribute("MatchedXMLMessage", xmlmsg);
506
507   return result;
508 }
509
510 bool TestStepWait::do_execute() throw() {
511   return a_completed;
512 }
513
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
517 }
518
519 bool TestStepWait::fulfilled(const anna::DataBlock &db/*, bool matchSessionId*/) throw() {
520   if (a_condition.comply(db/*, matchSessionId*/)) {
521     a_message = db; // store matched
522     complete();
523     return true;
524   }
525
526   return false;
527 }
528
529 void TestStepWait::do_reset() throw() {
530   a_message.clear();
531   a_clientSession = NULL;
532   a_serverSession = NULL;
533 }
534
535 ////////////////////////////////////////////////////////////////////////////////////////////////////////
536 // TestStepCmd
537 ////////////////////////////////////////////////////////////////////////////////////////////////////////
538 anna::xml::Node* TestStepCmd::asXML(anna::xml::Node* parent)
539 throw() {
540   anna::xml::Node* result = TestStep::asXML(parent);
541   //parent->createChild("TestStepCmd");
542
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);
549   }
550
551   return result;
552 }
553
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();
558     cmd += " ";
559     cmd += getParameters();
560     size_t index;
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()));
567
568     a_thread = std::thread(cmdRunOnThread, this, cmd);
569     a_thread.detach();
570   }
571
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 !       
574 }
575
576 void TestStepCmd::do_complete() throw() {
577
578   a_threadRunning = false;
579   if (a_threadDeprecated) {
580     a_threadDeprecated = false;
581     do_reset();
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
585   }
586
587   if (getResultCode() != 0)
588     a_testCase->setState(TestCase::State::Failed);
589   else
590     next(); // next() invoked here because execute() is always false for delay and never advance the iterator
591 }
592
593 void TestStepCmd::do_reset() throw() {
594
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;
599   }
600
601   a_resultCode = -2;
602   //a_output = "";
603 }
604