c4f5db7f3359f3715ad39b401bee94480dfe4e8d
[anna.git] / example / diameter / launcher / MyLocalServer.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 // Project
10 #include <anna/core/core.hpp>
11 #include <anna/diameter/functions.hpp>
12 #include <anna/time/functions.hpp>
13 #include <anna/diameter/codec/Engine.hpp>
14 #include <anna/diameter.comm/Response.hpp>
15 #include <anna/diameter.comm/ClientSession.hpp>
16 #include <anna/diameter.comm/Server.hpp>
17 #include <anna/diameter.comm/OriginHost.hpp>
18
19 // Process
20 #include <MyLocalServer.hpp>
21 #include <MyDiameterEngine.hpp>
22 #include <MyDiameterEntity.hpp>
23 #include <Launcher.hpp>
24 #include <anna/testing/TestManager.hpp>
25
26
27 void MyLocalServer::eventRequest(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
28 throw(anna::RuntimeException) {
29   LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventRequest", ANNA_FILE_LOCATION));
30   // Performance stats:
31   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
32   anna::diameter::comm::OriginHost *my_node = my_app.getOriginHost(getEngine()->getOriginHostName());
33   anna::diameter::codec::Engine *codecEngine = my_node->getCodecEngine();
34
35   // CommandId:
36   anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
37   LOGDEBUG
38   (
39     std::string msg = "Request received: ";
40     msg += anna::diameter::functions::commandIdAsPairString(cid);
41     msg += " | DiameterServer: ";
42     msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
43     msg += " | EventTime: ";
44     msg += anna::time::functions::currentTimeAsString();
45     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
46   );
47
48   // Write reception
49   if(my_node->logEnabled()) my_node->writeLogFile(message, "recvfc", serverSession->asString());
50
51   // If no answer is programmed and entity is configured, the failed request would be forwarded even being wrong (delegates at the end point)
52   int code = cid.first;
53   anna::diameter::codec::Message *programmed_answer = a_reactingAnswers.getMessage(code);
54   bool programmed = (programmed_answer != NULL);
55
56   anna::diameter::comm::Entity *entity = my_node->getEntity();
57   if(!programmed && entity) {  // forward condition (no programmed answer + entity available)
58     anna::diameter::comm::Message *msg = my_node->createCommMessage();
59     msg->forwardEndToEnd(); // end-to-end will be kept
60     msg->setBody(message);
61     msg->setRequestServerSessionKey(serverSession->getKey());
62     bool success = entity->send(msg);
63
64     // Detailed log:
65     if(my_node->logEnabled()) {
66       anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
67       anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
68       std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
69       my_node->writeLogFile(message, (success ? "fwd2e" : "fwd2eError"), detail); // forwarded
70     }
71
72
73     // Testing:
74     anna::testing::TestManager::instantiate().receiveMessage(message, serverSession);
75
76     return;
77   }
78
79   // Error analisys:
80   bool analysisOK = true; // by default
81   anna::diameter::codec::Message *answer_message = NULL;
82   anna::diameter::codec::Message codecMsg;
83   anna::diameter::codec::Message codecAnsMsg;
84
85   CommandLine& cl(anna::CommandLine::instantiate());
86   if(!cl.exists("ignoreErrors")) {  // Error analysis
87     answer_message = (anna::diameter::codec::Message *)&codecAnsMsg;
88     answer_message->clear();
89
90     // Decode
91     try { codecMsg.decode(message, answer_message); } catch(anna::RuntimeException &ex) { ex.trace(); }
92
93     answer_message->setStandardToAnswer(codecMsg, my_node->getCommEngine()->getOriginHostName(), my_node->getCommEngine()->getOriginRealmName());
94     analysisOK = (answer_message->getResultCode() == anna::diameter::helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS);
95   }
96
97   // Programmed answer only when all is ok
98   if(analysisOK) {
99     if(programmed) {
100       answer_message = programmed_answer;
101       // Prepare answer:
102       my_app.getCommunicator()->prepareAnswer(answer_message, message);
103     } else {
104
105       // Testing:
106       anna::testing::TestManager::instantiate().receiveMessage(message, serverSession);
107
108       return; // nothing done
109     }
110   }
111
112   anna::diameter::codec::Engine::ValidationMode::_v backupVM = codecEngine->getValidationMode();
113
114   if(!analysisOK)
115     codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Never);
116
117   anna::diameter::comm::Message *msg;
118   try {
119     msg = my_node->createCommMessage();
120     msg->setBody(answer_message->code());
121     /* response = NULL =*/serverSession->send(msg);
122
123     if(my_node->logEnabled()) my_node->writeLogFile(*answer_message, "sent2c", serverSession->asString());
124   } catch(anna::RuntimeException &ex) {
125     ex.trace();
126     if(my_node->logEnabled()) my_node->writeLogFile(*answer_message, "send2cError", serverSession->asString());
127   }
128
129   // release msg
130   my_node->releaseCommMessage(msg);
131
132   // Restore validation mode
133   codecEngine->setValidationMode(backupVM);
134
135   // Pop front the reacting answer:
136   if(analysisOK && programmed) a_reactingAnswers.nextMessage(code);
137
138   // Testing:
139   anna::testing::TestManager::instantiate().receiveMessage(message, serverSession);
140 }
141
142 void MyLocalServer::eventResponse(const anna::diameter::comm::Response &response)
143 throw(anna::RuntimeException) {
144   LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventResponse", ANNA_FILE_LOCATION));
145   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
146   anna::diameter::comm::OriginHost * my_node = my_app.getOriginHost(getEngine()->getOriginHostName());
147   anna::diameter::comm::ClassCode::_v code = response.getClassCode();
148   anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode();
149   anna::diameter::comm::Message* request = const_cast<anna::diameter::comm::Message*>(response.getRequest());
150   const anna::DataBlock* message = response.getMessage();
151   const anna::diameter::comm::ServerSession *serverSession = static_cast<const anna::diameter::comm::ServerSession *>(response.getSession());
152   bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind);
153   bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage);
154   bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout);
155   bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable);
156   bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success);
157
158   // CommandId:
159   anna::diameter::CommandId request_cid = request->getCommandId();
160   LOGDEBUG
161   (
162     std::string msg = "Response received for original diameter request: ";
163     msg += anna::diameter::functions::commandIdAsPairString(request_cid);
164     msg += " | Response: ";
165     msg += response.asString();
166     msg += " | LocalServer: ";
167     msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
168     msg += " | EventTime: ";
169     msg += anna::time::functions::currentTimeAsString();
170     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
171   );
172
173   if(isUnavailable) {
174     //if (isApplicationMessage)
175     LOGWARNING(anna::Logger::warning("Diameter client unavailable for Diameter Request", ANNA_FILE_LOCATION));
176   }
177
178   if(contextExpired) {
179     //if (isApplicationMessage)
180     LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the client", ANNA_FILE_LOCATION));
181
182     if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) {  // don't trace CEA
183       if(my_node->logEnabled()) my_node->writeLogFile(*request, "req2c-expired", serverSession->asString());
184     }
185   }
186
187   if(isOK) {
188     LOGDEBUG(
189       std::string msg = "Received response for diameter message:  ";
190       msg += anna::diameter::functions::commandIdAsPairString(request_cid);
191       anna::Logger::debug(msg, ANNA_FILE_LOCATION);
192     );
193
194     // Write reception
195     if(my_node->logEnabled()) my_node->writeLogFile(*message, "recvfc", serverSession->asString());
196
197     // This is not very usual, but answers could arrive from clients:
198     anna::diameter::comm::Entity *entity = my_node->getEntity();
199
200     if(entity) {
201       anna::diameter::comm::ClientSession *usedClientSession = my_node->getCommEngine()->findClientSession(request->getRequestClientSessionKey());
202       std::string detail;
203
204       if(my_node->logEnabled()) detail = usedClientSession ? usedClientSession->asString() : "<null client session>";  // this should not happen
205       anna::diameter::comm::Message *msg;
206
207       try {
208         msg = my_node->createCommMessage();
209         msg->forwardEndToEnd(); // end-to-end will be kept
210         msg->setBody(*message);
211
212         // Metodo 1:
213         if(usedClientSession) /* response = NULL =*/usedClientSession->send(msg);
214
215         // Metodo 2:
216         //msg->setRequestClientSessionKey(request->getRequestClientSessionKey());
217         //bool success = entity->send(msg);
218
219         if(my_node->logEnabled()) my_node->writeLogFile(*message, "fwd2e", detail);  // forwarded
220       } catch(anna::RuntimeException &ex) {
221         ex.trace();
222         if(my_node->logEnabled()) my_node->writeLogFile(*message, "fwd2eError", detail);  // forwarded
223       }
224
225       // release msgs
226       my_node->releaseCommMessage(msg);
227       my_node->releaseCommMessage(request);
228     }
229   }
230
231   // Testing:
232   if(isOK) anna::testing::TestManager::instantiate().receiveMessage(*message, serverSession);
233 }
234
235 void MyLocalServer::eventUnknownResponse(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
236 throw(anna::RuntimeException) {
237   LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventUnknownResponse", ANNA_FILE_LOCATION));
238   // Performance stats:
239   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
240   anna::diameter::comm::OriginHost *my_node = my_app.getOriginHost(getEngine()->getOriginHostName());
241   // CommandId:
242   anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
243   LOGDEBUG
244   (
245     std::string msg = "Out-of-context response received from client: ";
246     msg += anna::diameter::functions::commandIdAsPairString(cid);
247     msg += " | DiameterServer: ";
248     msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
249     msg += " | EventTime: ";
250     msg += anna::time::functions::currentTimeAsString();
251     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
252   );
253
254   if(my_node->logEnabled()) my_node->writeLogFile(message, "recvfc-ans-unknown", serverSession->asString());
255 }
256
257 void MyLocalServer::eventDPA(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
258 throw(anna::RuntimeException) {
259   LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventDPA", ANNA_FILE_LOCATION));
260   // Performance stats:
261   Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
262   anna::diameter::comm::OriginHost *my_node = my_app.getOriginHost(getEngine()->getOriginHostName());
263   // CommandId:
264   anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
265   LOGDEBUG
266   (
267     std::string msg = "Disconnect-Peer-Answer response received from client: ";
268     msg += anna::diameter::functions::commandIdAsPairString(cid);
269     msg += " | DiameterServer: ";
270     msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
271     msg += " | EventTime: ";
272     msg += anna::time::functions::currentTimeAsString();
273     anna::Logger::debug(msg, ANNA_FILE_LOCATION);
274   );
275
276   // Write reception
277   if(my_node->logEnabled()) my_node->writeLogFile(message, "recvfc", serverSession->asString());
278
279   // Testing:
280   anna::testing::TestManager::instantiate().receiveMessage(message, serverSession);
281 }