RTBKit  0.9
Open-source framework to create real-time ad bidding systems.
soa/service/statsd_connector.cc
00001 /* statsd_connector.cc
00002    Nicolas Kruchten
00003    Copyright (c) 2011 Datacratic.  All rights reserved.
00004 
00005 */
00006 
00007 #include "soa/service/statsd_connector.h"
00008 #include "ace/INET_Addr.h"
00009 #include "jml/arch/exception.h"
00010 #include "jml/arch/format.h"
00011 #include <iostream>
00012 
00013 
00014 using namespace std;
00015 using namespace ML;
00016 
00017 namespace Datacratic {
00018 
00019 
00020 /*****************************************************************************/
00021 /* STATSD CONNECTOR                                                          */
00022 /*****************************************************************************/
00023 
00024 StatsdConnector::
00025 StatsdConnector()
00026 {
00027 }
00028 
00029 StatsdConnector::
00030 StatsdConnector(const string& statsdAddr)
00031 {
00032     open(statsdAddr);
00033 }
00034 
00035 StatsdConnector::
00036 ~StatsdConnector()
00037 {
00038     sckt.close();
00039 }
00040 
00041 void
00042 StatsdConnector::
00043 open(const string& statsdAddr)
00044 {
00045     sckt.close();
00046     addr = ACE_INET_Addr(statsdAddr.c_str());
00047 
00048     if(sckt.open(addr) == -1)
00049         throw Exception("could not create statsd udp socket");
00050 }
00051     
00052 void
00053 StatsdConnector::
00054 incrementCounter(const char* counterName, float sampleRate, int value)
00055 {
00056     if (sampleRate < 1.0 && ((random() % 10000) / 10000.0) >= sampleRate)
00057         return;
00058 
00059     char msgBuf[1024];
00060     int res = snprintf(msgBuf, 1024, "%s:%d|c|@%.2f", counterName, value,
00061                        sampleRate);
00062     if (res >= 1024) {
00063         cerr << "invalid statsd counter name: " << counterName << endl;
00064         return;
00065     }
00066     
00067     int sendRes = sckt.send(msgBuf, res, addr, MSG_DONTWAIT);
00068     if (sendRes == -1) {
00069         cerr << "statsd message failure: " << strerror(errno)
00070              << endl;
00071     }
00072 }
00073 
00074 void
00075 StatsdConnector::
00076 recordGauge(const char* counterName, float sampleRate, float value)
00077 {
00078     if (sampleRate < 1.0 && ((random() % 10000) / 10000.0) >= sampleRate)
00079         return;
00080 
00081     char msgBuf[1024];
00082     int res = snprintf(msgBuf, 1024, "%s:%f|ms", counterName, value);
00083 
00084     if (res >= 1024) {
00085         cerr << "invalid statsd counter name: " << counterName << endl;
00086         return;
00087     }
00088     
00089     int sendRes = sckt.send(msgBuf, res, addr, MSG_DONTWAIT);
00090     if (sendRes == -1) {
00091         cerr << "statsd message failure: " << strerror(errno)
00092              << endl;
00093     }
00094 }
00095 
00096 } // namespace Datacratic
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator