MSGDTD=../../../include/anna/diameter/codec/message.dtd
DCTDTD=../../../include/anna/diameter/stack/dictionary.dtd
BASE_PROT=commands_baseProtocol.xml
+SERVICES=./resources/services_examples
+SRVDTD=$SERVICES/services.dtd
# Executables in priority order:
EXEC_installed=/opt/bin/anna/example_diameter_launcher
EXECS=( $EXEC_installed ./release/example_diameter_launcher ./debug/example_diameter_launcher )
+# Stack management
+STACKMGMT_EXEC_installed=/opt/bin/anna/example_diameter_stackManagement
+STACKMGMT_EXECS=( $STACKMGMT_EXEC_installed ../stackManagement/release/example_diameter_stackManagement ../stackManagement/debug/example_diameter_stackManagement )
+
#############
# FUNCTIONS #
#############
echo " non-existent path directory."
echo
echo " For example:"
- echo " $0 b $HOME/ADL/basicServer"
- echo " $0 b $HOME/ADL/MMSbalancer"
- echo " $0 f $HOME/ADL/tester"
+ echo " $0 b $HOME/ADML/basicServer"
+ echo " $0 b $HOME/ADML/MMSbalancer"
+ echo " $0 f $HOME/ADML/tester"
echo
exit 0
}
# $1: deployment type
createRunScript () {
-
# Basic launcher 'run.sh' will be created at deployment configuration:
[ "$1" = "b" ] && return
- [ "$1" = "a" ] && exe=ADL-launcher
- [ "$1" = "f" ] && { exe=ADL-ftclient ; ln -s ADL-launcher $exe ; }
+
+ local other=
+ [ "$1" = "a" ] && { exe=ADML-launcher ; other="--httpServer \`grep -v ^# .httpServer\`"; }
+ [ "$1" = "f" ] && { exe=ADML-ftclient ; ln -s ADML-launcher $exe ; }
+
+ echo "Creating 'run.sh' script ..."
cat << EOF > run.sh
#!/bin/bash
0> launcher.trace
rm -f counters/*
# Execution line:
-./\$EXE --cntDir counters $(for i in `cat args.txt | grep -v "^#"`; do echo -n "$i "; done)&
+./\$EXE --services services.xml --cntDir counters $other &
echo \$! > .pid
EOF
chmod a+x run.sh
- rm args.txt
}
createDictionaryPaths () {
+ echo "Creating dictionaries ..."
+
for i in stacks/*commands*xml
do
stacks/dependence.sh $i >/dev/null
stack=`basename $i`
if test "$stack" != "$BASE_PROT"
then
- > .dictionary__${stack}
+ > .dictionary-${stack}
for j in `cat ${i}.dep`
do
- echo -n "${j}," >> .dictionary__${stack}
+ echo -n "${j} " >> .dictionary-${stack}
done
- echo "stacks/$BASE_PROT,stacks/${stack}" >> .dictionary__${stack}
+ echo "stacks/$BASE_PROT stacks/${stack}" >> .dictionary-${stack}
fi
done
- # Default:
- ln -s .dictionary__commands_qosControl.xml .dictionary
+ # Create autonomous dictionaries:
+ mkdir stacks/autonomous
+ for i in `ls .dictionary-*`
+ do
+ name=$(echo $i | cut -d\- -f2)
+ $STACKMGMT_EXEC `cat $i` >/dev/null
+ mv result.xml stacks/autonomous/$name
+ done
- # Remove deps:
+ # Cleanup:
rm -f stacks/*.dep
+ rm -f .dictionary-*
+ rm -f example_diameter_stackManagement.trace*
+
+ # Default:
+ ln -s stacks/autonomous/commands_qosControl.xml dictionary.xml
}
#############
cd `dirname $0`
echo
echo "---------------------------------------"
-echo "Anna Diameter Launcher (ADL) deployment"
+echo "Anna Diameter Launcher (ADML) deployment"
echo "---------------------------------------"
[ "$1" = "--help" -o "$1" = "-h" ] && usage
echo " (--help or -h for more info)"
echo
echo "Basic checkings ..."
+# Launcher executable:
available=
for EXEC in ${EXECS[@]}; do
echo -n "Looking executable at '$EXEC' ... "
[ -x $EXEC ] && { available=yes ; echo "available !" ; break ; }
echo "not found"
done
-[ -z "$available" ] && _exit "Anna Diameter Launcher (ADL) is not installed neither linked. See README.md (Install section)."
+[ -z "$available" ] && _exit "Anna Diameter Launcher (ADML) is not installed neither linked. See README.md (Install section)."
+# Dictionary creation:
+available=
+for STACKMGMT_EXEC in ${STACKMGMT_EXECS[@]}; do
+ echo -n "Looking stack management executable at '$STACKMGMT_EXEC' ... "
+ [ -x $STACKMGMT_EXEC ] && { available=yes ; echo "available !" ; break ; }
+ echo "not found"
+done
+[ -z "$available" ] && _exit "Anna Diameter Stack Management Tool is not installed neither linked. See README.md (Install section)."
+
[ ! -d $SETUPS_DIR ] && _exit "Diameter stacks not found ($SETUPS_DIR)."
echo
a)
echo "Advanced deployment"
DEPLOYMENTS_DIR=deployments/advanced
- DPATH_dflt=$HOME/ADL/advanced
+ DPATH_dflt=$HOME/ADML/advanced
;;
b)
echo "Basic deployment"
DEPLOYMENTS_DIR=deployments/basic
- DPATH_dflt=$HOME/ADL/basic
+ DPATH_dflt=$HOME/ADML/basic
;;
f)
echo "FT deployment"
DEPLOYMENTS_DIR=deployments/ft-client
- DPATH_dflt=$HOME/ADL/ft-client
+ DPATH_dflt=$HOME/ADML/ft-client
;;
*)
mkdir -p $DPATH/stacks
mkdir -p $DPATH/DTDs
mkdir -p $DPATH/counters
-mkdir -p $DPATH/resources
+[ "option" = "b" ] && mkdir -p $DPATH/services
if [ "$EXEC" = "$EXEC_installed" ]
then
- ln -s $EXEC_installed $DPATH/ADL-launcher
+ ln -s $EXEC_installed $DPATH/ADML-launcher
else
- cp $EXEC $DPATH/ADL-launcher
+ cp $EXEC $DPATH/ADML-launcher
fi
cp -rL $DEPLOYMENTS_DIR/* $DPATH
-cp resources/* $DPATH/resources
cp $SETUPS_DIR/*xml $DPATH/stacks
cp $SETUPS_DIR/*sh $DPATH/stacks
cp $SETUPS_DIR/readme.txt $DPATH/stacks
cp $MSGDTD $DPATH/DTDs
cp $DCTDTD $DPATH/DTDs
+cp $SRVDTD $DPATH/DTDs
+[ "option" = "b" ] && cp $SERVICES/* $DPATH/services
echo "Preparing ..."
cd $DPATH
// See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
+// Standard
+#include <sstream> // std::istringstream
+#include <iostream> // std::cout
+
// Project
+#include <anna/timex/Engine.hpp>
#include <anna/statistics/Engine.hpp>
#include <anna/diameter/codec/Engine.hpp>
#include <anna/http/Transport.hpp>
#include <anna/diameter/helpers/base/functions.hpp>
#include <anna/time/functions.hpp>
#include <anna/diameter.comm/ApplicationMessageOamModule.hpp>
+#include <anna/xml/xml.hpp>
// Process
#include "Launcher.hpp"
+#include "RealmNode.hpp"
+#include "MyDiameterEngine.hpp"
#define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.tasks.input"
#define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.tasks.output"
-#define DIAMETER_CODEC_ENGINE_NAME_PREFIX "MyCodecEngine"
+
const char *ServicesDTD = "\
<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
<!--\n\
Stack record\n\
\n\
- id: Normally the id corresponds to the Application-Id for which the dictionary provided is designed\n\
+ id: Normally the id corresponds to the Application-Id for which the dictionary provided is designed.\n\
+ (in multistack applications, it shall be mandatory respect such association to know the stack used\n\
+ for processed messages).\n\
dictionary: Path to the dictionary file\n\
-->\n\
\n\
<!ELEMENT node EMPTY>\n\
-<!ATTLIST node name CDATA #REQUIRED application-id CDATA #REQUIRED cer CDATA #IMPLIED dwr CDATA #IMPLIED entity CDATA #IMPLIED entityServerSessions CDATA #IMPLIED diameterServer CDATA #IMPLIED diameterServerSessions CDATA #IMPLIED balance (yes | no) #IMPLIED sessionBasedModelsClientSocketSelection (SessionIdHighPart | SessionIdOptionalPart | RoundRobin) #IMPLIED ignoreFlags (yes | no) #IMPLIED ignoreErrors (yes | no) #IMPLIED>\n\
+<!ATTLIST node originRealm CDATA #REQUIRED applicationId CDATA #REQUIRED originHost CDATA #IMPLIED cer CDATA #IMPLIED dwr CDATA #IMPLIED allowedInactivityTime CDATA #IMPLIED tcpConnectDelay CDATA #IMPLIED answersTimeout CDATA #IMPLIED ceaTimeout CDATA #IMPLIED watchdogPeriod CDATA #IMPLIED entity CDATA #IMPLIED entityServerSessions CDATA #IMPLIED diameterServer CDATA #IMPLIED diameterServerSessions CDATA #IMPLIED balance (yes | no) #IMPLIED sessionBasedModelsClientSocketSelection (SessionIdLowPart | SessionIdHighPart | SessionIdOptionalPart | RoundRobin) #IMPLIED retries CDATA #IMPLIED log CDATA #IMPLIED splitLog (yes | no) #IMPLIED detailedLog (yes | no) #IMPLIED dumpLog (yes | no) #IMPLIED burstLog (yes | no) #IMPLIED>\n\
<!--\n\
Node record\n\
\n\
- name: Each node will be named normally with the Origin-Realm value\n\
- application-id: The Application-Id provided must exists as a registered 'stack id'\n\
- cer: User defined CER path file to be encoded to establish diameter connections. If missing, will be harcoded\n\
- dwr: User defined DWR path file to be encoded for diameter protocol keep alive. If missing, will be harcoded\n\
- entity: Target diameter entity (comma-separated '<address>:<port>' format). For example: 10.20.30.40:3868,10.20.30.41:3868. If missing, no entity will be enabled\n\
+ originRealm: Node identifier (Origin-Realm name).\n\
+ applicationId: The Application-Id provided must exists as a registered 'stack id'.\n\
+ originHost: Diameter application host name (system name). If missing, process sets o.s. hostname\n\
+ Note that if you have two or more realms, the names must be different.\n\
+ cer: User defined CER path file to be encoded to establish diameter connections.\n\
+ If missing, will be harcoded\n\
+ dwr: User defined DWR path file to be encoded for diameter protocol keep alive.\n\
+ If missing, will be harcoded\n\
+ allowedInactivityTime: Milliseconds for the maximum allowed inactivity time on server sessions born over the\n\
+ local server before being reset. If missing, default value of 90000 will be assigned\n\
+ tcpConnectDelay: Milliseconds to wait TCP connect to any server. If missing, default value of 200 will\n\
+ be assigned\n\
+ answersTimeout: Milliseconds to wait pending application answers from diameter peers. If missing,\n\
+ default value of 10000 will be assigned\n\
+ ceaTimeout: Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout'\n\
+ will be assigned\n\
+ watchdogPeriod: Milliseconds for watchdog timer (Tw) for diameter keep-alive procedure. If missing, default\n\
+ value of 30000 will be assigned\n\
+ entity: Target diameter entity (comma-separated '<address>:<port>' format).\n\
+ For example: 10.20.30.40:3868,10.20.30.41:3868. If missing, no entity will be enabled\n\
entityServerSessions: Diameter entity server sessions (0: diameter entity disabled). Default value of 1\n\
- diameterServer: Diameter own server address in '<address>:<port>' format. For example: 10.20.30.40:3868. If missing, no local server will be enabled\n\
+ diameterServer: Diameter own server address in '<address>:<port>' format. For example: 10.20.30.40:3868.\n\
+ If missing, no local server will be enabled\n\
diameterServerSessions: Diameter own server available connections (0: diameter server disabled). Default value of 1\n\
- balance: Balance over entity servers instead of doing standard behaviour (first primary, secondary if fails, etc.). Default value 'no'\n\
- ignoreErrors: Local server skips requests errors analysis which would prepare automatic answers for them when a problem is found. If no answer is programmed and entity is configured, a failed request would be forwarded (delegates at the end point) even if this parameter is missing. Default value 'no'\n\
+ balance: Balance over entity servers instead of doing standard behaviour (first primary, secondary\n\
+ if fails, etc.). Default value 'no'\n\
+ sessionBasedModelsClientSocketSelection: By default, round-robin will be applied for IEC model (SMS/MMS), and Session-Id Low Part\n\
+ will be analyzed for ECUR/SCUR model (data, voice and content). You could change ECUR/SCUR\n\
+ analysis behaviour providing 'SessionIdHighPart', 'SessionIdOptionalPart' (atoi applied;\n\
+ usually subscriber id data, i.e. MSISDN or IMSI) and 'RoundRobin' (also 'SessionIdLowPart')\n\
+ retries: Expired responses will cause a number of request retransmissions. Disabled by default (0 retries)\n\
+ log: Process log file (operations result, traffic log, etc.). By default '<originRealm>.launcher.log'.\n\
+ Empty string or \"null\" name, to disable. Warning: there is no rotation for log files\n\
+ (use logrotate or whatever you consider)\n\
+ splitLog: Splits log file (appends to log filename, extensions with the type of event: see help on\n\
+ startup information-level traces). No log files for code/decode and load operations are created.\n\
+ Default value 'no'\n\
+ detailedLog: Insert detailed information at log files. Should be disabled on automatic tests. Useful on\n\
+ 'balance' mode to know messages flow along the sockets. Default value 'no'\n\
+ dumpLog: Write to disk every incoming/outcoming message named as:\n\
+ '<originRealm>.<hop by hop>.<end to end>.<message code>.<request|answer>.<type of event>.xml'\n\
+ Default value 'no'\n\
+ burstLog: Burst operations log file. By default '<originRealm>.launcher.burst'. Empty string or \"null\" name, to disable.\n\
+ Warning: there is no rotation for log files (use logrotate or whatever). Output: dot (.) for each\n\
+ burst message sent/pushed, cross (x) for popped ones, and order number when multiple of 1% of burst\n\
+ list size, plus OTA requests when changed\n\
+\n\
-->\n\
\n\
";
Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
- a_myDiameterEngine = new MyDiameterEngine();
- a_myDiameterEngine->setRealm("ADL.ericsson.com");
- a_myDiameterEngine->setAutoBind(false); // allow to create client-sessions without binding them, in order to set timeouts.
- a_logFile = "launcher.log";
- a_burstLogFile = "launcher.burst";
- a_splitLog = false;
- a_detailedLog = false;
- a_dumpLog = false;
+ a_codecEngine = new anna::diameter::codec::Engine("MyCodecEngine");
a_timeEngine = NULL;
a_counterRecorder = NULL;
a_counterRecorderClock = NULL;
- a_entity = NULL;
- a_diameterLocalServer = NULL;
- a_cerPathfile = "cer.xml";
- a_dwrPathfile = "dwr.xml";
- a_workingStackId = 0;
-
- // Burst
- a_burstCycle = 1;
- a_burstRepeat = false;
- a_burstActive = false;
- a_burstLoadIndx = 0;
- a_burstDeliveryIt = a_burstMessages.begin();
- a_otaRequest = 0;
- a_burstPopCounter = 0;
-}
-anna::diameter::comm::Message *Launcher::createCommMessage() throw(anna::RuntimeException) {
- return a_commMessages.create();
-}
+ // a_nodes.clear();
+ a_workingNode = NULL;
-void Launcher::releaseCommMessage(anna::diameter::comm::Message *msg) throw() {
- a_commMessages.release(msg);
+ a_httpServerSocket = NULL;
}
-void Launcher::baseProtocolSetupAsClient() throw(anna::RuntimeException) {
-
- anna::diameter::codec::Engine *codecEngine;
-
- codecEngine = getCodecEngine();
- // XXXXXXXXXXXXXXXXXXXX codecEngine = a_myDiameterEngine->getBaseProtocolCodecEngine();
-
-
- // Build CER
- // <CER> ::= < Diameter Header: 257, REQ >
- // { Origin-Host } 264 diameterIdentity
- // { Origin-Realm } 296 idem
- // 1* { Host-IP-Address } 257, address
- // { Vendor-Id } 266 Unsigned32
- // { Product-Name } 269 UTF8String
- // [Origin-State-Id] 278 Unsigned32
- // * [ Supported-Vendor-Id ] 265 Unsigned32
- // * [ Auth-Application-Id ] 258 Unsigned32
- // * [Acct-Application-Id] 259 Unsigned32
- anna::diameter::codec::Message diameterCER(codecEngine);
- int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
- std::string OH = a_myDiameterEngine->getHost();
- std::string OR = a_myDiameterEngine->getRealm();
- std::string hostIP = anna::functions::getHostnameIP(); // Address
- int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
- std::string productName = "ANNA Diameter Launcher"; // UTF8String
- bool loadingError = false;
- try {
- diameterCER.loadXML(a_cerPathfile);
- } catch(anna::RuntimeException &ex) {
- //ex.trace();
- loadingError = true;
- }
- if(loadingError) {
- LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
- diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
- diameterCER.setApplicationId(applicationId);
- diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
- diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
- diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str()); // supported by Address class, anyway is better to provide "1|<ip address>"
- diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
- diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
- diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
- }
- // Build DWR
- // <DWR> ::= < Diameter Header: 280, REQ >
- // { Origin-Host }
- // { Origin-Realm }
- anna::diameter::codec::Message diameterDWR(codecEngine);
- loadingError = false;
+void Launcher::servicesFromXML(const anna::xml::Node* servicesNode) throw(anna::RuntimeException) {
+ //<!ATTLIST stack id CDATA #REQUIRED dictionary CDATA #REQUIRED>
+ const anna::xml::Attribute *id, *dictionary;
- try {
- diameterDWR.loadXML(a_dwrPathfile);
- } catch(anna::RuntimeException &ex) {
- //ex.trace();
- loadingError = true;
- }
+ // <!ATTLIST node originRealm CDATA #REQUIRED applicationId CDATA #REQUIRED originHost CDATA #IMPLIED cer CDATA #IMPLIED dwr CDATA #IMPLIED allowedInactivityTime CDATA #IMPLIED tcpConnectDelay CDATA #IMPLIED answersTimeout CDATA #IMPLIED ceaTimeout CDATA #IMPLIED watchdogPeriod CDATA #IMPLIED entity CDATA #IMPLIED entityServerSessions CDATA #IMPLIED diameterServer CDATA #IMPLIED diameterServerSessions CDATA #IMPLIED balance (yes | no) #IMPLIED sessionBasedModelsClientSocketSelection (SessionIdLowPart | SessionIdHighPart | SessionIdOptionalPart | RoundRobin) #IMPLIED retries CDATA #IMPLIED log CDATA #IMPLIED splitLog (yes | no) #IMPLIED detailedLog (yes | no) #IMPLIED dumpLog (yes | no) #IMPLIED burstLog (yes | no) #IMPLIED>
+ const anna::xml::Attribute *originRealm, *appId, *originHost, *cer, *dwr, *allowedInactivityTime, *tcpConnectDelay,
+ *answersTimeout, *ceaTimeout, *watchdogPeriod, *entity, *entityServerSessions,
+ *diameterServer, *diameterServerSessions, *balance, *sessionBasedModelsClientSocketSelection,
+ *retries, *log, *splitLog, *detailedLog, *dumpLog, *burstLog;
+
+ // Never clear services content from here (append new data from xml). At the moment no node removing is implemented in this process
- if(loadingError) {
- LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
- diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
- diameterDWR.setApplicationId(applicationId);
- diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
- diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
+ // Stacks
+ anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
+ anna::diameter::stack::Dictionary *d;
+
+ for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) {
+ std::string nodeName = (*it)->getName();
+
+ if(nodeName == "stack") {
+ // Input data:
+ id = (*it)->getAttribute("id");
+ dictionary = (*it)->getAttribute("dictionary");
+
+ try {
+ d = stackEngine.createDictionary(id->getIntegerValue(), dictionary->getValue());
+ getCodecEngine()->setDictionary(d);
+ } catch(anna::RuntimeException &ex) {
+ //_exit(ex.asString());
+ throw ex;
+ }
+ }
}
- // Assignment for CER/DWR and CEA/DWA:
- a_myDiameterEngine->setCERandDWR(diameterCER.code(), diameterDWR.code());
- //a_myDiameterEngine->setCEAandDWA(diameterCEA.code(), diameterDWA.code());
-}
+ // Codec engine adjustments:
+ // Auto stack selection based on Application-ID:
+ bool multistack = (stackEngine.stack_size() > 1);
+ if (multistack) getCodecEngine()->selectStackWithApplicationId(true);
+
+ for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) {
+ std::string nodeName = (*it)->getName();
+
+ if(nodeName == "node") {
+ // Input data:
+ originRealm = (*it)->getAttribute("originRealm");
+ appId = (*it)->getAttribute("applicationId");
+ originHost = (*it)->getAttribute("originHost", false /* no exception */);
+ cer = (*it)->getAttribute("cer", false /* no exception */);
+ dwr = (*it)->getAttribute("dwr", false /* no exception */);
+ allowedInactivityTime = (*it)->getAttribute("allowedInactivityTime", false /* no exception */);
+ tcpConnectDelay = (*it)->getAttribute("tcpConnectDelay", false /* no exception */);
+ answersTimeout = (*it)->getAttribute("answersTimeout", false /* no exception */);
+ ceaTimeout = (*it)->getAttribute("ceaTimeout", false /* no exception */);
+ watchdogPeriod = (*it)->getAttribute("watchdogPeriod", false /* no exception */);
+ entity = (*it)->getAttribute("entity", false /* no exception */);
+ entityServerSessions = (*it)->getAttribute("entityServerSessions", false /* no exception */);
+ diameterServer = (*it)->getAttribute("diameterServer", false /* no exception */);
+ diameterServerSessions = (*it)->getAttribute("diameterServerSessions", false /* no exception */);
+ balance = (*it)->getAttribute("balance", false /* no exception */); // (yes | no)
+ sessionBasedModelsClientSocketSelection = (*it)->getAttribute("sessionBasedModelsClientSocketSelection", false /* no exception */); // (SessionIdHighPart | SessionIdOptionalPart | RoundRobin)
+ retries = (*it)->getAttribute("retries", false /* no exception */);
+ log = (*it)->getAttribute("log", false /* no exception */);
+ splitLog = (*it)->getAttribute("splitLog", false /* no exception */); // (yes | no)
+ detailedLog = (*it)->getAttribute("detailedLog", false /* no exception */); // (yes | no)
+ dumpLog = (*it)->getAttribute("dumpLog", false /* no exception */); // (yes | no)
+ burstLog = (*it)->getAttribute("burstLog", false /* no exception */); // (yes | no)
+
+ // Basic checkings:
+ if (stackEngine.getDictionary(appId->getIntegerValue()) == NULL) {
+ std::string msg = "Cannot found a registered stack id with the value of applicationId provided: "; msg += appId->getValue();
+ throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
+ }
+ realm_nodes_it nodeIt = a_nodes.find(originRealm->getValue());
+ if (nodeIt != a_nodes.end()) {
+ std::string msg = "Already registered node name (Origin-Realm): "; msg += originRealm->getValue();
+ throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
+ }
-void Launcher::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail, anna::diameter::codec::Engine *codecEngine) const throw() {
-// if (!logEnabled()) return;
- anna::diameter::codec::Message codecMsg(codecEngine);
- try { codecMsg.decode(db); } catch(anna::RuntimeException &ex) { ex.trace(); }
- writeLogFile(codecMsg, logExtension, detail);
+ // Engine time measures checking & assignment:
+ anna::Millisecond allowedInactivityTimeMs(90000);
+ anna::Millisecond tcpConnectDelayMs(200);
+ anna::Millisecond answersTimeoutMs(10000);
+ anna::Millisecond ceaTimeoutMs(10000);
+ anna::Millisecond watchdogPeriodMs(30000);
+
+ if (allowedInactivityTime) allowedInactivityTimeMs = checkTimeMeasure("allowedInactivityTime", allowedInactivityTime->getValue());
+ if (tcpConnectDelay) tcpConnectDelayMs = checkTimeMeasure("tcpConnectDelay", tcpConnectDelay->getValue());
+ if (answersTimeout) answersTimeoutMs = checkTimeMeasure("answersTimeout", answersTimeout->getValue());
+ if (ceaTimeout) ceaTimeoutMs = checkTimeMeasure("ceaTimeout", ceaTimeout->getValue());
+ if (watchdogPeriod) watchdogPeriodMs = checkTimeMeasure("watchdogPeriod", watchdogPeriod->getValue());
+
+ // Checking command line parameters
+ std::string sessionBasedModelsType;
+ if(sessionBasedModelsClientSocketSelection) {
+ sessionBasedModelsType = sessionBasedModelsClientSocketSelection->getValue();
+ if((sessionBasedModelsType != "SessionIdHighPart") && (sessionBasedModelsType != "SessionIdOptionalPart") && (sessionBasedModelsType != "RoundRobin")) {
+ throw anna::RuntimeException("Parameter 'sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
+ }
+ }
-}
+ int retransmissions = retries ? retries->getIntegerValue() : 0;
+ if(retransmissions < 0) {
+ throw anna::RuntimeException("Parameter 'retries' must be non-negative", ANNA_FILE_LOCATION);
+ }
-// Si ya lo tengo decodificado:
-void Launcher::writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw() {
-// if (!logEnabled()) return;
- // Open target file:
- std::string targetFile = a_logFile;
+ // Create new Node instance /////////////////////////////////////////////////////////////////
+ a_workingNode = new RealmNode(originRealm->getValue(), appId->getIntegerValue(), a_codecEngine);
+ MyDiameterEngine *commEngine = a_workingNode->getMyDiameterEngine();
+ /////////////////////////////////////////////////////////////////////////////////////////////
+
+ // Assignments:
+ commEngine->setMaxConnectionDelay(tcpConnectDelayMs);
+ commEngine->setWatchdogPeriod(watchdogPeriodMs);
+
+ // Realm information:
+ if (originHost) commEngine->setHost(originHost->getValue());
+ commEngine->setRealm(originRealm->getValue());
+
+ // Diameter entity:
+ if(entity) {
+ int sessions = entityServerSessions ? entityServerSessions->getIntegerValue() : 1;
+
+ if(sessions > 0) {
+ // Number of sessions:
+ commEngine->setNumberOfClientSessionsPerServer(sessions);
+
+ // Client CER and DWR
+ std::string cerPathfile = cer ? cer->getValue() : "";
+ std::string dwrPathfile = dwr ? dwr->getValue() : "";
+ commEngine->setClientCERandDWR(cerPathfile, dwrPathfile);
+
+ // Register one entity for this engine:
+ a_workingNode->createEntity(entity->getValue(), ceaTimeoutMs, answersTimeoutMs);
+ a_workingNode->setRequestRetransmissions(retransmissions);
+ a_workingNode->getEntity()->setSessionBasedModelsType(sessionBasedModelsType);
+ a_workingNode->getEntity()->setBalance(balance ? (balance->getValue() == "yes") : false); // for sendings
+ }
+ }
- if(a_splitLog) {
- targetFile += ".";
- targetFile += logExtension;
- }
+ // Diameter Server:
+ if(diameterServer) {
+ int sessions = diameterServerSessions ? diameterServerSessions->getIntegerValue() : 1;
+ a_workingNode->startDiameterServer(diameterServer->getValue(), sessions, allowedInactivityTimeMs);
+ }
- std::ofstream out(targetFile.c_str(), std::ifstream::out | std::ifstream::app);
- // Set text to dump:
- std::string title = "[";
- title += logExtension;
- title += "]";
- // Build complete log:
- std::string log = "\n";
- std::string xml = decodedMessage.asXMLString();
-
-
- if(a_detailedLog) {
- anna::time::Date now;
- now.setNow();
- title += " ";
- title += now.asString();
- log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline);
- log += xml;
- log += "\n";
- log += anna::functions::highlight("Used resource");
- log += detail;
- log += "\n";
- } else {
- log += title;
- log += "\n";
- log += xml;
- log += "\n";
- }
+ // Logs:
+ std::string realm = commEngine->getRealm();
+ std::string s_log = realm + ".launcher.log"; if (log) s_log = log->getValue();
+ bool b_splitLog = (splitLog ? (splitLog->getValue() == "yes") : false);
+ bool b_detailedLog = (detailedLog ? (detailedLog->getValue() == "yes") : false);
+ bool b_dumpLog = (dumpLog ? (dumpLog->getValue() == "yes") : false);
+ std::string s_burstLog = realm + ".launcher.burst"; if (burstLog) s_burstLog = burstLog->getValue();
+ a_workingNode->setLogs(s_log, b_splitLog, b_detailedLog, b_dumpLog, s_burstLog);
- if(a_dumpLog) {
- std::string name = anna::functions::asString(decodedMessage.getHopByHop());
- name += ".";
- name += anna::functions::asString(decodedMessage.getEndToEnd());
- name += ".";
- name += anna::functions::asString(decodedMessage.getId().first);
- name += ".";
- name += ((decodedMessage.getId().second) ? "request.":"answer.");
- name += logExtension;
- name += ".xml";
- std::ofstream outMsg(name.c_str(), std::ifstream::out | std::ifstream::app);
- outMsg.write(xml.c_str(), xml.size());
- outMsg.close();
- }
- // Write and close
- out.write(log.c_str(), log.size());
- out.close();
+ // New Node assignment //////////////////////////////////////////////////////////////////////
+ a_nodes[originRealm->getValue()] = a_workingNode;
+ /////////////////////////////////////////////////////////////////////////////////////////////
+ }
+ }
}
-void Launcher::writeBurstLogFile(const std::string &buffer) throw() {
- std::ofstream out(a_burstLogFile.c_str(), std::ifstream::out | std::ifstream::app);
- out.write(buffer.c_str(), buffer.size());
- out.close(); // close() will be called when the object is destructed (i.e., when it goes out of scope).
- // you'd call close() only if you indeed for some reason wanted to close the filestream
- // earlier than it goes out of scope.
-}
-void Launcher::checkTimeMeasure(const char * commandLineParameter, bool optional) throw(anna::RuntimeException) {
- CommandLine& cl(anna::CommandLine::instantiate());
+void Launcher::loadServices(const std::string & xmlPathFile) throw(anna::RuntimeException) {
+
+ LOGDEBUG(
+ std::string trace = "Loading ADML services file '";
+ trace += xmlPathFile;
+ trace += "'";
+ anna::Logger::debug(trace, ANNA_FILE_LOCATION);
+ );
+ anna::xml::DocumentFile xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy)
+ anna::xml::DTDMemory xmlDTD;
+ const anna::xml::Node *rootNode;
+ xmlDocument.initialize(xmlPathFile.c_str()); // fail here is i/o error
+ xmlDTD.initialize(ServicesDTD);
+ try {
+ rootNode = xmlDocument.parse(xmlDTD); // Parsing: fail here if xml violates dtd
+ }
+ catch (anna::RuntimeException &ex) {
+ LOGWARNING(
+ std::string msg = "Services DTD schema:\n\n";
+ msg += ServicesDTD;
+ anna::Logger::warning(msg, ANNA_FILE_LOCATION);
+ );
+ throw ex;
+ }
+
+ LOGDEBUG(
+ std::string trace = "Loaded XML file (";
+ trace += xmlPathFile;
+ trace += "):\n";
+ trace += anna::xml::Compiler().apply(rootNode);
+ anna::Logger::debug(trace, ANNA_FILE_LOCATION);
+ );
+ servicesFromXML(rootNode);
+}
- if(!cl.exists(commandLineParameter) && optional) return; // start error if mandatory
- std::string parameter = cl.getValue(commandLineParameter);
+anna::Millisecond Launcher::checkTimeMeasure(const std::string ¶meter, const std::string &value) throw(anna::RuntimeException) {
- if(anna::functions::isLike("^[0-9]+$", parameter)) { // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
- int msecs = cl.getIntegerValue(commandLineParameter);
+ if(anna::functions::isLike("^[0-9]+$", value)) { // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
+ int msecs;
+ std::istringstream ( value ) >> msecs;
if(msecs > a_timeEngine->getMaxTimeout()) { // 600000 ms
- std::string msg = "Commandline parameter '";
- msg += commandLineParameter;
- msg += "' is greater than allowed max timeout for timming engine: ";
+ std::string msg = "Configuration value for '";
+ msg += parameter;
+ msg += "' ("; msg += value; msg += " msecs) is greater than allowed max timeout for timming engine: ";
msg += anna::functions::asString(a_timeEngine->getMaxTimeout());
throw RuntimeException(msg, ANNA_FILE_LOCATION);
}
if(msecs > 300000) {
- std::string msg = "Commandline parameter '";
- msg += commandLineParameter;
- msg += "' is perhaps very big (over 5 minutes). Take into account memory consumption issues.";
+ std::string msg = "Configuration value for '";
+ msg += parameter;
+ msg += "' ("; msg += value; msg += " msecs) is perhaps very big (over 5 minutes).";
LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
}
if(msecs <= a_timeEngine->getResolution()) {
- std::string msg = "Commandline parameter '";
- msg += commandLineParameter;
- msg += "' (and in general, all time measures) must be greater than timming engine resolution: ";
+ std::string msg = "Configuration value for '";
+ msg += parameter;
+ msg += "' ("; msg += value; msg += " msecs) as any other time measure, must be greater than timming engine resolution: ";
msg += anna::functions::asString(a_timeEngine->getResolution());
throw RuntimeException(msg, ANNA_FILE_LOCATION);
}
- return; // ok
+ return (anna::Millisecond)msecs; // ok
}
- // Excepcion (por no ser entero):
- std::string msg = "Error at commandline parameter '";
- msg += commandLineParameter;
- msg += "' = '";
+ // Non-integer exception:
+ std::string msg = "Configuration error for '";
msg += parameter;
+ msg += "' = '";
+ msg += value;
msg += "': must be a non-negative integer number";
throw RuntimeException(msg, ANNA_FILE_LOCATION);
}
-void Launcher::startDiameterServer(int diameterServerSessions) throw(anna::RuntimeException) {
- if(diameterServerSessions <= 0) return;
+bool Launcher::setWorkingNode(const std::string &name) throw() {
+ bool result = false;
- std::string address;
- int port;
- CommandLine& cl(anna::CommandLine::instantiate());
- anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("diameterServer"), address, port);
- //ServerSocket *createServerSocket(const std::string & addr, int port = Session::DefaultPort, int maxConnections = -1, int category = 1, const std::string & description = "")
- a_diameterLocalServer = (MyLocalServer*)(a_myDiameterEngine->createLocalServer(address, port, diameterServerSessions));
- a_diameterLocalServer->setDescription("Launcher diameter local server");
- a_diameterLocalServer->setCodecEngine(getCodecEngine()); // this is for automatic answers (failed-avp) XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX el del nodo correspondiente
- int allowedInactivityTime = 90000; // ms
+ realm_nodes_nc_it nodeIt = a_nodes.find(name);
+ if (nodeIt == a_nodes.end()) {
+ LOGWARNING(
+ std::string msg = "Unknown node with name '"; msg += name; msg += "'. Ignoring ...";
+ anna::Logger::warning(msg, ANNA_FILE_LOCATION);
+ );
+ }
+ else {
+ a_workingNode = nodeIt->second;
+ result = true;
+ }
- if(cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime");
+ return result;
+}
+
+RealmNode *Launcher::getRealmNode(const std::string &realmName) const throw() {
+ for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++)
+ if(it->second->getMyDiameterEngine()->getRealm() == realmName) return it->second;
- a_diameterLocalServer->setAllowedInactivityTime((anna::Millisecond)allowedInactivityTime);
+ return NULL; // this never happens
}
void Launcher::initialize()
anna::comm::Application::initialize();
CommandLine& cl(anna::CommandLine::instantiate());
anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single);
-// if (cl.exists ("clone"))
-// workMode = anna::comm::Communicator::WorkMode::Clone;
a_communicator = new MyCommunicator(workMode);
+
//a_timeEngine = new anna::timex::Engine((anna::Millisecond)600000, anna::timex::Engine::minResolution);
a_timeEngine = new anna::timex::Engine((anna::Millisecond)600000, (anna::Millisecond)100); // puedo bajar hasta 10
- // Counters record procedure:
- anna::Millisecond cntRecordPeriod = (anna::Millisecond)300000; // ms
-
- if(cl.exists("cntRecordPeriod")) cntRecordPeriod = cl.getIntegerValue("cntRecordPeriod");
+ // Counters record procedure:
+ const char *varname = "cntRecordPeriod";
+ anna::Millisecond cntRecordPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)300000;
if(cntRecordPeriod != 0) {
- checkTimeMeasure("cntRecordPeriod");
a_counterRecorderClock = new MyCounterRecorderClock("Counters record procedure clock", cntRecordPeriod); // clock
std::string cntDir = ".";
-
if(cl.exists("cntDir")) cntDir = cl.getValue("cntDir");
-
a_counterRecorder = new MyCounterRecorder(cntDir + anna::functions::asString("/Counters.Pid%d", (int)getPid()));
}
+
+ // Load launcher services:
+ loadServices(cl.getValue("services")); // before run (have components to be created)
+
+ // Show loaded stacks:
+ std::cout << "Stacks provided:" << std::endl;
+ std::cout << anna::functions::tab(anna::diameter::stack::Engine::instantiate().asString(false /* light */));
+ std::cout << std::endl;
}
void Launcher::run()
throw(anna::RuntimeException) {
LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION));
CommandLine& cl(anna::CommandLine::instantiate());
+ anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
+
// Start time:
a_start_time.setNow();
// Statistics:
anna::statistics::Engine::instantiate().enable();
- // Checking command line parameters
- if(cl.exists("sessionBasedModelsClientSocketSelection")) {
- std::string type = cl.getValue("sessionBasedModelsClientSocketSelection");
-
- if((type != "SessionIdHighPart") && (type != "SessionIdOptionalPart") && (type != "RoundRobin")) {
- throw anna::RuntimeException("Commandline option '-sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
- }
- }
-
// Tracing:
if(cl.exists("trace"))
anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
}
- // Stack:
- a_codecEngine = new anna::diameter::codec::Engine(DIAMETER_CODEC_ENGINE_NAME_PREFIX);
- anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
- std::string stacks = cl.getValue("stacks");
- bool multistack = false;
- try {
- anna::Tokenizer stacksTok;
- stacksTok.apply(stacks, "#");
- anna::Tokenizer::const_iterator stacks_it, stack_it;
-
- for(stacks_it = stacksTok.begin(); stacks_it != stacksTok.end(); stacks_it++) {
- std::string stack = anna::Tokenizer::data(stacks_it);
- anna::Tokenizer stackTok;
- stackTok.apply(stack, ",");
-
- if(stackTok.size() == 1) {
- if(stacksTok.size() != 1)
- throw anna::RuntimeException("Application Id value is mandatory when more than one stack is going to be configured", ANNA_FILE_LOCATION);
-
- anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* no matter */, stack); // the stack is the dictionary
- codecEngine->setDictionary(d);
- break;
- }
-
- if(stackTok.size() != 2)
- throw anna::RuntimeException("Each stack must be in the form '<application-id>,<xml dictionary pathfile>'", ANNA_FILE_LOCATION);
-
- multistack = true;
- stack_it = stackTok.begin();
- unsigned int stackId = atoll(anna::Tokenizer::data(stack_it));
- stack_it++;
- std::string file = anna::Tokenizer::data(stack_it);
- anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(stackId, file);
- }
-
- // Auto stack selection based on Application-ID:
- if (multistack) getCodecEngine()->selectStackWithApplicationId(true);
-
- std::cout << "Stacks provided: " << std::endl;
- std::cout << anna::functions::tab(stackEngine.asString(false /* light */));
- std::cout << std::endl;
- } catch(anna::RuntimeException &ex) {
- _exit(ex.asString());
- }
- //LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION));
-
-
///////////////////////////////
// Diameter library COUNTERS //
///////////////////////////////
appMsgOamModule.enableCounters(); // this special module is disabled by default (the only)
+
/////////////////////////////////
// Counter recorder associated //
/////////////////////////////////
// Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always').
// If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError':
if(cl.exists("integrationAndDebugging")) {
- getCodecEngine()->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always); // XXXXXXXXXXXXXXXXXXXXXXXXX
+ getCodecEngine()->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always);
getCodecEngine()->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
}
else if (fixMode == "Always") fm = anna::diameter::codec::Engine::FixMode::Always;
else if (fixMode == "Never") fm = anna::diameter::codec::Engine::FixMode::Never;
else LOGINFORMATION(anna::Logger::information("Unreconized command-line fix mode. Assumed default 'BeforeEncoding'", ANNA_FILE_LOCATION));
- getCodecEngine()->setFixMode(fm); // XXXXXXXXXXXXXXXXXXXXXXX
- }
-
- getCodecEngine()->ignoreFlagsOnValidation(cl.exists("ignoreFlags")); // XXXXXXXXXXXXXXXXXXXXXXX
-
- // Base protocol for internal use (CEA, DWA, DPA and tracing:
- a_myDiameterEngine->setBaseProtocolCodecEngine(getCodecEngine());
-
-
- // Diameter Server:
- if(cl.exists("diameterServer"))
- startDiameterServer(cl.exists("diameterServerSessions") ? cl.getIntegerValue("diameterServerSessions") : 1);
-
- // Optional command line parameters ////////////////////////////////////////////////////////
- checkTimeMeasure("allowedInactivityTime");
- checkTimeMeasure("tcpConnectDelay");
- checkTimeMeasure("answersTimeout");
- checkTimeMeasure("ceaTimeout");
- checkTimeMeasure("watchdogPeriod");
- checkTimeMeasure("reconnectionPeriod");
- int tcpConnectDelay = 200; // ms
- anna::Millisecond answersTimeout = (anna::Millisecond)10000; // ms
- anna::Millisecond ceaTimeout;
- anna::Millisecond watchdogPeriod = (anna::Millisecond)30000; // ms
- int reconnectionPeriod = 10000; // ms
-
- if(cl.exists("tcpConnectDelay")) tcpConnectDelay = cl.getIntegerValue("tcpConnectDelay");
-
- if(cl.exists("answersTimeout")) answersTimeout = cl.getIntegerValue("answersTimeout");
-
- if(cl.exists("ceaTimeout")) ceaTimeout = cl.getIntegerValue("ceaTimeout");
- else ceaTimeout = answersTimeout;
-
- if(cl.exists("watchdogPeriod")) watchdogPeriod = cl.getIntegerValue("watchdogPeriod");
-
- if(cl.exists("reconnectionPeriod")) reconnectionPeriod = cl.getIntegerValue("reconnectionPeriod");
-
- a_myDiameterEngine->setMaxConnectionDelay((anna::Millisecond)tcpConnectDelay);
- a_myDiameterEngine->setWatchdogPeriod(watchdogPeriod);
- std::string originHost = "";
- std::string originRealm = "";
-
- if(cl.exists("cer")) a_cerPathfile = cl.getValue("cer");
-
- if(cl.exists("dwr")) a_dwrPathfile = cl.getValue("dwr");
-
- if(cl.exists("originHost")) originHost = cl.getValue("originHost");
-
- if(cl.exists("originRealm")) originRealm = cl.getValue("originRealm");
-
- a_myDiameterEngine->setHost(originHost);
- a_myDiameterEngine->setRealm(originRealm);
-
- // Diameter entity:
- if(cl.exists("entity")) {
- int entityServerSessions = cl.exists("entityServerSessions") ? cl.getIntegerValue("entityServerSessions") : 1;
-
- if(entityServerSessions > 0) {
- baseProtocolSetupAsClient();
- anna::socket_v servers = anna::functions::getSocketVectorFromString(cl.getValue("entity"));
- a_myDiameterEngine->setNumberOfClientSessionsPerServer(entityServerSessions);
- a_entity = (MyDiameterEntity*)(a_myDiameterEngine->createEntity(servers, "Launcher diameter entity"));
- a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::Bind, ceaTimeout);
- a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::ApplicationMessage, answersTimeout);
- a_entity->setCodecEngine(getCodecEngine()); // XXXXXXXXXXXXXXXXXXXXXXX
- a_entity->bind();
- }
+ getCodecEngine()->setFixMode(fm);
}
- // Logs
- if(cl.exists("log")) a_logFile = cl.getValue("log");
-
- if(cl.exists("splitLog")) a_splitLog = true;
-
- if(cl.exists("detailedLog")) a_detailedLog = true;
-
- if(cl.exists("dumpLog")) a_dumpLog = true;
+ getCodecEngine()->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
- if(cl.exists("burstLog")) a_burstLogFile = cl.getValue("burstLog");
// Log statistics concepts
if(cl.exists("logStatisticSamples")) {
}
}
- a_communicator->setRecoveryTime((const anna::Millisecond)reconnectionPeriod);
- if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket); // HTTP
+ // Start client connections //////////////////////////////////////////////////////////////////////////////////
+ MyDiameterEntity *entity;
+ for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) {
+ entity = it->second->getEntity();
+ if (entity) entity->bind();
+ }
+
+ // Go into communicator poll
+ // Reconnection period (tcp reconnect retry time):
+ const char *varname = "reconnectionPeriod";
+ anna::Millisecond reconnectionPeriod = (cl.exists(varname)) ? checkTimeMeasure(varname, cl.getValue(varname)) : (anna::Millisecond)10000;
+
+ a_communicator->setRecoveryTime(reconnectionPeriod);
+ if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket); // HTTP
a_communicator->accept();
}
return false;
}
-int Launcher::clearBurst() throw() {
- int size = a_burstMessages.size();
-
- if(size) {
- std::map<int, anna::diameter::comm::Message*>::const_iterator it;
- std::map<int, anna::diameter::comm::Message*>::const_iterator it_min(a_burstMessages.begin());
- std::map<int, anna::diameter::comm::Message*>::const_iterator it_max(a_burstMessages.end());
-
- for(it = it_min; it != it_max; it++) releaseCommMessage((*it).second);
-
- a_burstMessages.clear();
- } else {
- std::string msg = "Burst list already empty. Nothing done";
- std::cout << msg << std::endl;
- LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
- }
-
- a_burstActive = false;
- a_burstLoadIndx = 0;
- a_burstDeliveryIt = a_burstMessages.begin();
- return size;
-}
-
-int Launcher::loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException) {
- anna::diameter::comm::Message *msg = createCommMessage();
- msg->setBody(db);
- a_burstMessages[a_burstLoadIndx++] = msg;
- return (a_burstLoadIndx - 1);
-}
-
-int Launcher::stopBurst() throw() {
- if(!a_burstActive) {
- std::string msg = "Burst launch is already stopped. Nothing done";
- std::cout << msg << std::endl;
- LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
- return -1;
- }
-
- a_burstActive = false;
- // Remaining on cycle:
- return (a_burstMessages.size() - (*a_burstDeliveryIt).first);
-}
-
-int Launcher::popBurst(int releaseAmount) throw() {
- if(!a_burstActive) {
- std::string msg = "Burst launch is stopped. Nothing done";
- std::cout << msg << std::endl;
- LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
- return -1;
- }
-
- if(releaseAmount < 1) {
- std::string msg = "No valid release amount is specified. Ignoring burst pop";
- std::cout << msg << std::endl;
- LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
- return -2;
- }
-
- int currentOTArequests = a_entity->getOTARequests();
- a_burstPopCounter = (releaseAmount > currentOTArequests) ? currentOTArequests : releaseAmount;
- return a_burstPopCounter;
-}
-
-int Launcher::pushBurst(int loadAmount) throw() {
- if(a_burstMessages.size() == 0) {
- std::string msg = "Burst data not found (empty list). Ignoring burst launch";
- std::cout << msg << std::endl;
- LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
- return -1;
- }
-
- if(loadAmount < 1) {
- std::string msg = "No valid load amount is specified. Ignoring burst push";
- std::cout << msg << std::endl;
- LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
- return -2;
- }
-
- a_burstActive = true;
- int count;
-
- for(count = 0; count < loadAmount; count++)
- if(!sendBurstMessage()) break;
-
- return count;
-}
-
-int Launcher::sendBurst(int loadAmount) throw() {
- if(a_burstMessages.size() == 0) {
- std::string msg = "Burst data not found (empty list). Ignoring burst launch";
- std::cout << msg << std::endl;
- LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
- return -1;
- }
-
- if(loadAmount < 1) {
- std::string msg = "No valid load amount is specified. Ignoring burst send";
- std::cout << msg << std::endl;
- LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
- return -2;
- }
-
- int count;
-
- for(count = 0; count < loadAmount; count++)
- if(!sendBurstMessage(true /* anyway */)) break;
-
- return count;
-}
-
-int Launcher::startBurst(int initialLoad) throw() {
- if(initialLoad < 1) {
- std::string msg = "No initial load is specified. Ignoring burst start";
- std::cout << msg << std::endl;
- LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
- return -2;
- }
-
- a_burstActive = true;
- a_burstCycle = 1;
- a_burstDeliveryIt = a_burstMessages.begin();
- return (pushBurst(initialLoad));
-}
-
-bool Launcher::sendBurstMessage(bool anyway) throw() {
- if(!anyway && !burstActive()) return false;
-
- if(a_burstPopCounter > 0) {
- if(burstLogEnabled()) writeBurstLogFile("x");
-
- a_burstPopCounter--;
- return false;
- }
-
- if(a_burstDeliveryIt == a_burstMessages.end()) {
- a_burstDeliveryIt = a_burstMessages.begin();
-
- if(!anyway) {
- if(a_burstRepeat) {
- a_burstCycle++;
-
- if(burstLogEnabled()) writeBurstLogFile(anna::functions::asString("\nCompleted burst cycle. Starting again (repeat mode) on cycle %d.\n", a_burstCycle));
- } else {
- if(burstLogEnabled()) writeBurstLogFile("\nCompleted burst cycle. Burst finished (repeat mode disabled).\n");
-
- stopBurst();
- return false;
- }
- }
- }
-
- anna::diameter::comm::Message *msg = (*a_burstDeliveryIt).second;
- int order = (*a_burstDeliveryIt).first + 1;
- a_burstDeliveryIt++;
- bool dot = true;
- // sending
- bool result = a_entity->send(msg, anna::CommandLine::instantiate().exists("balance"));
-
- if(burstLogEnabled()) {
- if(a_burstMessages.size() >= 100)
- dot = (order % (a_burstMessages.size() / 100));
-
- if(dot) {
- writeBurstLogFile(".");
- } else {
- writeBurstLogFile(anna::functions::asString(" %d", order));
- int otaReqs = a_entity->getOTARequests();
-
- if(result && (otaReqs != a_otaRequest)) {
- // false if was a sending after an answer received (no OTA change in this case)
- // true after push and pop operations
- a_otaRequest = otaReqs;
- writeBurstLogFile(anna::functions::asString("[OTA %d]", a_otaRequest));
- }
- }
- }
-
- // Detailed log:
- if(logEnabled()) {
- anna::diameter::comm::Server *usedServer = a_entity->getLastUsedResource();
- anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
- std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
- writeLogFile(msg->getBody(), (result ? "sent2e" : "send2eError"), detail, getCodecEngine()); // el del nodo de trabajo
- }
-
- return result;
-}
-
-std::string Launcher::lookBurst(int order) const throw() {
- std::string result = "No message found for order provided (";
- result += anna::functions::asString(order);
- result += ")";
- std::map<int, anna::diameter::comm::Message*>::const_iterator it = a_burstMessages.find(order - 1);
-
- if(it != a_burstMessages.end()) {
- // Decode
- anna::diameter::codec::Message codecMsg(getCodecEngine()); // XXXXXXXXXXXXXXXX el del nodo de trabajo
- try { codecMsg.decode((*it).second->getBody()); } catch(anna::RuntimeException &ex) { ex.trace(); }
- result = codecMsg.asXMLString();
- }
-
- return result;
-}
-
-std::string Launcher::gotoBurst(int order) throw() {
- std::string result = "Position not found for order provided (";
- std::map<int, anna::diameter::comm::Message*>::iterator it = a_burstMessages.find(order - 1);
-
- if(it != a_burstMessages.end()) {
- a_burstDeliveryIt = it;
- result = "Position updated for order provided (";
- }
-
- result += anna::functions::asString(order);
- result += ")";
- return result;
+void Launcher::resetStatistics() throw() {
+ getWorkingNode()->getMyDiameterEngine()->resetStatistics();
}
void Launcher::resetCounters() throw() {
result += "\nOVERVIEW";
result += "\n--------";
result += "\n";
- result += "\nThe ADL (ANNA Diameter Launcher) process is a complete diameter agent with client and server";
- result += "\n capabilities as well as balancer (proxy) features. It could be used as diameter server";
- result += "\n (i.e. to simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.),";
- result += "\n and balancer systems to provide failover to external round-robin launchers. Also, auxiliary";
- result += "\n encoder/decoder/loader function could be deployed to reinterpret certain external flow and";
- result += "\n send it to another process.";
- result += "\n";
+ result += "\nThe ADML (ANNA Diameter Multirealm Launcher) process is a multi-realm node with client and server";
+ result += "\n capabilities as well as balancer (proxy) features. It could be used as diameter server (i.e. to";
+ result += "\n simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.), and balancer";
+ result += "\n systems to provide failover to external round-robin launchers. Also, auxiliary encoder/decoder/loader";
+ result += "\n function could be deployed to reinterpret certain external flow and send it to another process.";
+ result += "\n ";
result += "\nThe ANNA::diameter_comm built-in module provides a great set of characteristics as multiple connections";
result += "\n on both server and client side, definition for multiple-server entities (and not only two as standard";
result += "\n establish as minimum), separate statistics analyzer per each resource, automatic CER/CEA and DWR/DWA";
result += "\n generation, expiration control and many more features.";
result += "\n";
+ result += "\nThe ADML process can easily configure a many realm nodes as needed, which will have own endpoints.";
+ result += "\nYou should avoid loop configurations (client and server for that client) because automatic forwarding,";
+ result += "\n is implemented and this would get in a never ending cycle when a request is sent.";
+ result += "\n";
result += "\nProcess traces are dump on \"launcher.trace\" and could have any trace level (POSIX levels), usually";
result += "\n 'debug' or 'warning'. See ANNA documentation for more details.";
result += "\n";
result += "\n posibilities, many of which could be modified on the air through the management interface";
result += "\n (we will talk later about this great feature). Some of the more common parameters are:";
result += "\n";
- result += "\nAs mandatory, the stacks enabled given through the application-id and the xml dictionary:";
+ result += "\nAs mandatory, the stacks enabled given through the applicationId and the xml dictionary:";
result += "\n --stacks <appid1,dictionary1#appid2,dictionary2#...#appidN,dictionaryN>";
result += "\n";
result += "\nActing as a diameter server (accepting i.e. 10 connections), you would have:";
result += "\nDYNAMIC OPERATIONS";
result += "\n------------------";
result += "\n";
- result += "\nADL supports several operations which could be reconized via HTTP interface or SIGUSR2 caugh.";
+ result += "\nADML supports several operations which could be reconized via HTTP interface or SIGUSR2 caugh.";
result += "\nAn operation is specified by mean a string containing the operation name and needed arguments";
result += "\n separated by pipes. These are the available commands:";
result += "\n";
result += "\n";
result += "\nhelp This help. Startup information-level traces also dump this help.";
result += "\n";
- result += "\n--------------------------------------------------------------------------------------- Stack selection";
+ result += "\n---------------------------------------------------------------------------------------- Node selection";
result += "\n";
- result += "\nstack|<id> Select current working stack id (node selection). Many operations";
- result += " could use this value if proceed, in multistack configurations.";
+ result += "\nnode[|<name>] Select current working node by mean the registered name.";
+ result += "\n All the subsequent operations will be referred to this node.";
+ result += "\n Without argument, the current node is dumped on stdout.";
result += "\n";
result += "\n------------------------------------------------------------------------------------ Parsing operations";
result += "\n";
result += "\n";
result += "\ndiameterServerSessions|<integer> Updates the maximum number of accepted connections to diameter";
result += "\n server socket.";
- result += "\ncontext|[target file] Application context could also be written by mean this operation,";
+ result += "\ncontext[|target file] Application context could also be written by mean this operation,";
result += "\n and not only through SIGUSR1. If optional path file is missing,";
result += "\n default '/var/tmp/anna.context.<pid>' will be used.";
result += "\ncollect Reset statistics and counters to start a new test stage of";
result += "\n or sending operation 'context|[target file]'.";
result += "\nforceCountersRecord Forces dump to file the current counters of the process.";
result += "\n";
- result += "\n<visibility action>|[<address>:<port>]|[socket id]";
+ result += "\n<visibility action>[|<address>:<port>][|socket id]";
result += "\n";
result += "\n Actions: hide, show (update state) and hidden, shown (query state).";
result += "\n Acts over a client session for messages delivery (except CER/A, DWR/A, DPR/A).";
result += "\nsendxml2e|<source_file> Sends xml source file (pathfile) through configured entity.";
result += "\nsendxml2c|<source_file> Sends xml source file (pathfile) to client.";
result += "\nsendxml|<source_file> Same as 'sendxml2e'.";
- result += "\nanswerxml2e|[source_file] Answer xml source file (pathfile) for incoming request with same code from entity.";
+ result += "\nanswerxml2e[|source_file] Answer xml source file (pathfile) for incoming request with same code from entity.";
result += "\n The answer is stored in a FIFO queue for a specific message code, then there are";
result += "\n as many queues as different message codes have been programmed.";
- result += "\nanswerxml2c|[source_file] Answer xml source file (pathfile) for incoming request with same code from client.";
+ result += "\nanswerxml2c[|source_file] Answer xml source file (pathfile) for incoming request with same code from client.";
result += "\n The answer is stored in a FIFO queue for a specific message code, then there are";
result += "\n as many queues as different message codes have been programmed.";
- result += "\nanswerxml|[source_file] Same as 'answerxml2c'.";
+ result += "\nanswerxml[|source_file] Same as 'answerxml2c'.";
result += "\nanswerxml(2e/2c) List programmed answers (to entity/client) if no parameter provided.";
result += "\nanswerxml(2e/2c)|dump Write programmed answers (to entity/client) to file 'programmed_answer.<message code>.<sequence>',";
result += "\n where 'sequence' is the order of the answer in each FIFO code-queue of programmed answers.";
result += "\n";
result += "\n-------------------------------------------------------------------------------------------- Load tests";
result += "\n";
- result += "\nburst|<action>|[parameter] Used for performance testing, we first program diameter requests";
+ result += "\nburst|<action>[|parameter] Used for performance testing, we first program diameter requests";
result += "\n messages in order to launch them from client side to the configured";
result += "\n diameter entity. We could start the burst with an initial load";
result += "\n (non-asynchronous sending), after this, a new request will be sent";
result += "\n line parameter) shows popped messages with crosses (x). Each cross";
result += "\n represents one received answer for which no new request is sent.";
result += "\n burst|stop Stops the burst cycle. You can resume pushing 1 load amount.";
- result += "\n burst|repeat|[[yes]|no] Restarts the burst launch when finish. If initial load or push load";
+ result += "\n burst|repeat[|[yes]|no] Restarts the burst launch when finish. If initial load or push load";
result += "\n amount is greater than burst list size, they will be limited when";
result += "\n the list is processed except when repeat mode is enabled.";
result += "\n burst|send|<amount> Sends messages from burst list. The main difference with start/push";
response_content = "Operation processed with exception. See traces\n"; // supposed
std::string result = "";
anna::DataBlock db_aux(true);
- anna::diameter::codec::Message codecMsg(getCodecEngine()); // XXXXXXXXXXXXXX el del nodo de trabajo
+ anna::diameter::codec::Message codecMsg(getCodecEngine());
+ MyDiameterEntity *entity = getWorkingNode()->getEntity();
+ MyDiameterEngine *commEngine = getWorkingNode()->getMyDiameterEngine();
+ MyLocalServer *localServer = getWorkingNode()->getDiameterServer();
///////////////////////////////////////////////////////////////////
// Simple operations without arguments:
// Check the number of parameters:
bool wrongBody = false;
+ if((opType == "node") && (numParams > 1)) wrongBody = true;
+
if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true;
if(((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true;
return;
}
+ // Realm switch:
+ if(opType == "node") {
+ if (param1 != "") {
+ if (setWorkingNode(param1)) response_content = anna::functions::asString("Current node is now '%s'\n", param1.c_str());
+ }
+ else {
+ std::cout << getWorkingNode()->asXMLString() << std::endl;
+ }
+ return;
+ }
+
if(opType == "code") {
codecMsg.loadXML(param1);
std::string hexString = anna::functions::asHexString(codecMsg.code());
outfile.write(xmlString.c_str(), xmlString.size());
outfile.close();
} else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
- MyDiameterEntity *entity = getEntity();
-
if(!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION);
if(param1 != "") {
key += "|";
key += param2;
- if(opType == "hide") getMyDiameterEngine()->findClientSession(key)->hide();
+ if(opType == "hide") commEngine->findClientSession(key)->hide();
- if(opType == "show") getMyDiameterEngine()->findClientSession(key)->show();
+ if(opType == "show") commEngine->findClientSession(key)->show();
- if(opType == "hidden") result = getMyDiameterEngine()->findClientSession(key)->hidden() ? "true" : "false";
+ if(opType == "hidden") result = commEngine->findClientSession(key)->hidden() ? "true" : "false";
- if(opType == "shown") result = getMyDiameterEngine()->findClientSession(key)->shown() ? "true" : "false";
+ if(opType == "shown") result = commEngine->findClientSession(key)->shown() ? "true" : "false";
} else {
std::string address;
int port;
anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port);
- if(opType == "hide") getMyDiameterEngine()->findServer(address, port)->hide();
+ if(opType == "hide") commEngine->findServer(address, port)->hide();
- if(opType == "show") getMyDiameterEngine()->findServer(address, port)->show();
+ if(opType == "show") commEngine->findServer(address, port)->show();
- if(opType == "hidden") result = getMyDiameterEngine()->findServer(address, port)->hidden() ? "true" : "false";
+ if(opType == "hidden") result = commEngine->findServer(address, port)->hidden() ? "true" : "false";
- if(opType == "shown") result = getMyDiameterEngine()->findServer(address, port)->shown() ? "true" : "false";
+ if(opType == "shown") result = commEngine->findServer(address, port)->shown() ? "true" : "false";
}
} else {
if(opType == "hide") entity->hide();
if(opType == "shown") result = entity->shown() ? "true" : "false";
}
} else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
- MyDiameterEntity *entity = getEntity();
-
if(!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
- anna::diameter::comm::Message *msg = createCommMessage();
- //msg->setRetries(4);
- //msg->setOnExpiry(anna::diameter::comm::Message::OnExpiry::Retransmit);
+ anna::diameter::comm::Message *msg = getWorkingNode()->createCommMessage();
if((opType == "sendxml") || (opType == "sendxml2e")) {
codecMsg.loadXML(param1);
}
bool success = entity->send(msg, cl.exists("balance"));
- releaseCommMessage(msg);
+ getWorkingNode()->releaseCommMessage(msg);
// Detailed log:
- if(logEnabled()) {
+ if(getWorkingNode()->logEnabled()) {
anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
- writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail);
+ getWorkingNode()->writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail);
}
} else if((opType == "burst")) {
- anna::diameter::comm::Entity *entity = getEntity();
-
if(!entity) throw anna::RuntimeException("No entity configured to use burst feature", ANNA_FILE_LOCATION);
// burst|clear clears all loaded burst messages.
if(param1 == "clear") {
result = "Removed ";
- result += anna::functions::asString(clearBurst());
+ result += anna::functions::asString(getWorkingNode()->clearBurst());
result += " elements.";
} else if(param1 == "load") {
if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION);
if(codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION);
try { codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); } // at least we need to see validation errors although it will continue loading (see validation mode configured in launcher)
- int position = loadBurstMessage(codecMsg.code());
+ int position = getWorkingNode()->loadBurstMessage(codecMsg.code());
result = "Loaded '";
result += param2;
result += "' file into burst list position ";
if(param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION);
int initialLoad = atoi(param2.c_str());
- int processed = startBurst(initialLoad);
+ int processed = getWorkingNode()->startBurst(initialLoad);
if(processed > 0) {
result = "Initial load completed for ";
} else if(param1 == "push") {
if(param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION);
- int pushed = pushBurst(atoi(param2.c_str()));
+ int pushed = getWorkingNode()->pushBurst(atoi(param2.c_str()));
if(pushed > 0) {
result = "Pushed ";
if(param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION);
int releaseLoad = atoi(param2.c_str());
- int popped = popBurst(releaseLoad);
+ int popped = getWorkingNode()->popBurst(releaseLoad);
if(popped > 0) {
result = "Burst popped for ";
result += ".";
}
} else if(param1 == "stop") {
- int left = stopBurst();
+ int left = getWorkingNode()->stopBurst();
if(left != -1) {
result += anna::functions::entriesAsString(left, "message");
if(param2 == "") param2 = "yes";
bool repeat = (param2 == "yes");
- repeatBurst(repeat);
+ getWorkingNode()->repeatBurst(repeat);
result += (repeat ? "Mode on." : "Mode off.");
} else if(param1 == "send") {
if(param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION);
- int sent = sendBurst(atoi(param2.c_str()));
+ int sent = getWorkingNode()->sendBurst(atoi(param2.c_str()));
if(sent > 0) {
result = "Sent ";
} else if(param1 == "goto") {
if(param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION);
- result = gotoBurst(atoi(param2.c_str()));
+ result = getWorkingNode()->gotoBurst(atoi(param2.c_str()));
result += ".";
} else if(param1 == "look") {
if(param2 == "") throw anna::RuntimeException("Missing order position for burst look operation", ANNA_FILE_LOCATION);
result = "\n\n";
- result += lookBurst(atoi(param2.c_str()));
+ result += getWorkingNode()->lookBurst(atoi(param2.c_str()));
result += "\n\n";
} else {
throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION);
}
} else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
- MyLocalServer *localServer = getDiameterLocalServer();
-
if(!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION);
- anna::diameter::comm::Message *msg = createCommMessage();
+ anna::diameter::comm::Message *msg = getWorkingNode()->createCommMessage();
if(opType == "sendxml2c") {
codecMsg.loadXML(param1);
}
bool success = localServer->send(msg);
- releaseCommMessage(msg);
+ getWorkingNode()->releaseCommMessage(msg);
// Detailed log:
- if(logEnabled()) {
+ if(getWorkingNode()->logEnabled()) {
anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
- writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail);
+ getWorkingNode()->writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail);
}
} else if(opType == "loadxml") {
codecMsg.loadXML(param1);
} else if(opType == "diameterServerSessions") {
int diameterServerSessions = atoi(param1.c_str());
- if(!getDiameterLocalServer())
- startDiameterServer(diameterServerSessions);
+ if(localServer)
+ localServer->setMaxConnections(diameterServerSessions);
else
- getDiameterLocalServer()->setMaxConnections(diameterServerSessions);
- } else if((opType == "answerxml") || (opType == "answerxml2c")) {
- MyLocalServer *localServer = getDiameterLocalServer();
+ LOGWARNING(anna::Logger::warning("To update the number of sessions, you must configure the process diameter local server: you could also launch it with no sessions (disabled)", ANNA_FILE_LOCATION));
+ } else if((opType == "answerxml") || (opType == "answerxml2c")) {
if(!localServer)
throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION);
localServer->getReactingAnswers()->addMessage(code, message);
}
} else if(opType == "answerxml2e") {
- MyDiameterEntity *entity = getEntity();
-
if(!entity)
throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION);
}
}
-int MyDiameterEntity::readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw() {
- CommandLine& cl(anna::CommandLine::instantiate());
- std::string sessionBasedModelsType = (cl.exists("sessionBasedModelsClientSocketSelection") ? cl.getValue("sessionBasedModelsClientSocketSelection") : "SessionIdLowPart");
-
- if(sessionBasedModelsType == "RoundRobin") return -1; // IEC also would return -1
-
- try {
- // Service-Context-Id:
- anna::diameter::helpers::dcca::ChargingContext::_v chargingContext;
- std::string scid = anna::diameter::helpers::dcca::functions::getServiceContextId(message->getBody(), chargingContext);
-
- switch(chargingContext) {
- case anna::diameter::helpers::dcca::ChargingContext::Data:
- case anna::diameter::helpers::dcca::ChargingContext::Voice:
- case anna::diameter::helpers::dcca::ChargingContext::Content: {
- // Session-Id: '<DiameterIdentity>;<high 32 bits>;<low 32 bits>[;<optional value>="">]'
- std::string sid = anna::diameter::helpers::base::functions::getSessionId(message->getBody());
- std::string diameterIdentity, optional;
- anna::U32 high, low;
- anna::diameter::helpers::base::functions::decodeSessionId(sid, diameterIdentity, high, low /* context-teid */, optional);
-
- if(sessionBasedModelsType == "SessionIdLowPart") return (low % maxClientSessions);
-
- if(sessionBasedModelsType == "SessionIdHighPart") return (high % maxClientSessions);
-
- if(sessionBasedModelsType == "SessionIdOptionalPart") return (atoi(optional.c_str()) % maxClientSessions);
- }
-
- case anna::diameter::helpers::dcca::ChargingContext::SMS:
- case anna::diameter::helpers::dcca::ChargingContext::MMS:
- case anna::diameter::helpers::dcca::ChargingContext::Unknown:
- default:
- return -1;
- }
- } catch(anna::RuntimeException &ex) {
- LOGDEBUG(
- std::string msg = ex.getText();
- msg += " | Round-robin between sessions will be used to send";
- anna::Logger::debug(msg, ANNA_FILE_LOCATION);
- );
- }
-
- return -1;
-}
-
anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const
throw() {
anna::xml::Node* result = parent->createChild("launcher");
result->createAttribute("StartTime", a_start_time.asString());
result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
// Diameter:
- getCodecEngine()->asXML(result); // XXXXXXXXXXXXXXX todos los nodos ...
+ getCodecEngine()->asXML(result);
+ for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) {
+ it->second->asXML(result);
+ }
+
// OAM:
anna::diameter::comm::OamModule::instantiate().asXML(result);
anna::diameter::comm::ApplicationMessageOamModule::instantiate().asXML(result);
anna::statistics::Engine::instantiate().asXML(result);
return result;
}
-
#define example_diameter_launcher_Launcher_hpp
// Standard
+#include <fstream>
#include <string>
#include <map>
-#include <fstream>
// Project
#include <anna/core/core.hpp>
#include <anna/comm/comm.hpp>
-#include <anna/diameter.comm/Entity.hpp>
#include <anna/time/Date.hpp>
-#include <anna/timex/Engine.hpp>
+
+// Process
+#include "MyCommunicator.hpp"
+#include "MyCounterRecorder.hpp"
+
namespace anna {
+ namespace timex {
+ class Engine;
+ }
namespace diameter {
- namespace comm {
- //class Entity;
- //class Response;
- class LocalServer;
+ namespace codec {
+ class Engine;
}
}
}
-// Process
-#include "MyCommunicator.hpp"
-#include "MyCounterRecorder.hpp"
-#include "MyDiameterEngine.hpp"
+// RealmNode resources
+class RealmNode;
+typedef std::map<std::string, RealmNode*> realm_nodes_t;
+typedef std::map<std::string, RealmNode*>::const_iterator realm_nodes_it;
+typedef std::map<std::string, RealmNode*>::iterator realm_nodes_nc_it;
class Launcher : public anna::comm::Application {
+ // Start time:
+ anna::time::Date a_start_time;
+
+ // Core engines:
MyCommunicator *a_communicator;
- MyDiameterEngine *a_myDiameterEngine;
- MyDiameterEntity *a_entity;
anna::diameter::codec::Engine *a_codecEngine;
- std::string a_logFile, a_burstLogFile;
- std::ofstream a_burstLogStream;
- bool a_splitLog, a_detailedLog, a_dumpLog;
- anna::time::Date a_start_time;
anna::timex::Engine* a_timeEngine;
MyCounterRecorder *a_counterRecorder;
MyCounterRecorderClock *a_counterRecorderClock;
- std::string a_cerPathfile; // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
- std::string a_dwrPathfile; // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
- std::string a_workingNode; // this is the node name (usually equals to the Origin-Realm value
-
- // Burst feature
- int a_burstCycle;
- bool a_burstRepeat;
- bool a_burstActive;
- std::map < int /* dummy, p.e. used for order number */, anna::diameter::comm::Message* > a_burstMessages; // XXXXXXXXXXXXXXXXXXXXX
- int a_burstLoadIndx;
- std::map<int, anna::diameter::comm::Message*>::const_iterator a_burstDeliveryIt;
- int a_otaRequest;
- int a_burstPopCounter;
-
- // comm Messages factory:
- anna::Recycler<anna::diameter::comm::Message> a_commMessages;
+ // Nodes deployment:
+ realm_nodes_t a_nodes;
+ RealmNode *a_workingNode;
+
+ // comm resources:
anna::comm::ServerSocket* a_httpServerSocket; // HTTP
- MyLocalServer* a_diameterLocalServer; // DIAMETER XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
- void checkTimeMeasure(const char * commandLineParameter, bool optional = true) throw(anna::RuntimeException);
+
+
+ void servicesFromXML(const anna::xml::Node* servicesNode) throw(anna::RuntimeException);
+ anna::Millisecond checkTimeMeasure(const std::string ¶meter, const std::string &value) throw(anna::RuntimeException);
void initialize() throw(anna::RuntimeException); // HTTP
void run() throw(anna::RuntimeException);
+
public:
Launcher();
+ void loadServices(const std::string & xmlPathFile) throw(anna::RuntimeException);
+ void startServices() throw(anna::RuntimeException);
+
anna::diameter::codec::Engine *getCodecEngine() const throw() { return a_codecEngine; }
- std::string getWorkingNode() const throw() { return a_workingNode; }
- void setWorkingNode(const std::string &node) throw() { a_workingNode = node; }
+ RealmNode *getWorkingNode() const throw() { return a_workingNode; } // management operations working node
+ bool setWorkingNode(const std::string &name) throw(); // we could update ignoreFlagsOnValidation/integrationAndDebugging over the global codec engine
+ // but finally, that configuration issues will be global to the process.
+
+ RealmNode *getRealmNode(const std::string &realmName) const throw();
+
+
MyCommunicator *getCommunicator() throw() { return a_communicator; }
- MyDiameterEngine* getMyDiameterEngine() const throw() { return (a_myDiameterEngine); }
- void baseProtocolSetupAsClient(void) throw(anna::RuntimeException);
- MyDiameterEntity *getEntity() throw() { return a_entity; } // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
- MyLocalServer* getDiameterLocalServer() throw() { return a_diameterLocalServer; } // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
void eventOperation(const std::string &, std::string &) throw(anna::RuntimeException);
- bool logEnabled() const throw() { return (((a_logFile == "") || (a_logFile == "null")) ? false : true); }
- void writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw(); // XXXXXXXXXXXXXXXXXXXXX
- void writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw(); // XXXXXXXXXXXXXXXXXX
- void writeBurstLogFile(const std::string &buffer) throw();
- bool burstLogEnabled() const throw() { return (((a_burstLogFile == "") || (a_burstLogFile == "null")) ? false : true); }
- void startDiameterServer(int) throw(anna::RuntimeException); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
void forceCountersRecord() throw(anna::RuntimeException) { if (a_counterRecorderClock) a_counterRecorderClock->tick(); }
- anna::xml::Node* asXML(anna::xml::Node* parent) const throw(); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
- void resetStatistics() throw() { a_myDiameterEngine->resetStatistics(); }
+ anna::xml::Node* asXML(anna::xml::Node* parent) const throw();
+ void resetStatistics() throw();
void resetCounters() throw();
void signalUSR2() throw(anna::RuntimeException);
std::string help() const throw();
- // Messages factory:
- anna::diameter::comm::Message *createCommMessage() throw(anna::RuntimeException);
- void releaseCommMessage(anna::diameter::comm::Message*) throw();
-
// helpers
bool getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw();
-
- // Burst feature
- int clearBurst() throw(); // returns removed
- int loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException);
- void repeatBurst(bool repeat) throw() { a_burstRepeat = repeat; }
- int startBurst(int initialLoad) throw(); // return processed on start, or -1 if burst list is empty, -2 if invalid initial load (0 or negative)
- int pushBurst(int loadAmount) throw(); // returns pushed (perhaps is less than provided because of no repeat mode and burst list exhausted), or -1 if burst list is empty, -2 if invalid load (0 or negative)
- int sendBurst(int loadAmount) throw(); // returns sent (burst always cycled using send), returns -1 if burst list is empty, -2 if invalid load (0 or negative)
- int popBurst(int releaseAmount) throw(); // returns popped (perhaps is less than provided because of OTA request), or -1 if burst stopped
- int stopBurst() throw(); // returns remaining on cycle, or -1 if burst already stopped
- bool burstActive() const throw() { return a_burstActive; }
- bool sendBurstMessage(bool anyway = false) throw();
- std::string lookBurst(int order) const throw();
- std::string gotoBurst(int order) throw();
};
#endif
#include <anna/diameter/functions.hpp>
#include <anna/time/functions.hpp>
#include <anna/diameter.comm/Response.hpp>
+#include <anna/diameter.comm/ClientSession.hpp>
#include <anna/diameter/helpers/base/functions.hpp>
#include <anna/diameter/helpers/dcca/functions.hpp>
// Process
+#include "MyDiameterEngine.hpp"
#include "MyDiameterEntity.hpp"
+#include "MyLocalServer.hpp"
#include "Launcher.hpp"
+#include "RealmNode.hpp"
void MyDiameterEntity::eventRequestRetransmission(const anna::diameter::comm::ClientSession* clientSession, anna::diameter::comm::Message *request) throw() {
// Performance stats:
Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
- CommandLine& cl(anna::CommandLine::instantiate());
+ RealmNode * my_node = my_app.getRealmNode(getEngine()->getRealm());
// CommandId:
anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(request->getBody());
LOGDEBUG
);
// Write retransmission
- if(my_app.logEnabled()) my_app.writeLogFile(request->getBody(), "retry", clientSession->asString(), a_codecEngine);
+ if(my_node->logEnabled()) my_node->writeLogFile(request->getBody(), "retry", clientSession->asString());
}
int MyDiameterEntity::readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw() {
- CommandLine& cl(anna::CommandLine::instantiate());
- std::string sessionBasedModelsType = (cl.exists("sessionBasedModelsClientSocketSelection") ? cl.getValue("sessionBasedModelsClientSocketSelection") : "SessionIdLowPart");
- if(sessionBasedModelsType == "RoundRobin") return -1; // IEC also would return -1
+ if(a_sessionBasedModelsType == "RoundRobin") return -1; // IEC also would return -1
try {
// Service-Context-Id:
anna::U32 high, low;
anna::diameter::helpers::base::functions::decodeSessionId(sid, diameterIdentity, high, low /* context-teid */, optional);
- if(sessionBasedModelsType == "SessionIdLowPart") return (low % maxClientSessions);
+ if(a_sessionBasedModelsType == "SessionIdLowPart") return (low % maxClientSessions);
- if(sessionBasedModelsType == "SessionIdHighPart") return (high % maxClientSessions);
+ if(a_sessionBasedModelsType == "SessionIdHighPart") return (high % maxClientSessions);
- if(sessionBasedModelsType == "SessionIdOptionalPart") return (atoi(optional.c_str()) % maxClientSessions);
+ if(a_sessionBasedModelsType == "SessionIdOptionalPart") return (atoi(optional.c_str()) % maxClientSessions);
}
case anna::diameter::helpers::dcca::ChargingContext::SMS:
case anna::diameter::helpers::dcca::ChargingContext::MMS:
LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventRequest", ANNA_FILE_LOCATION));
// Performance stats:
Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
- CommandLine& cl(anna::CommandLine::instantiate());
+ RealmNode * my_node = my_app.getRealmNode(getEngine()->getRealm());
// CommandId:
anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
LOGDEBUG
);
// Write reception
- if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString(), a_codecEngine);
+ if(my_node->logEnabled()) my_node->writeLogFile(message, "recvfe", clientSession->asString());
// Lookup reacting answers list:
int code = cid.first;
my_app.getCommunicator()->prepareAnswer(answer_message, message);
try {
- anna::diameter::comm::Message *msg = my_app.createCommMessage();
+ anna::diameter::comm::Message *msg = my_node->createCommMessage();
msg->setBody(answer_message->code());
/* response = NULL =*/clientSession->send(msg);
- my_app.releaseCommMessage(msg);
+ my_node->releaseCommMessage(msg);
- if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2e", clientSession->asString());
+ if(my_node->logEnabled()) my_node->writeLogFile(*answer_message, "sent2e", clientSession->asString());
} catch(anna::RuntimeException &ex) {
ex.trace();
- if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2eError", clientSession->asString());
+ if(my_node->logEnabled()) my_node->writeLogFile(*answer_message, "send2eError", clientSession->asString());
}
// Pop front the reacting answer:
// not found: forward to client (if exists)
// Forward to client:
- anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
+ MyLocalServer *localServer = my_node->getDiameterServer();
if(localServer && (cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CER */) {
try {
- anna::diameter::comm::Message *msg = my_app.createCommMessage();
+ anna::diameter::comm::Message *msg = my_node->createCommMessage();
msg->forwardEndToEnd(); // end-to-end will be kept
msg->setBody(message);
msg->setRequestClientSessionKey(clientSession->getKey());
bool success = localServer->send(msg);
// Detailed log:
- if(my_app.logEnabled()) {
+ if(my_node->logEnabled()) {
anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
- my_app.writeLogFile(message, (success ? "fwd2c" : "fwd2cError"), detail, a_codecEngine);
+ my_node->writeLogFile(message, (success ? "fwd2c" : "fwd2cError"), detail);
}
} catch(anna::RuntimeException &ex) {
ex.trace();
throw(anna::RuntimeException) {
LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventResponse", ANNA_FILE_LOCATION));
Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
- CommandLine& cl(anna::CommandLine::instantiate());
+ RealmNode * my_node = my_app.getRealmNode(getEngine()->getRealm());
anna::diameter::comm::ClassCode::_v code = response.getClassCode();
anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode();
anna::diameter::comm::Message* request = const_cast<anna::diameter::comm::Message*>(response.getRequest());
LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the entity", ANNA_FILE_LOCATION));
if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA
- if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2e-expired", clientSession->asString(), a_codecEngine);
+ if(my_node->logEnabled()) my_node->writeLogFile(*request, "req2e-expired", clientSession->asString());
}
}
// Write reception
if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA
- if(my_app.logEnabled()) {
- my_app.writeLogFile(*message, "recvfe", clientSession->asString(), a_codecEngine);
+ if(my_node->logEnabled()) {
+ my_node->writeLogFile(*message, "recvfe", clientSession->asString());
}
}
// Forward to client:
- anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
+ MyLocalServer *localServer = my_node->getDiameterServer();
if(localServer && (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CEA */) {
try {
- anna::diameter::comm::Message *msg = my_app.createCommMessage();
+ anna::diameter::comm::Message *msg = my_node->createCommMessage();
msg->forwardEndToEnd(); // end-to-end will be kept
msg->setBody(*message);
bool success = localServer->send(msg, request->getRequestServerSessionKey());
- my_app.releaseCommMessage(msg);
- my_app.releaseCommMessage(request);
+ my_node->releaseCommMessage(msg);
+ my_node->releaseCommMessage(request);
// Detailed log:
- anna::diameter::comm::ServerSession *usedServerSession = my_app.getMyDiameterEngine()->findServerSession(request->getRequestServerSessionKey());
+ anna::diameter::comm::ServerSession *usedServerSession = my_node->getMyDiameterEngine()->findServerSession(request->getRequestServerSessionKey());
std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
- if(my_app.logEnabled()) {
- my_app.writeLogFile(*message, (success ? "fwd2c" : "fwd2cError"), detail, a_codecEngine);
+ if(my_node->logEnabled()) {
+ my_node->writeLogFile(*message, (success ? "fwd2c" : "fwd2cError"), detail);
}
} catch(anna::RuntimeException &ex) {
ex.trace();
}
// Triggering burst:
- if(isOK || contextExpired) my_app.sendBurstMessage();
+ if(isOK || contextExpired) my_node->sendBurstMessage();
}
void MyDiameterEntity::eventUnknownResponse(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message)
LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventUnknownResponse", ANNA_FILE_LOCATION));
// Performance stats:
Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
+ RealmNode * my_node = my_app.getRealmNode(getEngine()->getRealm());
// CommandId:
anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
LOGDEBUG
);
// Write reception
- if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe-ans-unknown", clientSession->asString(), a_codecEngine);
+ if(my_node->logEnabled()) my_node->writeLogFile(message, "recvfe-ans-unknown", clientSession->asString());
}
void MyDiameterEntity::eventDPA(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message)
LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventDPA", ANNA_FILE_LOCATION));
// Performance stats:
Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
+ RealmNode * my_node = my_app.getRealmNode(getEngine()->getRealm());
// CommandId:
anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
LOGDEBUG
);
// Write reception
- if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString(), a_codecEngine);
+ if(my_node->logEnabled()) my_node->writeLogFile(message, "recvfe", clientSession->asString());
}
class MyDiameterEntity : public anna::diameter::comm::Entity {
anna::diameter::codec::Engine * a_codecEngine; // for automatic answers (failed-avp), write logs, etc.
+ bool a_balance; // Balance over entity servers instead of doing standard behaviour (first primary, secondary if fails, etc.). Default: false.
+ std::string a_sessionBasedModelsType;
void eventRequestRetransmission(const anna::diameter::comm::ClientSession *, anna::diameter::comm::Message*) throw();
void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException);
public:
+ MyDiameterEntity() {
+ a_codecEngine = NULL;
+ a_balance = false;
+ a_sessionBasedModelsType = "SessionIdLowPart";
+ }
+
ProgrammedAnswers a_reactingAnswers;
void setCodecEngine(anna::diameter::codec::Engine *codecEngine) throw() { a_codecEngine = codecEngine; a_reactingAnswers.setCodecEngine(codecEngine); }
ProgrammedAnswers *getReactingAnswers() throw() { return (ProgrammedAnswers *)&a_reactingAnswers; }
+
+ // Additional configuration parameters:
+ void setSessionBasedModelsType(const std::string &type) throw() { a_sessionBasedModelsType = type; }
+ void setBalance(bool balance) throw() { a_balance = balance; }
+ const std::string & getSessionBasedModelsType() const throw() { return a_sessionBasedModelsType; }
+ bool getBalance() const throw() { return a_balance; }
};
#endif
#include <anna/time/functions.hpp>
#include <anna/diameter/codec/Engine.hpp>
#include <anna/diameter.comm/Response.hpp>
+#include <anna/diameter.comm/ClientSession.hpp>
+#include <anna/diameter.comm/Server.hpp>
// Process
#include "MyLocalServer.hpp"
+#include "MyDiameterEngine.hpp"
+#include "MyDiameterEntity.hpp"
#include "Launcher.hpp"
+#include "RealmNode.hpp"
void MyLocalServer::eventRequest(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventRequest", ANNA_FILE_LOCATION));
// Performance stats:
Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
- CommandLine& cl(anna::CommandLine::instantiate());
+ RealmNode * my_node = my_app.getRealmNode(getEngine()->getRealm());
+
// CommandId:
anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
LOGDEBUG
);
// Write reception
- if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString(), a_codecEngine);
+ if(my_node->logEnabled()) my_node->writeLogFile(message, "recvfc", serverSession->asString());
// If no answer is programmed and entity is configured, the failed request would be forwarded even being wrong (delegates at the end point)
int code = cid.first;
anna::diameter::codec::Message *programmed_answer = a_reactingAnswers.getMessage(code);
bool programmed = (programmed_answer != NULL);
- anna::diameter::comm::Entity *entity = my_app.getEntity();
+ anna::diameter::comm::Entity *entity = my_node->getEntity();
if(!programmed && entity) { // forward condition (no programmed answer + entity available)
- anna::diameter::comm::Message *msg = my_app.createCommMessage();
+ anna::diameter::comm::Message *msg = my_node->createCommMessage();
msg->forwardEndToEnd(); // end-to-end will be kept
msg->setBody(message);
msg->setRequestServerSessionKey(serverSession->getKey());
- bool success = entity->send(msg, cl.exists("balance"));
+ bool success = entity->send(msg, my_node->getEntity()->getBalance());
// Detailed log:
- if(my_app.logEnabled()) {
+ if(my_node->logEnabled()) {
anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
- my_app.writeLogFile(message, (success ? "fwd2e" : "fwd2eError"), detail, a_codecEngine); // forwarded
+ my_node->writeLogFile(message, (success ? "fwd2e" : "fwd2eError"), detail); // forwarded
}
return;
anna::diameter::codec::Message codecMsg(a_codecEngine);
anna::diameter::codec::Message codecAnsMsg(a_codecEngine);
+ CommandLine& cl(anna::CommandLine::instantiate());
if(!cl.exists("ignoreErrors")) { // Error analysis
answer_message = (anna::diameter::codec::Message *)&codecAnsMsg;
answer_message->clear();
// Decode
try { codecMsg.decode(message, answer_message); } catch(anna::RuntimeException &ex) { ex.trace(); }
- answer_message->setStandardToAnswer(codecMsg, my_app.getMyDiameterEngine()->getHost(), my_app.getMyDiameterEngine()->getRealm());
+ answer_message->setStandardToAnswer(codecMsg, my_node->getMyDiameterEngine()->getHost(), my_node->getMyDiameterEngine()->getRealm());
analysisOK = (answer_message->getResultCode() == anna::diameter::helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS);
}
a_codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Never);
try {
- anna::diameter::comm::Message *msg = my_app.createCommMessage();
+ anna::diameter::comm::Message *msg = my_node->createCommMessage();
msg->setBody(answer_message->code());
/* response = NULL =*/serverSession->send(msg);
- my_app.releaseCommMessage(msg);
+ my_node->releaseCommMessage(msg);
- if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2c", serverSession->asString());
+ if(my_node->logEnabled()) my_node->writeLogFile(*answer_message, "sent2c", serverSession->asString());
} catch(anna::RuntimeException &ex) {
ex.trace();
- if(my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2cError", serverSession->asString());
+ if(my_node->logEnabled()) my_node->writeLogFile(*answer_message, "send2cError", serverSession->asString());
}
// Restore validation mode
throw(anna::RuntimeException) {
LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventResponse", ANNA_FILE_LOCATION));
Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
- CommandLine& cl(anna::CommandLine::instantiate());
+ RealmNode * my_node = my_app.getRealmNode(getEngine()->getRealm());
anna::diameter::comm::ClassCode::_v code = response.getClassCode();
anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode();
anna::diameter::comm::Message* request = const_cast<anna::diameter::comm::Message*>(response.getRequest());
LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the client", ANNA_FILE_LOCATION));
if(request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA
- if(my_app.logEnabled()) my_app.writeLogFile(*request, "req2c-expired", serverSession->asString(), a_codecEngine);
+ if(my_node->logEnabled()) my_node->writeLogFile(*request, "req2c-expired", serverSession->asString());
}
}
);
// Write reception
- if(my_app.logEnabled()) my_app.writeLogFile(*message, "recvfc", serverSession->asString(), a_codecEngine);
+ if(my_node->logEnabled()) my_node->writeLogFile(*message, "recvfc", serverSession->asString());
// This is not very usual, but answers could arrive from clients:
- anna::diameter::comm::Entity *entity = my_app.getEntity();
+ anna::diameter::comm::Entity *entity = my_node->getEntity();
if(entity) {
- anna::diameter::comm::ClientSession *usedClientSession = my_app.getMyDiameterEngine()->findClientSession(request->getRequestClientSessionKey());
+ anna::diameter::comm::ClientSession *usedClientSession = my_node->getMyDiameterEngine()->findClientSession(request->getRequestClientSessionKey());
std::string detail;
- if(my_app.logEnabled()) detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // this should not happen
+ if(my_node->logEnabled()) detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // this should not happen
try {
- anna::diameter::comm::Message *msg = my_app.createCommMessage();
+ anna::diameter::comm::Message *msg = my_node->createCommMessage();
msg->forwardEndToEnd(); // end-to-end will be kept
msg->setBody(*message);
//msg->setRequestClientSessionKey(request->getRequestClientSessionKey());
//bool success = entity->send(msg);
- my_app.releaseCommMessage(msg);
- my_app.releaseCommMessage(request);
+ my_node->releaseCommMessage(msg);
+ my_node->releaseCommMessage(request);
- if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2e", detail, a_codecEngine); // forwarded
+ if(my_node->logEnabled()) my_node->writeLogFile(*message, "fwd2e", detail); // forwarded
} catch(anna::RuntimeException &ex) {
ex.trace();
- if(my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2eError", detail, a_codecEngine); // forwarded
+ if(my_node->logEnabled()) my_node->writeLogFile(*message, "fwd2eError", detail); // forwarded
}
}
}
LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventUnknownResponse", ANNA_FILE_LOCATION));
// Performance stats:
Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
+ RealmNode * my_node = my_app.getRealmNode(getEngine()->getRealm());
// CommandId:
anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
LOGDEBUG
anna::Logger::debug(msg, ANNA_FILE_LOCATION);
);
- if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc-ans-unknown", serverSession->asString(), a_codecEngine);
+ if(my_node->logEnabled()) my_node->writeLogFile(message, "recvfc-ans-unknown", serverSession->asString());
}
void MyLocalServer::eventDPA(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventDPA", ANNA_FILE_LOCATION));
// Performance stats:
Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
+ RealmNode * my_node = my_app.getRealmNode(getEngine()->getRealm());
// CommandId:
anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
LOGDEBUG
anna::Logger::debug(msg, ANNA_FILE_LOCATION);
);
- if(my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString(), a_codecEngine);
+ if(my_node->logEnabled()) my_node->writeLogFile(message, "recvfc", serverSession->asString());
}
+++ /dev/null
-// ANNA - Anna is Not Nothingness Anymore //
-// //
-// (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
-// //
-// See project site at http://redmine.teslayout.com/projects/anna-suite //
-// See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
-
-
-// Standard
-#include <string>
-
-// Project
-//#include <anna/diameter/codec/Engine.hpp>
-
-// Process
-#include "Node.hpp"
-
-
-void Node::clear () throw() {
- for (reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) {
- anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
- engine->releaseMessage(*(it->second->begin()));
- delete(it->second);
- }
- a_deques.clear();
-}
-
-void Node::dump () throw() {
- std::string outfilename, xmlString;
- for(reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) {
- int sequence = 1;
- for(codec_messages_deque_const_iterator itm = it->second->begin(); itm != it->second->end(); itm++) {
- // programmed_answer.<code>.<sequence>
- outfilename = "programmed_answer.";
- outfilename += anna::functions::asString(it->first);
- outfilename += ".";
- outfilename += anna::functions::asString(sequence++);
- outfilename += ".xml";
- std::ofstream outfile(outfilename.c_str(), std::ifstream::out);
- xmlString = (*itm)->asXMLString();
- outfile.write(xmlString.c_str(), xmlString.size());
- outfile.close();
- }
- }
-}
-
-void Node::addMessage(int code, anna::diameter::codec::Message *message) throw() {
- reacting_answers_const_iterator it = a_deques.find(code);
- if (it != a_deques.end()) {
- it->second->push_back(message);
- }
- else {
- codec_messages_deque *deque = new codec_messages_deque;
- a_deques[code] = deque;
- deque->push_back(message);
- }
-}
-
-anna::diameter::codec::Message* Node::getMessage(int code) const throw() { //get the front message (begin()), returns NULL if deque is empty
- anna::diameter::codec::Message *result = NULL;
- reacting_answers_const_iterator it = a_deques.find(code);
- if (it != a_deques.end()) {
- if (!it->second->empty()) result = *(it->second->begin());
- }
- return result;
-}
-
-void Node::nextMessage(int code) throw() { //pops the deque and release the message (when deque is not empty: deque::empty)
- reacting_answers_const_iterator it = a_deques.find(code);
- if (it != a_deques.end()) {
- if (!it->second->empty()) {
- anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
- if (a_rotate) {
- addMessage(code, *(it->second->begin()));
- }
- else {
- engine->releaseMessage(*(it->second->begin()));
- }
- it->second->pop_front();
- }
- }
-}
-
-std::string Node::asString(const char *queueName) const throw() {
- std::string result = "";
- std::string aux = "FIFO QUEUE '";
- aux += queueName;
- aux += "', Rotation ";
- aux += a_rotate ? "enabled":"disabled";
- result += anna::functions::highlightJustify(aux);
- if(a_deques.size() != 0) {
- for(reacting_answers_const_iterator it = a_deques.begin(); it != a_deques.end(); it++) {
- if (it->second->size() != 0) {
- aux = "Answer code ";
- aux += anna::functions::asString(it->first);
- result += anna::functions::highlightJustify(aux, anna::functions::TextHighlightMode::OverAndUnderline,
- anna::functions::TextJustifyMode::Left, '-');
- for(codec_messages_deque_const_iterator itm = it->second->begin(); itm != it->second->end(); itm++) {
- result += (*itm)->asXMLString();
- result += "\n";
- }
- result += "\n";
- }
- }
- }
- else {
- result = "No ocurrences found\n\n";
- }
- return result;
-}
+++ /dev/null
-// ANNA - Anna is Not Nothingness Anymore //
-// //
-// (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
-// //
-// See project site at http://redmine.teslayout.com/projects/anna-suite //
-// See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
-
-
-#ifndef example_diameter_launcher_Node_hpp
-#define example_diameter_launcher_Node_hpp
-
-// Standard
-#include <string>
-
-// Process
-#include "MyDiameterEntity.hpp"
-#include "MyLocalServer.hpp"
-
-
-class Node {
-
- std::string a_name;
- unsigned int a_applicationId;
- std::string a_cer; // path file
- std::string a_dwr; // path file
- MyDiameterEntity *a_entity;
- MyLocalServer *a_diameterServer;
- bool a_balance; // Balance over entity servers instead of doing standard behaviour (first primary, secondary if fails, etc.). Default: false.
- bool a_ignoreErrors; // default: false
-
-
-public:
- Node() { a_rotate = false; }
- ~Node() { clear(); }
-
-
- bool rotate() const throw() { return a_rotate; }
- void rotate(bool r) throw() { a_rotate = r; }
-
- void clear () throw();
- void dump () throw();
- void addMessage(int code, anna::diameter::codec::Message *message) throw();
- anna::diameter::codec::Message* getMessage(int code) const throw();
- void nextMessage(int code) throw();
- std::string asString(const char *queueName) const throw();
-};
-
-#endif
--- /dev/null
+// ANNA - Anna is Not Nothingness Anymore //
+// //
+// (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
+// //
+// See project site at http://redmine.teslayout.com/projects/anna-suite //
+// See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
+
+
+// Standard
+#include <string>
+
+// Project
+#include <anna/diameter.comm/Message.hpp>
+#include <anna/core/core.hpp>
+#include <anna/time/Date.hpp>
+#include <anna/xml/Compiler.hpp>
+
+// Process
+#include "RealmNode.hpp"
+#include "MyDiameterEngine.hpp"
+
+
+
+RealmNode::RealmNode(const std::string &originRealm, unsigned int applicationId, anna::diameter::codec::Engine *codecEngine) :
+ a_originRealm(originRealm), a_applicationId(applicationId), a_codecEngine(codecEngine) {
+
+ std::string commEngineName = a_originRealm + "_DiameterCommEngine";
+ a_commEngine = new MyDiameterEngine(commEngineName.c_str());
+ a_commEngine->setAutoBind(false); // allow to create client-sessions without binding them, in order to set timeouts.
+ a_commEngine->setBaseProtocolCodecEngine(getCodecEngine());
+
+ a_logFile = "";
+ a_burstLogFile = "";
+ a_splitLog = false;
+ a_detailedLog = false;
+ a_dumpLog = false;
+ a_entity = NULL;
+ a_diameterServer = NULL;
+
+ // Comm resources:
+ a_allowedInactivityTime = (anna::Millisecond)90000;
+ a_tcpConnectDelay = (anna::Millisecond)200;
+ a_answersTimeout = (anna::Millisecond)10000;
+ a_ceaTimeout = (anna::Millisecond)10000;
+ a_watchdogPeriod = (anna::Millisecond)30000;
+ a_requestRetransmissions = 0;
+
+ // Burst
+ a_burstCycle = 1;
+ a_burstRepeat = false;
+ a_burstActive = false;
+ a_burstLoadIndx = 0;
+ a_burstDeliveryIt = a_burstMessages.begin();
+ a_otaRequest = 0;
+ a_burstPopCounter = 0;
+}
+
+
+void RealmNode::createEntity(const std::string &entityRepresentation, const anna::Millisecond &bindTimeout, const anna::Millisecond &applicationTimeout) throw() {
+
+ anna::socket_v servers = anna::functions::getSocketVectorFromString(entityRepresentation);
+ std::string entityDescription = "Launcher diameter entity for "; entityDescription += a_originRealm;
+ a_entity = (MyDiameterEntity*)(a_commEngine->createEntity(servers, entityDescription));
+ a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::Bind, bindTimeout);
+ a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::ApplicationMessage, applicationTimeout);
+
+ // Codec engine for reacting answers (failed-avp):
+ a_entity->setCodecEngine(getCodecEngine());
+}
+
+void RealmNode::startDiameterServer(const std::string &serverRepresentation, int sessions, const anna::Millisecond &inactivityTimeout) throw(anna::RuntimeException) {
+
+ if(sessions <= 0) return;
+
+ std::string address; int port;
+ anna::functions::getAddressAndPortFromSocketLiteral(serverRepresentation, address, port);
+ std::string serverDescription = "Launcher diameter local server for "; serverDescription += a_originRealm;
+ a_diameterServer = (MyLocalServer*)(a_commEngine->createLocalServer(address, port, sessions));
+ // we could set sessions = 0, and after application run(), use setMaxConnections(real sessions)
+ // over the local server in order to start it.
+
+ a_diameterServer->setDescription(serverDescription);
+ a_diameterServer->setAllowedInactivityTime(inactivityTimeout);
+
+ // Codec engine for reacting answers (failed-avp):
+ a_diameterServer->setCodecEngine(getCodecEngine());
+}
+
+anna::diameter::comm::Message *RealmNode::createCommMessage() throw(anna::RuntimeException) {
+ anna::diameter::comm::Message *result = a_commMessages.create();
+ result->setRetries(a_requestRetransmissions);
+ if (a_requestRetransmissions > 0) result->setOnExpiry(anna::diameter::comm::Message::OnExpiry::Retransmit);
+ return result;
+}
+
+
+void RealmNode::releaseCommMessage(anna::diameter::comm::Message *msg) throw() {
+ a_commMessages.release(msg);
+}
+
+
+void RealmNode::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw() {
+// if (!logEnabled()) return;
+ anna::diameter::codec::Message codecMsg(getCodecEngine());
+ try { codecMsg.decode(db); } catch(anna::RuntimeException &ex) { ex.trace(); }
+ writeLogFile(codecMsg, logExtension, detail);
+
+}
+
+// Si ya lo tengo decodificado:
+void RealmNode::writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw() {
+// if (!logEnabled()) return;
+ // Open target file:
+ std::string targetFile = a_logFile;
+
+ if(a_splitLog) {
+ targetFile += ".";
+ targetFile += logExtension;
+ }
+
+ std::ofstream out(targetFile.c_str(), std::ifstream::out | std::ifstream::app);
+ // Set text to dump:
+ std::string title = "[";
+ title += logExtension;
+ title += "]";
+ // Build complete log:
+ std::string log = "\n";
+ std::string xml = decodedMessage.asXMLString();
+
+
+ if(a_detailedLog) {
+ anna::time::Date now;
+ now.setNow();
+ title += " ";
+ title += now.asString();
+ log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline);
+ log += xml;
+ log += "\n";
+ log += anna::functions::highlight("Used resource");
+ log += detail;
+ log += "\n";
+ } else {
+ log += title;
+ log += "\n";
+ log += xml;
+ log += "\n";
+ }
+
+ if(a_dumpLog) {
+ std::string name = getMyDiameterEngine()->getRealm();
+ name += ".";
+ name += anna::functions::asString(decodedMessage.getHopByHop());
+ name += ".";
+ name += anna::functions::asString(decodedMessage.getEndToEnd());
+ name += ".";
+ name += anna::functions::asString(decodedMessage.getId().first);
+ name += ".";
+ name += ((decodedMessage.getId().second) ? "request.":"answer.");
+ name += logExtension;
+ name += ".xml";
+ std::ofstream outMsg(name.c_str(), std::ifstream::out | std::ifstream::app);
+ outMsg.write(xml.c_str(), xml.size());
+ outMsg.close();
+ }
+
+ // Write and close
+ out.write(log.c_str(), log.size());
+ out.close();
+}
+
+void RealmNode::writeBurstLogFile(const std::string &buffer) throw() {
+ std::ofstream out(a_burstLogFile.c_str(), std::ifstream::out | std::ifstream::app);
+ out.write(buffer.c_str(), buffer.size());
+ out.close(); // close() will be called when the object is destructed (i.e., when it goes out of scope).
+ // you'd call close() only if you indeed for some reason wanted to close the filestream
+ // earlier than it goes out of scope.
+}
+
+int RealmNode::clearBurst() throw() {
+ int size = a_burstMessages.size();
+
+ if(size) {
+ std::map<int, anna::diameter::comm::Message*>::const_iterator it;
+ std::map<int, anna::diameter::comm::Message*>::const_iterator it_min(a_burstMessages.begin());
+ std::map<int, anna::diameter::comm::Message*>::const_iterator it_max(a_burstMessages.end());
+
+ for(it = it_min; it != it_max; it++) releaseCommMessage((*it).second);
+
+ a_burstMessages.clear();
+ } else {
+ std::string msg = "Burst list already empty. Nothing done";
+ std::cout << msg << std::endl;
+ LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
+ }
+
+ a_burstActive = false;
+ a_burstLoadIndx = 0;
+ a_burstDeliveryIt = a_burstMessages.begin();
+ return size;
+}
+
+int RealmNode::loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException) {
+ anna::diameter::comm::Message *msg = createCommMessage();
+ msg->setBody(db);
+ a_burstMessages[a_burstLoadIndx++] = msg;
+ return (a_burstLoadIndx - 1);
+}
+
+int RealmNode::stopBurst() throw() {
+ if(!a_burstActive) {
+ std::string msg = "Burst launch is already stopped. Nothing done";
+ std::cout << msg << std::endl;
+ LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
+ return -1;
+ }
+
+ a_burstActive = false;
+ // Remaining on cycle:
+ return (a_burstMessages.size() - (*a_burstDeliveryIt).first);
+}
+
+int RealmNode::popBurst(int releaseAmount) throw() {
+ if(!a_burstActive) {
+ std::string msg = "Burst launch is stopped. Nothing done";
+ std::cout << msg << std::endl;
+ LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
+ return -1;
+ }
+
+ if(releaseAmount < 1) {
+ std::string msg = "No valid release amount is specified. Ignoring burst pop";
+ std::cout << msg << std::endl;
+ LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
+ return -2;
+ }
+
+ int currentOTArequests = a_entity->getOTARequests();
+ a_burstPopCounter = (releaseAmount > currentOTArequests) ? currentOTArequests : releaseAmount;
+ return a_burstPopCounter;
+}
+
+int RealmNode::pushBurst(int loadAmount) throw() {
+ if(a_burstMessages.size() == 0) {
+ std::string msg = "Burst data not found (empty list). Ignoring burst launch";
+ std::cout << msg << std::endl;
+ LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
+ return -1;
+ }
+
+ if(loadAmount < 1) {
+ std::string msg = "No valid load amount is specified. Ignoring burst push";
+ std::cout << msg << std::endl;
+ LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
+ return -2;
+ }
+
+ a_burstActive = true;
+ int count;
+
+ for(count = 0; count < loadAmount; count++)
+ if(!sendBurstMessage()) break;
+
+ return count;
+}
+
+int RealmNode::sendBurst(int loadAmount) throw() {
+ if(a_burstMessages.size() == 0) {
+ std::string msg = "Burst data not found (empty list). Ignoring burst launch";
+ std::cout << msg << std::endl;
+ LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
+ return -1;
+ }
+
+ if(loadAmount < 1) {
+ std::string msg = "No valid load amount is specified. Ignoring burst send";
+ std::cout << msg << std::endl;
+ LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
+ return -2;
+ }
+
+ int count;
+
+ for(count = 0; count < loadAmount; count++)
+ if(!sendBurstMessage(true /* anyway */)) break;
+
+ return count;
+}
+
+int RealmNode::startBurst(int initialLoad) throw() {
+ if(initialLoad < 1) {
+ std::string msg = "No initial load is specified. Ignoring burst start";
+ std::cout << msg << std::endl;
+ LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
+ return -2;
+ }
+
+ a_burstActive = true;
+ a_burstCycle = 1;
+ a_burstDeliveryIt = a_burstMessages.begin();
+ return (pushBurst(initialLoad));
+}
+
+bool RealmNode::sendBurstMessage(bool anyway) throw() {
+ if(!anyway && !burstActive()) return false;
+
+ if(a_burstPopCounter > 0) {
+ if(burstLogEnabled()) writeBurstLogFile("x");
+
+ a_burstPopCounter--;
+ return false;
+ }
+
+ if(a_burstDeliveryIt == a_burstMessages.end()) {
+ a_burstDeliveryIt = a_burstMessages.begin();
+
+ if(!anyway) {
+ if(a_burstRepeat) {
+ a_burstCycle++;
+
+ if(burstLogEnabled()) writeBurstLogFile(anna::functions::asString("\nCompleted burst cycle. Starting again (repeat mode) on cycle %d.\n", a_burstCycle));
+ } else {
+ if(burstLogEnabled()) writeBurstLogFile("\nCompleted burst cycle. Burst finished (repeat mode disabled).\n");
+
+ stopBurst();
+ return false;
+ }
+ }
+ }
+
+ anna::diameter::comm::Message *msg = (*a_burstDeliveryIt).second;
+ int order = (*a_burstDeliveryIt).first + 1;
+ a_burstDeliveryIt++;
+ bool dot = true;
+ // sending
+ bool result = a_entity->send(msg, anna::CommandLine::instantiate().exists("balance"));
+
+ if(burstLogEnabled()) {
+ if(a_burstMessages.size() >= 100)
+ dot = (order % (a_burstMessages.size() / 100));
+
+ if(dot) {
+ writeBurstLogFile(".");
+ } else {
+ writeBurstLogFile(anna::functions::asString(" %d", order));
+ int otaReqs = a_entity->getOTARequests();
+
+ if(result && (otaReqs != a_otaRequest)) {
+ // false if was a sending after an answer received (no OTA change in this case)
+ // true after push and pop operations
+ a_otaRequest = otaReqs;
+ writeBurstLogFile(anna::functions::asString("[OTA %d]", a_otaRequest));
+ }
+ }
+ }
+
+ // Detailed log:
+ if(logEnabled()) {
+ anna::diameter::comm::Server *usedServer = a_entity->getLastUsedResource();
+ anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
+ std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
+ writeLogFile(msg->getBody(), (result ? "sent2e" : "send2eError"), detail); // el del nodo de trabajo
+ }
+
+ return result;
+}
+
+std::string RealmNode::lookBurst(int order) const throw() {
+ std::string result = "No message found for order provided (";
+ result += anna::functions::asString(order);
+ result += ")";
+ std::map<int, anna::diameter::comm::Message*>::const_iterator it = a_burstMessages.find(order - 1);
+
+ if(it != a_burstMessages.end()) {
+ // Decode
+ anna::diameter::codec::Message codecMsg(getCodecEngine()); // XXXXXXXXXXXXXXXX el del nodo de trabajo
+ try { codecMsg.decode((*it).second->getBody()); } catch(anna::RuntimeException &ex) { ex.trace(); }
+ result = codecMsg.asXMLString();
+ }
+
+ return result;
+}
+
+std::string RealmNode::gotoBurst(int order) throw() {
+ std::string result = "Position not found for order provided (";
+ std::map<int, anna::diameter::comm::Message*>::iterator it = a_burstMessages.find(order - 1);
+
+ if(it != a_burstMessages.end()) {
+ a_burstDeliveryIt = it;
+ result = "Position updated for order provided (";
+ }
+
+ result += anna::functions::asString(order);
+ result += ")";
+ return result;
+}
+
+anna::xml::Node* RealmNode::asXML(anna::xml::Node* parent) const
+throw() {
+ anna::xml::Node* result = parent->createChild("RealmNode");
+
+ result->createAttribute("OriginRealm", a_originRealm);
+ result->createAttribute("ApplicationId", a_applicationId);
+ result->createAttribute("LogFile", a_logFile);
+ result->createAttribute("SplitLog", a_splitLog ? "yes" : "no");
+ result->createAttribute("DetailedLog", a_detailedLog ? "yes" : "no");
+ result->createAttribute("DumpLog", a_dumpLog ? "yes" : "no");
+ result->createAttribute("BurstLogFile", a_burstLogFile);
+ result->createAttribute("RequestRetransmissions", a_requestRetransmissions);
+
+ anna::xml::Node* commEngine = result->createChild("CommEngine");
+ a_commEngine->asXML(commEngine);
+
+ return result;
+}
+
+std::string RealmNode::asXMLString() const throw() {
+ anna::xml::Node root("root");
+ return anna::xml::Compiler().apply(asXML(&root));
+}
--- /dev/null
+// ANNA - Anna is Not Nothingness Anymore //
+// //
+// (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
+// //
+// See project site at http://redmine.teslayout.com/projects/anna-suite //
+// See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
+
+
+#ifndef example_diameter_launcher_RealmNode_hpp
+#define example_diameter_launcher_RealmNode_hpp
+
+// Standard
+#include <string>
+#include <fstream>
+
+// Project
+#include <anna/core/util/Millisecond.hpp>
+#include <anna/core/util/Recycler.hpp>
+#include <anna/core/DataBlock.hpp>
+#include <anna/diameter/codec/Message.hpp>
+
+
+namespace anna {
+ namespace diameter {
+ namespace codec {
+ class Engine;
+ }
+ namespace comm {
+ class Message;
+ }
+ }
+}
+
+
+class MyDiameterEntity;
+class MyDiameterEngine;
+class MyLocalServer;
+
+
+class RealmNode {
+
+ MyDiameterEngine *a_commEngine;
+ MyDiameterEntity *a_entity; // we could get it finding the unique instante within comm engine, but it is more comfortable assign here.
+ MyLocalServer* a_diameterServer; // idem
+ anna::diameter::codec::Engine *a_codecEngine;
+
+ // resources
+ int a_requestRetransmissions;
+ anna::Recycler<anna::diameter::comm::Message> a_commMessages;
+
+ // main
+ std::string a_originRealm;
+ unsigned int a_applicationId;
+
+ // Timming
+ anna::Millisecond a_allowedInactivityTime;
+ anna::Millisecond a_tcpConnectDelay;
+ anna::Millisecond a_answersTimeout;
+ anna::Millisecond a_ceaTimeout;
+ anna::Millisecond a_watchdogPeriod;
+
+ // Logs & burst
+ std::string a_logFile;
+ bool a_splitLog, a_detailedLog, a_dumpLog;
+ std::string a_burstLogFile;
+ std::ofstream a_burstLogStream;
+ int a_burstCycle;
+ bool a_burstRepeat;
+ bool a_burstActive;
+ std::map < int /* dummy, p.e. used for order number */, anna::diameter::comm::Message* > a_burstMessages;
+ int a_burstLoadIndx;
+ std::map<int, anna::diameter::comm::Message*>::const_iterator a_burstDeliveryIt;
+ int a_otaRequest;
+ int a_burstPopCounter;
+
+public:
+ RealmNode(const std::string &originRealm, unsigned int applicationId, anna::diameter::codec::Engine *codecEngine);
+ ~RealmNode() {;}
+
+ std::string asString() const throw();
+
+ // Core resources:
+ MyDiameterEngine* getMyDiameterEngine() const throw() { return a_commEngine; }
+ anna::diameter::codec::Engine *getCodecEngine() const throw() { return a_codecEngine; }
+ void createEntity(const std::string &entityRepresentation, const anna::Millisecond &bindTimeout, const anna::Millisecond &applicationTimeout) throw();
+ MyDiameterEntity *getEntity() const throw() { return a_entity; }
+ void startDiameterServer(const std::string &serverRepresentation, int sessions, const anna::Millisecond &inactivityTimeout) throw(anna::RuntimeException);
+ MyLocalServer* getDiameterServer() throw() { return a_diameterServer; }
+ void setRequestRetransmissions(int r) throw() { if (r >= 0) a_requestRetransmissions = r; }
+
+ // Messages factory:
+ anna::diameter::comm::Message *createCommMessage() throw(anna::RuntimeException);
+ void releaseCommMessage(anna::diameter::comm::Message*) throw();
+
+ // Traffic logs & burst:
+ void setLogs(const std::string &log, bool splitLog, bool detailedLog, bool dumpLog, const std::string &burstLog) throw() {
+ a_logFile = log;
+ a_splitLog = splitLog;
+ a_detailedLog = detailedLog;
+ a_dumpLog = dumpLog;
+ a_burstLogFile = burstLog;
+ }
+
+ bool logEnabled() const throw() { return (((a_logFile == "") || (a_logFile == "null")) ? false : true); }
+ void writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw();
+ void writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw();
+ void writeBurstLogFile(const std::string &buffer) throw();
+ bool burstLogEnabled() const throw() { return (((a_burstLogFile == "") || (a_burstLogFile == "null")) ? false : true); }
+ int clearBurst() throw(); // returns removed
+ int loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException);
+ void repeatBurst(bool repeat) throw() { a_burstRepeat = repeat; }
+ int startBurst(int initialLoad) throw(); // return processed on start, or -1 if burst list is empty, -2 if invalid initial load (0 or negative)
+ int pushBurst(int loadAmount) throw(); // returns pushed (perhaps is less than provided because of no repeat mode and burst list exhausted), or -1 if burst list is empty, -2 if invalid load (0 or negative)
+ int sendBurst(int loadAmount) throw(); // returns sent (burst always cycled using send), returns -1 if burst list is empty, -2 if invalid load (0 or negative)
+ int popBurst(int releaseAmount) throw(); // returns popped (perhaps is less than provided because of OTA request), or -1 if burst stopped
+ int stopBurst() throw(); // returns remaining on cycle, or -1 if burst already stopped
+ bool burstActive() const throw() { return a_burstActive; }
+ bool sendBurstMessage(bool anyway = false) throw();
+ std::string lookBurst(int order) const throw();
+ std::string gotoBurst(int order) throw();
+
+ anna::xml::Node* asXML(anna::xml::Node* parent) const throw();
+ std::string asXMLString() const throw();
+};
+
+#endif
ABOUT CONTENT
-------------
-Stacks available at './stacks'.
-The launcher uses the configuration given by '.dictionary' which points to a specification list.
-Available different setups by mean files named as '.dictionary__<stack description>'.
+Stacks available at './stacks'. The launcher uses 'dictionary.xml' created ad-hoc by default.
+It is a QoS application dictionary.
-Template for xml messages (message.dtd) and dictionaries (dictionary.dtd) are informative, not
-actually required by process. Located at './DTDs'.
-
-Additional helpers/scripts could be found at './resources' directory.
+Template for xml messages (message.dtd), dictionaries (dictionary.dtd) and services (services.dtd)
+are informative, not actually required by process. Located at './DTDs'.
STARTING THE PROCESS
--------------------
-Start with 'run.sh'. You could manually edit such script adding parameters as '-trace debug' to
-get complete 'launcher.trace'. Execute 'ADL-launcher' without arguments to see a complete
+Start with 'run.sh'. You could manually edit such script adding parameters as '--trace debug' to
+get complete 'launcher.trace'. Execute 'ADML-launcher' without arguments to see a complete
command-line help.
DEPLOYED SCRIPTS
----------------
You could get help about installed resources by mean 'help.sh', which launch a help request to
-the started ADL-launcher process http interface. All the implemented http operations could be
+the started ADML-launcher process http interface. All the implemented http operations could be
launched through a script to make easy use. The http client 'curl' is used by default due to
its presence on common linux distributions.
+++ /dev/null
--httpServer `grep -v ^# .httpServer`
--dictionary `grep -v ^# .dictionary`
--diameterServer `grep -v ^# .diameterServer`
--diameterServerSessions `grep -v ^# .diameterServerSessions`
--entity `grep -v ^# .entity`
--entityServerSessions `grep -v ^# .entityServerSessions`
entity_dflt=`cat .entity 2>/dev/null`
entityServerSessions_dflt=`cat .entityServerSessions 2>/dev/null`
-# Stack:
-dictionary_dflt=`cat .dictionary 2>/dev/null`
-
echo
echo
# If all have values:
if [ "$httpServer_dflt" != "" -a "$diameterServer_dflt" != "" -a "$diameterServerSessions_dflt" != "" -a \
- "$entity_dflt" != "" -a "$entityServerSessions_dflt" != "" -a \
- "$dictionary_dflt" != "" ]
+ "$entity_dflt" != "" -a "$entityServerSessions_dflt" != "" ]
then
echo "Do you wish to answer wizard commandline configuration ? (y/n) [n]:"
read wizard
[ "$diameterServerSessions_dflt" = "" ] && diameterServerSessions_dflt=1
[ "$entity_dflt" = "" ] && entity_dflt="localhost:4000,localhost:4001"
[ "$entityServerSessions_dflt" = "" ] && entityServerSessions_dflt=0
-[ "$dictionary_dflt" = "" ] && dictionary_dflt=dictionary.xml
# Wizard
read httpServer
[ "$httpServer" = "" ] && httpServer=$httpServer_dflt
-echo "Diameter dictionary: you could use '/opt/bin/anna/example_diameter_stackManagement' tool in order to build"
-echo " autonomous dictionaries for any kind of application. The key is to concatenate xml contents (ietf, 3gpp,"
-echo " vendor-specific, etc.). See 'example/diameter/stackManagement/self_ruling_setups.sh' for this."
-echo
-echo "This launcher can also join them providing a comma-separated list (dictionaries available on ./stack)."
-echo "By default, a QoS Application setup is suggested. Input the desired configuration instead, or press ENTER:"
-echo
-echo " [$dictionary_dflt]:"
-read dictionary
-[ "$dictionary" = "" ] && dictionary=$dictionary_dflt
-
# As server:
echo "Diameter own server available connections (0: diameter server disabled) [$diameterServerSessions_dflt]:"
read diameterServerSessions
# Configure:
echo $httpServer > .httpServer
-echo $dictionary > .dictionary
-echo $diameterServer > .diameterServer
-echo $diameterServerSessions > .diameterServerSessions
-echo $entity > .entity
-echo $entityServerSessions > .entityServerSessions
+
+cat services.msk \
+ | sed 's/_DIAMETER_SERVER_/'$diameterServer'/' \
+ | sed 's/_DIAMETER_SERVER_SESSIONS_/'$diameterServerSessions'/' \
+ | sed 's/_ENTITY_/'$entity'/' \
+ | sed 's/_ENTITY_SERVER_SESSIONS_/'$entityServerSessions'/' \
+> services.xml
echo
echo
--- /dev/null
+<services>
+ <!-- Stacks -->
+ <stack id="0" dictionary="dictionary.xml"/>
+
+ <!-- Nodes -->
+ <node originRealm="ADML-advanced" applicationId="0" entity="_ENTITY_" entityServerSessions="_ENTITY_SERVER_SESSIONS_" diameterServer="_DIAMETER_SERVER_" diameterServerSessions="_DIAMETER_SERVER_SESSIONS_"/>
+</services>
+
ABOUT CONTENT
-------------
-Template for xml messages (message.dtd) and dictionaries (dictionary.dtd) are informative, not
-actually required by process. They are located at './DTDs'. Stacks are available at './stacks'.
-There are also some stuff (hex/xml examples, etc.) which could be useful.
+Template for xml messages (message.dtd), dictionaries (dictionary.dtd) and services (services.dtd)
+are informative, not actually required by process. They are located at './DTDs'. Stacks are available
+at './stacks'. There are also some stuff (hex/xml examples, etc.) which could be useful.
Firstly you have to configure this directory in order to choose the type of launcher which will
be preconfigured for your basic needs: client, server, balancer (proxy) and dummy process (this
last is used for code/encode and does not launch any communication interface).
If you are going to launch different processes, we recommend to clone this whole directory into
-another one (call it 'ADL-client', 'ADL-server_2', 'Diameter_proxy', or whatever you want), and
+another one (call it 'ADML-client', 'ADML-server_2', 'Diameter_proxy', or whatever you want), and
then configure it again.
Execute './configure.sh' and follow the intructions. You can call this several times, but the
last configuration will be the one which prevails.
-Additional helpers/scripts could be found at './resources' directory.
-
STARTING THE PROCESS
--------------------
-After configuring the ADL execution context, a new script has been created: 'run.sh'.
-You can manually edit such script adding parameters as '-trace debug' to get complete traces,
-or adapt the communication endpoints for your environment.
+After configuring the ADML execution context, a new script has been created: 'run.sh'.
+You can manually edit such script adding parameters as '--trace debug' to get complete traces,
+or adapt the communication endpoints for your environment editing 'services.xml'.
Launch the executable process without arguments to see a complete command-line help.
-Don't be scared. There are plenty of possibilities but the 'run.sh' script has been prepared
-for the type of launcher you wanted.
+Don't be scared. There are plenty of possibilities but the 'run.sh' script and 'services.xml'
+have been prepared for the type of launcher you wanted.
OPERATION
---------
# VARIABLES #
#############
-# Diameter dictionary:
-STD_DICTIONARY=stacks/avps_etsi.xml,stacks/avps_ietf.xml,stacks/avps_tgpp.xml,stacks/commands_baseProtocol.xml
-APP_DICTIONARY=stacks/commands_qosControl.xml
-DICTIONARY=$STD_DICTIONARY,$APP_DICTIONARY
-
-# Communication endpoints:
-LOCAL_STANDARD_ENDPOINT=localhost:3868
-EXAMPLE_ENTITY_4_BALANCER=192.168.12.11:3868,192.168.12.21:3868
-CONNS=10
-
# General
-EXE_BN=ADL-launcher
+EXE_BN=ADML-launcher
#############
# FUNCTIONS #
cd \`dirname \$0\`
STARTED=\`pgrep $1 2>/dev/null\`
[ \$? -eq 0 ] && { echo "Already started!"; echo "\$STARTED" ; exit 1 ; }
-0> launcher.traces
+0> launcher.trace
rm -f counters/*
# Execution line:
-./$@ &
+./$@ --services services.xml &
echo \$! > .pid
EOF
tol=$(get_tol $option)
[ "$tol" = "" ] && _exit "Option '$option' not implemented !!"
+# Services
+ln -sf services/${tol}.xml services.xml
+
# Tracing
-TRACING="--cntDir counters"
+DEBUG="--cntDir counters"
echo
echo "Enable debug traces ? (y/n) [n]:"
read enable
[ "$enable" = "" ] && enable=n
-[ "$enable" = "y" ] && TRACING="$TRACING --trace debug"
+[ "$enable" = "y" ] && DEBUG="$DEBUG --trace debug"
# Kindness
KINDNESS=
fi
# Run script:
-EXE_LINK=ADL-$tol
+EXE_LINK=ADML-$tol
ln -sf $EXE_BN $EXE_LINK
case $tol in
client)
ENTITY=$LOCAL_STANDARD_ENDPOINT
- createRunScript $EXE_LINK --dictionary $DICTIONARY --entity $ENTITY --entityServerSessions $CONNS --diameterServerSessions 0 $KINDNESS $TRACING &
+ createRunScript $EXE_LINK $KINDNESS $DEBUG &
;;
server)
SERVER=$LOCAL_STANDARD_ENDPOINT
- createRunScript $EXE_LINK --dictionary $DICTIONARY --diameterServer $SERVER --diameterServerSessions $CONNS --entityServerSessions 0 $KINDNESS $TRACING &
+ createRunScript $EXE_LINK $KINDNESS $DEBUG &
;;
balancer)
SERVER=$LOCAL_STANDARD_ENDPOINT
ENTITY=$EXAMPLE_ENTITY_4_BALANCER
- createRunScript $EXE_LINK --dictionary $DICTIONARY --entity $ENTITY --entityServerSessions $CONNS --diameterServer $SERVER --diameterServerSessions $CONNS --balance $KINDNESS $TRACING &
+ createRunScript $EXE_LINK $KINDNESS $DEBUG &
;;
dummy)
- createRunScript $EXE_LINK --dictionary $DICTIONARY --entityServerSessions 0 --diameterServerSessions 0 $KINDNESS $TRACING &
+ createRunScript $EXE_LINK $KINDNESS $DEBUG &
;;
esac
echo
echo "Created 'run.sh' script !"
echo
+
ABOUT CONTENT
-------------
-Template for xml messages (message.dtd) and dictionaries (dictionary.dtd) are informative, not
-actually required by process. They are located at './DTDs'. Stacks are available at './stacks'.
-There are also some stuff (hex/xml examples, etc.) which could be useful.
+Template for xml messages (message.dtd), dictionaries (dictionary.dtd) and services (services.dtd)
+are informative, not actually required by process. They are located at './DTDs'. Stacks are available
+at './stacks'. There are also some stuff (hex/xml examples, etc.) which could be useful.
The directory 'tests' contains resources to create FT test cases. The script 'common.sh' implement
a basic scheduler to launch a request to the server, waits for incoming activity, retrieve the
represent different test cases, linking them to a common simple diameter client agent). But with
this simple scripts we could do something valid to start with.
-Additional helpers/scripts could be found at './resources' directory.
-
STARTING THE PROCESS
--------------------
Launch the executable process without arguments to see a complete command-line help.
-Don't be scared. There are plenty of possibilities but the 'run.sh' script has been prepared
-for the type of launcher you wanted.
+Don't be scared. There are plenty of possibilities but the 'run.sh' script and 'services.xml'
+have been prepared for the type of launcher you wanted.
OPERATION
---------
+++ /dev/null
---dictionary `grep -v ^# .dictionary`
---entity `grep -v ^# .entity`
---entityServerSessions `grep -v ^# .entityServerSessions`
---splitLog
entity_dflt=`cat .entity 2>/dev/null`
entityServerSessions_dflt=`cat .entityServerSessions 2>/dev/null`
-# Stack:
-dictionary_dflt=`cat .dictionary 2>/dev/null`
-
echo
echo
# If all have values:
-if [ "$entity_dflt" != "" -a "$entityServerSessions_dflt" != "" -a "$dictionary_dflt" != "" ]
+if [ "$entity_dflt" != "" -a "$entityServerSessions_dflt" != "" ]
then
echo "Do you wish to answer wizard commandline configuration ? (y/n) [n]:"
read wizard
#[ "$entity_dflt" = "" ] && entity_dflt="192.168.12.11:3868,192.168.12.21:3868"
[ "$entity_dflt" = "" ] && entity_dflt="localhost:3868"
[ "$entityServerSessions_dflt" = "" ] && entityServerSessions_dflt=1
-[ "$dictionary_dflt" = "" ] && dictionary_dflt=dictionary.xml
-
# Wizard
-echo "Diameter dictionary: you could use '/opt/bin/anna/example_diameter_stackManagement' tool in order to build"
-echo " autonomous dictionaries for any kind of application. The key is to concatenate xml contents (ietf, 3gpp,"
-echo " vendor-specific, etc.). See 'example/diameter/stackManagement/self_ruling_setups.sh' for this."
-echo
-echo "This launcher can also join them providing a comma-separated list (dictionaries available on ./stack)."
-echo "By default, a QoS Application setup is suggested. Input the desired configuration instead, or press ENTER:"
-echo
-echo " [$dictionary_dflt]:"
-read dictionary
-[ "$dictionary" = "" ] && dictionary=$dictionary_dflt
# As client:
echo "Diameter entity server sessions (0: diameter entity disabled) [$entityServerSessions_dflt]:"
[ "$entity" = "" ] && entity="$entity_dflt"
# Configure:
-echo $dictionary > .dictionary
-echo $entity > .entity
-echo $entityServerSessions > .entityServerSessions
+cat services.msk \
+ | sed 's/_ENTITY_/'$entity'/' \
+ | sed 's/_ENTITY_SERVER_SESSIONS_/'$entityServerSessions'/' \
+> services.xml
echo
echo
--- /dev/null
+<services>
+ <!-- Stacks -->
+ <stack id="0" dictionary="dictionary.xml"/>
+
+ <!-- Nodes -->
+ <node originRealm="ADML-ft-client" applicationId="0" entity="_ENTITY_" entityServerSessions="_ENTITY_SERVER_SESSIONS_" splitLog="yes"/>
+</services>
+
#############
# VARIABLES #
#############
-# Paths from the point of view of ADL executable:
+# Paths from the point of view of ADML executable:
REQ1_HEX=./hex_examples/aar-bad.hex
#############
// See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
+// Standard
+#include <string>
+
// Project
#include <anna/core/core.hpp>
#include <anna/time/functions.hpp>
try {
anna::CommandLine& commandLine(anna::CommandLine::instantiate());
// General
+ commandLine.add("services", anna::CommandLine::Argument::Mandatory, "Services xml path file. Shall be validated against dtd schema written on warning traces: 'Services DTD schema'");
commandLine.add("trace", anna::CommandLine::Argument::Optional, "Trace level (emergency, alert, critical, error, warning, notice, information, debug, local0..local7)");
- commandLine.add("log", anna::CommandLine::Argument::Optional, "Process log file (operations result, traffic log, etc.). By default 'launcher.log'. Empty string or \"null\" name, to disable. Warning: there is no rotation for log files (use logrotate or whatever)");
- commandLine.add("splitLog", anna::CommandLine::Argument::Optional, "Splits log file (appends to log filename, extensions with the type of event: see help on startup information-level traces). No log files for code/decode and load operations are created", false);
- commandLine.add("detailedLog", anna::CommandLine::Argument::Optional, "Insert detailed information at log files. Should be disabled on automatic tests. Useful on '-balance' mode to know messages flow along the sockets", false);
- commandLine.add("dumpLog", anna::CommandLine::Argument::Optional, "Write to disk every incoming/outcoming message named as '<hop by hop>.<end to end>.<message code>.<request|answer>.<type of event>.xml'", false);
- commandLine.add("logStatisticSamples", anna::CommandLine::Argument::Optional, "Log statistics samples for the provided concept id list, over './sample.<concept id>.csv' files. For example: \"1,2\" will log concepts 1 and 2. Reserved word \"all\" activates all registered statistics concept identifiers. That ids are shown at context dump (see help to get it).");
- commandLine.add("burstLog", anna::CommandLine::Argument::Optional, "Burst operations log file. By default 'launcher.burst'. Empty string or \"null\" name, to disable. Warning: there is no rotation for log files (use logrotate or whatever). Output: dot (.) for each burst message sent/pushed, cross (x) for popped ones, and order number when multiple of 1% of burst list size, plus OTA requests when changed.");
commandLine.add("cntDir", anna::CommandLine::Argument::Optional, "Counters directory. By default is the current execution directory. Warning: a counter file will be dump per record period; take care about the possible accumulation of files");
commandLine.add("cntRecordPeriod", anna::CommandLine::Argument::Optional, "Counters record procedure period in milliseconds. If missing, default value of 300000 (5 minutes) will be assigned. Value of 0 disables the record procedure.");
+ commandLine.add("logStatisticSamples", anna::CommandLine::Argument::Optional, "Log statistics samples for the provided concept id list, over './sample.<concept id>.csv' files. For example: \"1,2\" will log concepts 1 and 2. Reserved word \"all\" activates all registered statistics concept identifiers. That ids are shown at context dump (see help to get it).");
+
// Communications
+ commandLine.add("reconnectionPeriod", anna::CommandLine::Argument::Optional, "Milliseconds to recover diameter client-session when server connection has been broken. If missing, default value of 10000 will be assigned");
commandLine.add("httpServer", anna::CommandLine::Argument::Optional, "HTTP Management interface address (using i.e. curl tool) in '<address>:<port>' format. For example: 10.20.30.40:8080");
commandLine.add("httpServerShared", anna::CommandLine::Argument::Optional, "Enables shared bind for HTTP Management interface address. It would be useful i.e. to allow a great amount of curl operations per second", false);
- commandLine.add("diameterServer", anna::CommandLine::Argument::Optional, "Diameter own server address in '<address>:<port>' format. For example: 10.20.30.40:3868");
- commandLine.add("diameterServerSessions", anna::CommandLine::Argument::Optional, "Diameter own server available connections (0: diameter server disabled). Default value of 1");
- commandLine.add("entity", anna::CommandLine::Argument::Optional, "Target diameter entity (comma-separated '<address>:<port>' format). For example: 10.20.30.40:3868,10.20.30.41:3868");
- commandLine.add("entityServerSessions", anna::CommandLine::Argument::Optional, "Diameter entity server sessions (0: diameter entity disabled). Default value of 1");
- commandLine.add("balance", anna::CommandLine::Argument::Optional, "Balance over entity servers instead of doing standard behaviour (first primary, secondary if fails, etc.)", false);
- commandLine.add("sessionBasedModelsClientSocketSelection", anna::CommandLine::Argument::Optional, "By default, round-robin will be applied for IEC model (SMS/MMS), and Session-Id Low Part will be analyzed for ECUR/SCUR model (data, voice and content). You could change ECUR/SCUR analysis behaviour providing 'SessionIdHighPart', 'SessionIdOptionalPart' (atoi applied; usually subscriber id data, i.e. MSISDN or IMSI) and 'RoundRobin'.");
- commandLine.add("stacks", anna::CommandLine::Argument::Mandatory, "<appid1,dictionary1#appid2,dictionary2#...#appidN,dictionaryN>: this is a list of #-separated stacks defined by a comma-separated pair <application-id,xml dictionary pathfile>. If only one stack is provided, application-id could be omitted and then, all the messages will be decoded with the dictionary regardless the value of the application-id (the stack will be registered with id=0).");
- commandLine.add("ignoreFlags", anna::CommandLine::Argument::Optional, "Ignore flags on validation (at the moment only bits M & P from AVPs, because V bit is too important; no operation flags could be checked). Also force compact xml presentation ignoring flags during dictionary elements identification", false);
+
+ // Codec engine
commandLine.add("ignoreErrors", anna::CommandLine::Argument::Optional, "Local server skips requests errors analysis which would prepare automatic answers for them when a problem is found. If no answer is programmed and entity is configured, a failed request would be forwarded (delegates at the end point) even if this parameter is missing", false);
- commandLine.add("allowedInactivityTime", anna::CommandLine::Argument::Optional, "Milliseconds for the maximum allowed inactivity time on server sessions born over the local server before being reset. If missing, default value of 90000 will be assigned");
- commandLine.add("tcpConnectDelay", anna::CommandLine::Argument::Optional, "Milliseconds to wait TCP connect to any server. If missing, default value of 200 will be assigned");
- commandLine.add("answersTimeout", anna::CommandLine::Argument::Optional, "Milliseconds to wait pending application answers from diameter peers. If missing, default value of 10000 will be assigned");
- commandLine.add("ceaTimeout", anna::CommandLine::Argument::Optional, "Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout' will be assigned");
- commandLine.add("watchdogPeriod", anna::CommandLine::Argument::Optional, "Milliseconds for watchdog timer (Tw) for diameter keep-alive procedure. If missing, default value of 30000 will be assigned");
- commandLine.add("reconnectionPeriod", anna::CommandLine::Argument::Optional, "Milliseconds to recover diameter client-session when server connection has been broken. If missing, default value of 10000 will be assigned");
- commandLine.add("cer", anna::CommandLine::Argument::Optional, "Pathfile for the Capabilities Exchange Request xml message. If missing, \"cer.xml\" is searched. If missing again, process creates own CER");
- commandLine.add("dwr", anna::CommandLine::Argument::Optional, "Pathfile for the Device Watchdog Request xml message. If missing, \"dwr.xml\" is searched. If missing again, process creates own DWR");
- commandLine.add("originHost", anna::CommandLine::Argument::Optional, "Diameter application host name (system name). If missing, process sets o.s. hostname");
- commandLine.add("originRealm", anna::CommandLine::Argument::Optional, "Diameter application node realm name. If missing, process sets domain name");
+ commandLine.add("ignoreFlags", anna::CommandLine::Argument::Optional, "Ignore flags on validation (at the moment only bits M & P from AVPs, because V bit is too important; no operation flags could be checked). Also force compact xml presentation ignoring flags during dictionary elements identification", false);
commandLine.add("integrationAndDebugging", anna::CommandLine::Argument::Optional, "Sets validation mode to 'Always' (default validates only after decoding), and validation depth to 'Complete' (default validates until 'FirstError')", false);
commandLine.add("fixMode", anna::CommandLine::Argument::Optional, "Sets message fix mode (unreconized values will assume default 'BeforeEncoding'). Allowed: 'BeforeEncoding', 'AfterDecoding', 'Always', 'Never'");
--- /dev/null
+<services>
+ <!-- Stacks -->
+ <stack id="0" dictionary="dictionary.xml"/>
+
+ <!-- Nodes -->
+ <node originRealm="ADML-balancer" applicationId="0" entity="192.168.12.11:3868,192.168.12.21:3868" diameterServer="localhost:3868" balance="yes"/>
+ <!-- <node originRealm="ADML-proxy" applicationId="0" entity="localhost:3868" diameterServer="localhost:3870"/> -->
+</services>
+
--- /dev/null
+<services>
+ <!-- Stacks -->
+ <stack id="0" dictionary="dictionary.xml"/>
+
+ <!-- Nodes -->
+ <node originRealm="ADML-client" applicationId="0" entity="localhost:3868"/>
+</services>
+
--- /dev/null
+<services>
+ <!-- Stacks -->
+ <stack id="0" dictionary="dictionary.xml"/>
+
+ <!-- Nodes -->
+ <node originRealm="ADML-dummy" applicationId="0"/>
+</services>
+
--- /dev/null
+<services>
+ <!-- Stacks -->
+ <stack id="16777236" dictionary="dictionaryRx.xml"/>
+ <stack id="16777238" dictionary="dictionaryGx.xml"/>
+ <stack id="16777302" dictionary="dictionarySy.xml"/>
+
+ <!-- Nodes -->
+ <node originRealm="afNode" applicationId="16777236" entity="192.168.12.11:3868,192.168.12.21:3868"/>
+ <node originRealm="ggsnNode" applicationId="16777238" entity="192.168.12.11:3868,192.168.12.21:3868"/>
+ <node originRealm="ggsn2Node" applicationId="16777238" entity="192.168.12.11:3868,192.168.12.21:3868"/>
+ <node originRealm="ocsNode" applicationId="16777302" entity="192.168.12.11:3868,192.168.12.21:3868"/>
+</services>
+
--- /dev/null
+<services>
+ <!-- Stacks -->
+ <stack id="0" dictionary="dictionary.xml"/>
+
+ <!-- Nodes -->
+ <node originRealm="ADML-server" applicationId="0" diameterServer="localhost:3868"/>
+</services>
+
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Diameter services DTD -->
+
+<!ELEMENT services (stack*, node*)>
+
+<!ELEMENT stack EMPTY>
+<!ATTLIST stack id CDATA #REQUIRED dictionary CDATA #REQUIRED>
+<!--
+ Stack record
+
+ id: Normally the id corresponds to the Application-Id for which the dictionary provided is designed.
+ (in multistack applications, it shall be mandatory respect such association to know the stack used
+ for processed messages).
+ dictionary: Path to the dictionary file
+-->
+
+<!ELEMENT node EMPTY>
+<!ATTLIST node originRealm CDATA #REQUIRED applicationId CDATA #REQUIRED originHost CDATA #IMPLIED cer CDATA #IMPLIED dwr CDATA #IMPLIED allowedInactivityTime CDATA #IMPLIED tcpConnectDelay CDATA #IMPLIED answersTimeout CDATA #IMPLIED ceaTimeout CDATA #IMPLIED watchdogPeriod CDATA #IMPLIED entity CDATA #IMPLIED entityServerSessions CDATA #IMPLIED diameterServer CDATA #IMPLIED diameterServerSessions CDATA #IMPLIED balance (yes | no) #IMPLIED sessionBasedModelsClientSocketSelection (SessionIdLowPart | SessionIdHighPart | SessionIdOptionalPart | RoundRobin) #IMPLIED retries CDATA #IMPLIED log CDATA #IMPLIED splitLog (yes | no) #IMPLIED detailedLog (yes | no) #IMPLIED dumpLog (yes | no) #IMPLIED burstLog (yes | no) #IMPLIED>
+<!--
+ Node record
+
+ originRealm: Node identifier (Origin-Realm name).
+ applicationId: The Application-Id provided must exists as a registered 'stack id'.
+ originHost: Diameter application host name (system name). If missing, process sets o.s. hostname
+ Note that if you have two or more realms, the names must be different.
+ cer: User defined CER path file to be encoded to establish diameter connections.
+ If missing, will be harcoded
+ dwr: User defined DWR path file to be encoded for diameter protocol keep alive.
+ If missing, will be harcoded
+ allowedInactivityTime: Milliseconds for the maximum allowed inactivity time on server sessions born over the
+ local server before being reset. If missing, default value of 90000 will be assigned
+ tcpConnectDelay: Milliseconds to wait TCP connect to any server. If missing, default value of 200 will
+ be assigned
+ answersTimeout: Milliseconds to wait pending application answers from diameter peers. If missing,
+ default value of 10000 will be assigned
+ ceaTimeout: Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout'
+ will be assigned
+ watchdogPeriod: Milliseconds for watchdog timer (Tw) for diameter keep-alive procedure. If missing, default
+ value of 30000 will be assigned
+ entity: Target diameter entity (comma-separated '<address>:<port>' format).
+ For example: 10.20.30.40:3868,10.20.30.41:3868. If missing, no entity will be enabled
+ entityServerSessions: Diameter entity server sessions (0: diameter entity disabled). Default value of 1
+ diameterServer: Diameter own server address in '<address>:<port>' format. For example: 10.20.30.40:3868.
+ If missing, no local server will be enabled
+ diameterServerSessions: Diameter own server available connections (0: diameter server disabled). Default value of 1
+ balance: Balance over entity servers instead of doing standard behaviour (first primary, secondary
+ if fails, etc.). Default value 'no'
+ sessionBasedModelsClientSocketSelection: By default, round-robin will be applied for IEC model (SMS/MMS), and Session-Id Low Part
+ will be analyzed for ECUR/SCUR model (data, voice and content). You could change ECUR/SCUR
+ analysis behaviour providing 'SessionIdHighPart', 'SessionIdOptionalPart' (atoi applied;
+ usually subscriber id data, i.e. MSISDN or IMSI) and 'RoundRobin' (also 'SessionIdLowPart')
+ retries: Expired responses will cause a number of request retransmissions. Disabled by default (0 retries)
+ log: Process log file (operations result, traffic log, etc.). By default '<originRealm>.launcher.log'.
+ Empty string or "null" name, to disable. Warning: there is no rotation for log files
+ (use logrotate or whatever you consider)
+ splitLog: Splits log file (appends to log filename, extensions with the type of event: see help on
+ startup information-level traces). No log files for code/decode and load operations are created.
+ Default value 'no'
+ detailedLog: Insert detailed information at log files. Should be disabled on automatic tests. Useful on
+ 'balance' mode to know messages flow along the sockets. Default value 'no'
+ dumpLog: Write to disk every incoming/outcoming message named as:
+ '<originRealm>.<hop by hop>.<end to end>.<message code>.<request|answer>.<type of event>.xml'
+ Default value 'no'
+ burstLog: Burst operations log file. By default '<originRealm>.launcher.burst'. Empty string or "null" name, to disable.
+ Warning: there is no rotation for log files (use logrotate or whatever). Output: dot (.) for each
+ burst message sent/pushed, cross (x) for popped ones, and order number when multiple of 1% of burst
+ list size, plus OTA requests when changed
+
+-->
+
read
# diameter module
-./diameter/launcher/DEPLOY.sh
+./diameter/launcher/DEPLOY_clientAndServer.sh
# ...
# ...
* @param cer Capabilities-Exchange-Request message (encoded) for the client-sessions bind.
* @param dwr Device-Watchdog-Request message (encoded) for the client-sessions keep-alive.
*/
- void setCERandDWR(const anna::DataBlock & cer, const anna::DataBlock & dwr) throw(anna::RuntimeException);
+ void setClientCERandDWR(const anna::DataBlock & cer, const anna::DataBlock & dwr) throw(anna::RuntimeException);
+ /**
+ * Sets CER and DWR diameter messages to be used over created client-sessions. If empty string is provided for CER and/or DWR, default version will be configured.
+ * Its recommended to set this global configuration although it is possible to configure each client-session separately.
+ *
+ * @param cer Capabilities-Exchange-Request xml message path file for the client-sessions bind. If empty string is provided (default), a default version for CER will be encoded.
+ * @param dwr Device-Watchdog-Request xml message path file for the client-sessions keep-alive. If empty string is provided (default), a default version for DWR will be encoded.
+ */
+ void setClientCERandDWR(const std::string & cer = "", const std::string & dwr = "") throw(anna::RuntimeException);
/**
* Sets the watchdog period (DWR) for client-sessions.
*/
void setEngine(Engine *e) throw() { a_engine = e; }
-// /**
-// * Gets the diameter::comm::Engine
-// * @return Diameter::comm::Engine
-// */
-// Engine *getEngine() const throw() { return a_engine; }
+ /**
+ * Gets the diameter::comm::Engine
+ * @return Diameter::comm::Engine
+ */
+ Engine *getEngine() const throw() { return a_engine; }
/**
* Add a server to the entity and create all the servers configured at #setSocketsPerDiameterServer within that server.
*/
void setEngine(Engine *e) throw() { a_engine = e; }
-// /**
-// * Gets the diameter::comm::Engine
-// * @return Diameter::comm::Engine
-// */
-// Engine *getEngine() const throw() { return a_engine; }
-
// getters
+ /**
+ * Gets the diameter::comm::Engine
+ * @return Diameter::comm::Engine
+ */
+ Engine *getEngine() const throw() { return a_engine; }
+
/**
* Gets the local server key
* @return LocalServer key
}
} else if(Logger::isActive(Logger::Warning) == true) {
string msg(asString());
- msg += " | Not connected to applicatino yet";
+ msg += " | Not connected to application yet";
Logger::warning(msg, ANNA_FILE_LOCATION);
}
}
void Engine::releaseClientSession(ClientSession *clientSession) throw() { a_clientSessionsRecycler.release(clientSession); }
-void Engine::setCERandDWR(const anna::DataBlock & cer, const anna::DataBlock & dwr) throw(anna::RuntimeException) {
+void Engine::setClientCERandDWR(const anna::DataBlock & cer, const anna::DataBlock & dwr) throw(anna::RuntimeException) {
if(codec::functions::getCommandId(cer) != helpers::base::COMMANDID__Capabilities_Exchange_Request) {
throw anna::RuntimeException("The message provided as 'CER' is not a Capabilities-Exchange-Request", ANNA_FILE_LOCATION);
}
a_dwr = dwr;
}
-//void Engine::setCEAandDWA(const anna::DataBlock & cea, const anna::DataBlock & dwa) throw(anna::RuntimeException) {
-// if (codec::functions::getCommandId(cea) != helpers::base::COMMANDID__Capabilities_Exchange_Answer) {
-// throw anna::RuntimeException("The message provided as 'CEA' is not a Capabilities-Exchange-Answer", ANNA_FILE_LOCATION);
-// }
-//
-// if (codec::functions::getCommandId(dwa) != helpers::base::COMMANDID__Device_Watchdog_Answer) {
-// throw anna::RuntimeException("The message provided as 'DWA' is not a Device-Watchdog-Answer", ANNA_FILE_LOCATION);
-// }
-//
-// a_cea = cea;
-// a_dwa = dwa;
-//}
+void Engine::setClientCERandDWR(const std::string & cer, const std::string & dwr) throw(anna::RuntimeException) {
+
+ // Check for base protocol codec engine:
+ if (!getBaseProtocolCodecEngine())
+ throw anna::RuntimeException("Use diameter::comm::Engine::setBaseProtocolCodecEngine() to allow base protocol messages encoding, or use setClientCERandDWR(const anna::DataBlock & cer, const anna::DataBlock & dwr) which expect externally encoded messages", ANNA_FILE_LOCATION);
+
+ // Build CER
+ // <CER> ::= < Diameter Header: 257, REQ >
+ // { Origin-Host } 264 diameterIdentity
+ // { Origin-Realm } 296 idem
+ // 1* { Host-IP-Address } 257, address
+ // { Vendor-Id } 266 Unsigned32
+ // { Product-Name } 269 UTF8String
+ // [Origin-State-Id] 278 Unsigned32
+ // * [ Supported-Vendor-Id ] 265 Unsigned32
+ // * [ Auth-Application-Id ] 258 Unsigned32
+ // * [Acct-Application-Id] 259 Unsigned32
+ anna::diameter::codec::Message diameterCER(getBaseProtocolCodecEngine());
+ int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
+ std::string OH = getHost();
+ std::string OR = getRealm();
+ std::string hostIP = anna::functions::getHostnameIP(); // Address
+ int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
+ std::string productName = "ANNA Diameter Client"; // UTF8String
+ bool encodeDefault = false;
+
+ if (cer != "") {
+ try {
+ diameterCER.loadXML(cer);
+ } catch(anna::RuntimeException &ex) {
+ //ex.trace();
+ encodeDefault = true;
+ LOGWARNING(anna::Logger::warning("CER file not found or unable to parse. Encoding harcoded default version ...", ANNA_FILE_LOCATION));
+ }
+ }
+ else {
+ encodeDefault = true;
+ }
+
+ if(encodeDefault) {
+ diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
+ diameterCER.setApplicationId(applicationId);
+ diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
+ diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
+ diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str()); // supported by Address class, anyway is better to provide "1|<ip address>"
+ diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
+ diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
+ diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
+ }
+
+ // Build DWR
+ // <DWR> ::= < Diameter Header: 280, REQ >
+ // { Origin-Host }
+ // { Origin-Realm }
+ anna::diameter::codec::Message diameterDWR(getBaseProtocolCodecEngine());
+ encodeDefault = false;
+
+ if (dwr != "") {
+ try {
+ diameterDWR.loadXML(dwr);
+ } catch(anna::RuntimeException &ex) {
+ //ex.trace();
+ encodeDefault = true;
+ LOGWARNING(anna::Logger::warning("DWR file not found or unable to parse. Encoding harcoded default version ...", ANNA_FILE_LOCATION));
+ }
+ }
+ else {
+ encodeDefault = true;
+ }
+
+ if(encodeDefault) {
+ diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
+ diameterDWR.setApplicationId(applicationId);
+ diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
+ diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
+ }
+
+ // Assignment for internal encoded versions:
+ setClientCERandDWR(diameterCER.code(), diameterDWR.code());
+}
void Engine::setWatchdogPeriod(const anna::Millisecond & wp) throw(anna::RuntimeException) {
if(wp < ClientSession::DefaultWatchdogPeriod) {