stats_mgr.h 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. // Copyright (C) 2012 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #ifndef __STATS_MGR_H
  15. #define __STATS_MGR_H
  16. #include <iostream>
  17. #include <map>
  18. #include <boost/noncopyable.hpp>
  19. #include <boost/shared_ptr.hpp>
  20. #include <boost/multi_index_container.hpp>
  21. #include <boost/multi_index/hashed_index.hpp>
  22. #include <boost/multi_index/sequenced_index.hpp>
  23. #include <boost/multi_index/global_fun.hpp>
  24. #include <boost/multi_index/mem_fun.hpp>
  25. #include <boost/date_time/posix_time/posix_time.hpp>
  26. #include <exceptions/exceptions.h>
  27. namespace isc {
  28. namespace perfdhcp {
  29. /// \brief Statistics Manager
  30. ///
  31. /// This class template is a storage for various performance statistics
  32. /// collected during performance tests execution with perfdhcp tool.
  33. ///
  34. /// Statistics Manager holds lists of sent and received packets and
  35. /// groups them into exchanges. For example: DHCPDISCOVER message and
  36. /// corresponding DHCPOFFER messages belong to one exchange, DHCPREQUEST
  37. /// and corresponding DHCPACK message belong to another exchange etc.
  38. /// In order to update statistics for a particular exchange type, client
  39. /// class passes sent and received packets. Internally, Statistics Manager
  40. /// tries to match transaction id of received packet with sent packet
  41. /// stored on the list of sent packets. When packets are matched the
  42. /// round trip time can be calculated.
  43. ///
  44. /// \tparam T class representing DHCPv4 or DHCPv6 packet.
  45. template <class T>
  46. class StatsMgr : public boost::noncopyable {
  47. public:
  48. /// \brief Custom Counter
  49. ///
  50. /// This class represents custom statistics counters. Client class
  51. /// may create unlimited number of counters. Such counters are
  52. /// being stored in map in Statistics Manager and access using
  53. /// unique string key.
  54. class CustomCounter {
  55. public:
  56. /// \brief Constructor.
  57. ///
  58. /// This constructor sets counter name. This name is used in
  59. /// log file to report value of each counter.
  60. ///
  61. /// \param name name of the counter used in log file.
  62. CustomCounter(const std::string& name) :
  63. counter_(0),
  64. name_(name) { };
  65. /// \brief Increment operator.
  66. const CustomCounter& operator++() {
  67. ++counter_;
  68. return *this;
  69. }
  70. /// \brief Increment operator.
  71. const CustomCounter& operator++(int) {
  72. CustomCounter& this_counter(*this);
  73. operator++();
  74. return this_counter;
  75. }
  76. /// \brief Return counter value.
  77. ///
  78. /// Method returns counter value.
  79. ///
  80. /// \return counter value.
  81. unsigned long long getValue() const {
  82. return counter_;
  83. }
  84. /// \brief Return counter name.
  85. ///
  86. /// Method returns counter name.
  87. ///
  88. /// \return counter name.
  89. const std::string& getName() const {
  90. return name_;
  91. }
  92. private:
  93. /// \brief Default constructor.
  94. ///
  95. /// Default constrcutor is private because we don't want client
  96. /// class to call it because we want client class to specify
  97. /// counter's name.
  98. CustomCounter() { };
  99. unsigned long long counter_; ///< Counter's value.
  100. std::string name_; ///< Counter's name.
  101. };
  102. typedef typename boost::shared_ptr<CustomCounter> CustomCounterPtr;
  103. /// DHCP packet exchange types.
  104. enum ExchangeType {
  105. XCHG_DO, ///< DHCPv4 DISCOVER-OFFER
  106. XCHG_RA, ///< DHCPv4 REQUEST-ACK
  107. XCHG_SA, ///< DHCPv6 SOLICIT-ADVERTISE
  108. XCHG_RR ///< DHCPv6 REQUEST-REPLY
  109. };
  110. /// \brief Exchange Statistics.
  111. ///
  112. /// This class collects statistics for exchanges. Parent class
  113. /// may define number of different packet exchanges like:
  114. /// DHCPv4 DISCOVER-OFFER, DHCPv6 SOLICIT-ADVERTISE etc. Performance
  115. /// statistics will be collected for each of those separately in
  116. /// corresponding instance of ExchangeStats.
  117. class ExchangeStats {
  118. public:
  119. /// \brief Hash transaction id of the packet.
  120. ///
  121. /// Function hashes transaction id of the packet. Hashing is
  122. /// non-unique. Many packets may have the same hash value and thus
  123. /// they belong to the same packet buckets. Packet buckets are
  124. /// used for unordered packets search with multi index container.
  125. ///
  126. /// \param packet packet which transaction id is to be hashed.
  127. /// \throw isc::BadValue if packet is null.
  128. /// \return transaction id hash.
  129. static uint32_t hashTransid(const boost::shared_ptr<T> packet) {
  130. if (!packet) {
  131. isc_throw(BadValue, "Packet is null");
  132. }
  133. return packet->getTransid() & 1023;
  134. }
  135. /// \brief List of packets (sent or received).
  136. ///
  137. /// List of packets based on multi index container allows efficient
  138. /// search of packets based on their sequence (order in which they
  139. /// were inserted) as well as based on packet transaction id.
  140. typedef boost::multi_index_container<
  141. boost::shared_ptr<T>,
  142. boost::multi_index::indexed_by<
  143. boost::multi_index::sequenced<>,
  144. boost::multi_index::hashed_non_unique<
  145. boost::multi_index::global_fun<
  146. boost::shared_ptr<T>,
  147. uint32_t,
  148. &ExchangeStats::hashTransid
  149. >
  150. >,
  151. boost::multi_index::hashed_non_unique<
  152. boost::multi_index::const_mem_fun<
  153. T,
  154. uint32_t,
  155. &T::getTransid
  156. >
  157. >
  158. >
  159. > PktList;
  160. /// Packet list iterator for sequencial access to elements.
  161. typedef typename PktList::const_iterator PktListIterator;
  162. /// Packet list index to search packets using transaction id hash.
  163. typedef typename PktList::template nth_index<1>::type
  164. PktListTransidHashIndex;
  165. /// Packet list iterator to access packets using transaction id hash.
  166. typedef typename PktListTransidHashIndex::const_iterator
  167. PktListTransidHashIterator;
  168. /// Packet list index to search packets using transaction id.
  169. typedef typename PktList::template nth_index<2>::type
  170. PktListTransidIndex;
  171. /// Packet list iterator to access packets using transaction id.
  172. typedef typename PktListTransidIndex::const_iterator
  173. PktListTransidIterator;
  174. /// \brief Constructor
  175. ///
  176. /// \param xchg_type exchange type
  177. ExchangeStats(const ExchangeType xchg_type)
  178. : xchg_type_(xchg_type),
  179. min_delay_(std::numeric_limits<double>::max()),
  180. max_delay_(0.),
  181. sum_delay_(0.),
  182. orphans_(0),
  183. square_sum_delay_(0.),
  184. ordered_lookups_(0),
  185. unordered_lookup_size_sum_(0),
  186. unordered_lookups_(0),
  187. sent_packets_num_(0),
  188. rcvd_packets_num_(0) {
  189. sent_packets_cache_ = sent_packets_.begin();
  190. }
  191. /// \brief Add new packet to list of sent packets.
  192. ///
  193. /// Method adds new packet to list of sent packets.
  194. ///
  195. /// \param packet packet object to be added.
  196. /// \throw isc::BadValue if packet is null.
  197. void appendSent(const boost::shared_ptr<T> packet) {
  198. if (!packet) {
  199. isc_throw(BadValue, "Packet is null");
  200. }
  201. ++sent_packets_num_;
  202. sent_packets_.template get<0>().push_back(packet);
  203. }
  204. /// \brief Add new packet to list of received packets.
  205. ///
  206. /// Method adds new packet to list of received packets.
  207. ///
  208. /// \param packet packet object to be added.
  209. /// \throw isc::BadValue if packet is null.
  210. void appendRcvd(const boost::shared_ptr<T> packet) {
  211. if (!packet) {
  212. isc_throw(BadValue, "Packet is null");
  213. }
  214. ++rcvd_packets_num_;
  215. rcvd_packets_.push_back(packet);
  216. }
  217. /// \brief Update delay counters.
  218. ///
  219. /// Method updates delay counters based on timestamps of
  220. /// sent and received packets.
  221. ///
  222. /// \param sent_packet sent packet
  223. /// \param rcvd_packet received packet
  224. /// \throw isc::BadValue if sent or received packet is null.
  225. /// \throw isc::Unexpected if failed to calculate timestamps
  226. void updateDelays(const boost::shared_ptr<const T> sent_packet,
  227. const boost::shared_ptr<const T> rcvd_packet) {
  228. if (!sent_packet) {
  229. isc_throw(BadValue, "Sent packet is null");
  230. }
  231. if (!rcvd_packet) {
  232. isc_throw(BadValue, "Received packet is null");
  233. }
  234. boost::posix_time::ptime sent_time = sent_packet->getTimestamp();
  235. boost::posix_time::ptime rcvd_time = rcvd_packet->getTimestamp();
  236. if (sent_time.is_not_a_date_time() ||
  237. rcvd_time.is_not_a_date_time()) {
  238. isc_throw(Unexpected,
  239. "Timestamp must be set for sent and "
  240. "received packet to measure RTT");
  241. }
  242. boost::posix_time::time_period period(sent_time, rcvd_time);
  243. // We don't bother calculating deltas in nanoseconds. It is much
  244. // more convenient to use seconds instead because we are going to
  245. // sum them up.
  246. double delta =
  247. static_cast<double>(period.length().total_nanoseconds()) / 1e9;
  248. if (delta < 0) {
  249. isc_throw(Unexpected, "Sent packet's timestamp must not be "
  250. "greater than received packet's timestamp");
  251. }
  252. // Record the minimum delay between sent and received packets.
  253. if (delta < min_delay_) {
  254. min_delay_ = delta;
  255. }
  256. // Record the maximum delay between sent and received packets.
  257. if (delta > max_delay_) {
  258. max_delay_ = delta;
  259. }
  260. // Update delay sum and square sum. That will be used to calculate
  261. // mean delays.
  262. sum_delay_ += delta;
  263. square_sum_delay_ += delta * delta;
  264. }
  265. /// \brief Find packet on the list of sent packets.
  266. ///
  267. /// Method finds packet with specified transaction id on the list
  268. /// of sent packets. It is used to match received packet with
  269. /// corresponding sent packet.
  270. /// Since packets from the server most often come in the same order
  271. /// as they were sent by client, this method will first check if
  272. /// next sent packet matches. If it doesn't, function will search
  273. /// the packet using indexing by transaction id. This reduces
  274. /// packet search time significantly.
  275. ///
  276. /// \param rcvd_packet received packet to be matched with sent packet.
  277. /// \throw isc::BadValue if received packet is null.
  278. /// \return packet having specified transaction or NULL if packet
  279. /// not found
  280. boost::shared_ptr<T> findSent(const boost::shared_ptr<T> rcvd_packet) {
  281. if (!rcvd_packet) {
  282. isc_throw(BadValue, "Received packet is null");
  283. }
  284. if (sent_packets_.size() == 0) {
  285. // List of sent packets is empty so there is no sense
  286. // to continue looking fo the packet. It also means
  287. // that the received packet we got has no corresponding
  288. // sent packet so orphans counter has to be updated.
  289. ++orphans_;
  290. return boost::shared_ptr<T>();
  291. } else if (sent_packets_cache_ == sent_packets_.end()) {
  292. // Even if there are still many unmatched packets on the
  293. // list we might hit the end of it because of unordered
  294. // lookups. The next logical step is to reset cache.
  295. sent_packets_cache_ = sent_packets_.begin();
  296. }
  297. // With this variable we will be signalling success or failure
  298. // to find the packet.
  299. bool packet_found = false;
  300. // Most likely responses are sent from the server in the same
  301. // order as client's requests to the server. We are caching
  302. // next sent packet and first try to match it with the next
  303. // incoming packet. We are successful if there is no
  304. // packet drop or out of order packets sent. This is actually
  305. // the fastest way to look for packets.
  306. if ((*sent_packets_cache_)->getTransid() == rcvd_packet->getTransid()) {
  307. ++ordered_lookups_;
  308. packet_found = true;
  309. } else {
  310. // If we are here, it means that we were unable to match the
  311. // next incoming packet with next sent packet so we need to
  312. // take a little more expensive approach to look packets using
  313. // alternative index (transaction id & 1023).
  314. PktListTransidHashIndex& idx = sent_packets_.template get<1>();
  315. // Packets are grouped using trasaction id masked with value
  316. // of 1023. For instance, packets with transaction id equal to
  317. // 1, 1024 ... will belong to the same group (a.k.a. bucket).
  318. // When using alternative index we don't find the packet but
  319. // bucket of packets and we need to iterate through the bucket
  320. // to find the one that has desired transaction id.
  321. std::pair<PktListTransidHashIterator,PktListTransidHashIterator> p =
  322. idx.equal_range(hashTransid(rcvd_packet));
  323. // We want to keep statistics of unordered lookups to make
  324. // sure that there is a right balance between number of
  325. // unordered lookups and ordered lookups. If number of unordered
  326. // lookups is high it may mean that many packets are lost or
  327. // sent out of order.
  328. ++unordered_lookups_;
  329. // We also want to keep the mean value of the bucket. The lower
  330. // bucket size the better. If bucket sizes appear to big we
  331. // might want to increase number of buckets.
  332. unordered_lookup_size_sum_ += std::distance(p.first, p.second);
  333. for (PktListTransidHashIterator it = p.first; it != p.second;
  334. ++it) {
  335. if ((*it)->getTransid() == rcvd_packet->getTransid()) {
  336. packet_found = true;
  337. sent_packets_cache_ =
  338. sent_packets_.template project<0>(it);
  339. break;
  340. }
  341. }
  342. }
  343. if (!packet_found) {
  344. // If we are here, it means that both ordered lookup and
  345. // unordered lookup failed. Searched packet is not on the list.
  346. ++orphans_;
  347. return boost::shared_ptr<T>();
  348. }
  349. boost::shared_ptr<T> sent_packet(*sent_packets_cache_);
  350. // If packet was found, we assume it will be never searched
  351. // again. We want to delete this packet from the list to
  352. // improve performance of future searches.
  353. sent_packets_cache_ = eraseSent(sent_packets_cache_);
  354. return sent_packet;
  355. }
  356. /// \brief Return minumum delay between sent and received packet.
  357. ///
  358. /// Method returns minimum delay between sent and received packet.
  359. ///
  360. /// \return minimum delay between packets.
  361. double getMinDelay() const { return min_delay_; }
  362. /// \brief Return maxmimum delay between sent and received packet.
  363. ///
  364. /// Method returns maximum delay between sent and received packet.
  365. ///
  366. /// \return maximum delay between packets.
  367. double getMaxDelay() const { return max_delay_; }
  368. /// \brief Return avarage packet delay.
  369. ///
  370. /// Method returns average packet delay. If no packets have been
  371. /// received for this exchange avg delay can't be calculated and
  372. /// thus method throws exception.
  373. ///
  374. /// \throw isc::InvalidOperation if no packets for this exchange
  375. /// have been received yet.
  376. /// \return average packet delay.
  377. double getAvgDelay() const {
  378. if (sum_delay_ == 0) {
  379. isc_throw(InvalidOperation, "no packets received");
  380. }
  381. return sum_delay_ / rcvd_packets_num_;
  382. }
  383. /// \brief Return standard deviation of packet delay.
  384. ///
  385. /// Method returns standard deviation of packet delay. If no
  386. /// packets have been received for this exchange, the standard
  387. /// deviation can't be calculated and thus method throws
  388. /// exception.
  389. ///
  390. /// \throw isc::InvalidOperation if number of received packets
  391. /// for the exchange is equal to zero.
  392. /// \return standard deviation of packet delay.
  393. double getStdDevDelay() const {
  394. if (rcvd_packets_num_ == 0) {
  395. isc_throw(InvalidOperation, "no packets received");
  396. }
  397. return sqrt(square_sum_delay_ / rcvd_packets_num_ -
  398. getAvgDelay() * getAvgDelay());
  399. }
  400. /// \brief Return number of orphant packets.
  401. ///
  402. /// Method returns number of received packets that had no matching
  403. /// sent packet. It is possible that such packet was late or not
  404. /// for us.
  405. ///
  406. /// \return number of orphant received packets.
  407. unsigned long long getOrphans() const { return orphans_; }
  408. /// \brief Return average unordered lookup set size.
  409. ///
  410. /// Method returns average unordered lookup set size.
  411. /// This value changes every time \ref ExchangeStats::findSent
  412. /// function performs unordered packet lookup.
  413. ///
  414. /// \throw isc::InvalidOperation if there have been no unordered
  415. /// lookups yet.
  416. /// \return average unordered lookup set size.
  417. double getAvgUnorderedLookupSetSize() const {
  418. if (unordered_lookups_ == 0) {
  419. isc_throw(InvalidOperation, "no unordered lookups");
  420. }
  421. return static_cast<double>(unordered_lookup_size_sum_) /
  422. static_cast<double>(unordered_lookups_);
  423. }
  424. /// \brief Return number of unordered sent packets lookups
  425. ///
  426. /// Method returns number of unordered sent packet lookups.
  427. /// Unordered lookup is used when received packet was sent
  428. /// out of order by server - transaction id of received
  429. /// packet does not match transaction id of next sent packet.
  430. ///
  431. /// \return number of unordered lookups.
  432. unsigned long long getUnorderedLookups() const { return unordered_lookups_; }
  433. /// \brief Return number of ordered sent packets lookups
  434. ///
  435. /// Method returns number of ordered sent packet lookups.
  436. /// Ordered lookup is used when packets are received in the
  437. /// same order as they were sent to the server.
  438. /// If packets are skipped or received out of order, lookup
  439. /// function will use unordered lookup (with hash table).
  440. ///
  441. /// \return number of ordered lookups.
  442. unsigned long long getOrderedLookups() const { return ordered_lookups_; }
  443. /// \brief Return total number of sent packets
  444. ///
  445. /// Method returns total number of sent packets.
  446. ///
  447. /// \return number of sent packets.
  448. unsigned long long getSentPacketsNum() const {
  449. return sent_packets_num_;
  450. }
  451. /// \brief Return total number of received packets
  452. ///
  453. /// Method returns total number of received packets.
  454. ///
  455. /// \return number of received packets.
  456. unsigned long long getRcvdPacketsNum() const {
  457. return rcvd_packets_num_;
  458. }
  459. //// \brief Print timestamps for sent and received packets.
  460. ///
  461. /// Method prints timestamps for all sent and received packets for
  462. /// packet exchange.
  463. ///
  464. /// \throw isc::InvalidOperation if found packet with no timestamp set.
  465. void printTimestamps() {
  466. // Iterate through all received packets.
  467. for (PktListIterator it = rcvd_packets_.begin();
  468. it != rcvd_packets_.end();
  469. ++it) {
  470. boost::shared_ptr<T> rcvd_packet = *it;
  471. // Search for corresponding sent packet using transaction id
  472. // of received packet.
  473. PktListTransidIndex& idx = archived_packets_.template get<2>();
  474. PktListTransidIterator it_archived =
  475. idx.find(rcvd_packet->getTransid());
  476. // This should not happen that there is no corresponding
  477. // sent packet. If it does however, we just drop the packet.
  478. if (it_archived != idx.end()) {
  479. boost::shared_ptr<T> sent_packet = *it_archived;
  480. // Get sent and received packet times.
  481. boost::posix_time::ptime sent_time =
  482. sent_packet->getTimestamp();
  483. boost::posix_time::ptime rcvd_time =
  484. rcvd_packet->getTimestamp();
  485. // All sent and received packets should have timestamps
  486. // set but if there is a bug somewhere and packet does
  487. // not have timestamp we want to catch this here.
  488. if (sent_time.is_not_a_date_time() ||
  489. rcvd_time.is_not_a_date_time()) {
  490. isc_throw(InvalidOperation, "packet time is not set");
  491. }
  492. // Calculate durations of packets from beginning of epoch.
  493. boost::posix_time::ptime
  494. epoch_time(boost::posix_time::min_date_time);
  495. boost::posix_time::time_period
  496. sent_period(epoch_time, sent_time);
  497. boost::posix_time::time_period
  498. rcvd_period(epoch_time, rcvd_time);
  499. // Print timestamps for sent and received packet.
  500. printf("sent/received times: %s / %s\n",
  501. boost::posix_time::to_iso_string(sent_period.length()).c_str(),
  502. boost::posix_time::to_iso_string(rcvd_period.length()).c_str());
  503. }
  504. }
  505. }
  506. private:
  507. /// \brief Private default constructor.
  508. ///
  509. /// Default constructor is private because we want the client
  510. /// class to specify exchange type explicitely.
  511. ExchangeStats();
  512. /// \brief Erase packet from the list of sent packets.
  513. ///
  514. /// Method erases packet from the list of sent packets.
  515. ///
  516. /// \param it iterator pointing to packet to be erased.
  517. /// \return iterator pointing to packet following erased
  518. /// packet or sent_packets_.end() if packet not found.
  519. PktListIterator eraseSent(const PktListIterator it) {
  520. // We don't want to keep list of all sent packets
  521. // because it will affect packet lookup performance.
  522. // If packet is matched with received packet we
  523. // move it to list of archived packets. List of
  524. // archived packets may be used for diagnostics
  525. // when test is completed.
  526. archived_packets_.push_back(*it);
  527. return sent_packets_.template get<0>().erase(it);
  528. }
  529. ExchangeType xchg_type_; ///< Packet exchange type.
  530. PktList sent_packets_; ///< List of sent packets.
  531. /// Iterator pointing to the packet on sent list which will most
  532. /// likely match next received packet. This is based on the
  533. /// assumption that server responds in order to incoming packets.
  534. PktListIterator sent_packets_cache_;
  535. PktList rcvd_packets_; ///< List of received packets.
  536. /// List of archived packets. All sent packets that have
  537. /// been matched with received packet are moved to this
  538. /// list for diagnostics purposes.
  539. PktList archived_packets_;
  540. double min_delay_; ///< Minimum delay between sent
  541. ///< and received packets.
  542. double max_delay_; ///< Maximum delay between sent
  543. ///< and received packets.
  544. double sum_delay_; ///< Sum of delays between sent
  545. ///< and received packets.
  546. double square_sum_delay_; ///< Square sum of delays between
  547. ///< sent and recived packets.
  548. unsigned long long orphans_; ///< Number of orphant received packets.
  549. /// Sum of unordered lookup sets. Needed to calculate mean size of
  550. /// lookup set. It is desired that number of unordered lookups is
  551. /// minimal for performance reasons. Tracking number of lookups and
  552. /// mean size of the lookup set should give idea of packets serach
  553. /// complexity.
  554. unsigned long long unordered_lookup_size_sum_;
  555. unsigned long long unordered_lookups_; ///< Number of unordered sent packets
  556. ///< lookups.
  557. unsigned long long ordered_lookups_; ///< Number of ordered sent packets
  558. ///< lookups.
  559. unsigned long long sent_packets_num_; ///< Total number of sent packets.
  560. unsigned long long rcvd_packets_num_; ///< Total number of received packets.
  561. };
  562. /// Pointer to ExchangeStats.
  563. typedef boost::shared_ptr<ExchangeStats> ExchangeStatsPtr;
  564. /// Map containing all specified exchange types.
  565. typedef typename std::map<ExchangeType, ExchangeStatsPtr> ExchangesMap;
  566. /// Iterator poiting to \ref ExchangesMap
  567. typedef typename ExchangesMap::const_iterator ExchangesMapIterator;
  568. /// Map containing custom counters.
  569. typedef typename std::map<std::string, CustomCounterPtr> CustomCountersMap;
  570. /// Iterator for \ref CustomCountersMap.
  571. typedef typename CustomCountersMap::const_iterator CustomCountersMapIterator;
  572. /// \brief Constructor.
  573. StatsMgr()
  574. : exchanges_(),
  575. custom_counters_() {
  576. }
  577. /// \brief Specify new exchange type.
  578. ///
  579. /// This method creates new \ref ExchangeStats object that will
  580. /// collect statistics data from packets exchange of the specified
  581. /// type.
  582. ///
  583. /// \param xchg_type exchange type.
  584. /// \throw isc::BadValue if exchange of specified type exists.
  585. void addExchangeStats(const ExchangeType xchg_type) {
  586. if (exchanges_.find(xchg_type) != exchanges_.end()) {
  587. isc_throw(BadValue, "Exchange of specified type already added.");
  588. }
  589. exchanges_[xchg_type] = ExchangeStatsPtr(new ExchangeStats(xchg_type));
  590. }
  591. /// \brief Add named custom uint64 counter.
  592. ///
  593. /// Method creates new named counter and stores in counter's map under
  594. /// key specified here as short_name.
  595. ///
  596. /// \param short_name key to use to access counter in the map.
  597. /// \param long_name name of the counter presented in the log file.
  598. void addCustomCounter(const std::string& short_name,
  599. const std::string& long_name) {
  600. if (custom_counters_.find(short_name) != custom_counters_.end()) {
  601. isc_throw(BadValue,
  602. "Custom counter " << short_name << " already added.");
  603. }
  604. custom_counters_[short_name] =
  605. CustomCounterPtr(new CustomCounter(long_name));
  606. }
  607. /// \brief Return specified counter.
  608. ///
  609. /// Method returns specified counter.
  610. ///
  611. /// \param counter_key key poiting to the counter in the counters map.
  612. /// \return pointer to specified counter object.
  613. CustomCounterPtr getCounter(const std::string& counter_key) {
  614. CustomCountersMapIterator it = custom_counters_.find(counter_key);
  615. if (it == custom_counters_.end()) {
  616. isc_throw(BadValue,
  617. "Custom counter " << counter_key << "does not exist");
  618. }
  619. return it->second;
  620. }
  621. /// \brief Increment specified counter.
  622. ///
  623. /// Increement counter value by one.
  624. ///
  625. /// \param counter_key key poitinh to the counter in the counters map.
  626. /// \return pointer to specified counter after incrementation.
  627. const CustomCounter& IncrementCounter(const std::string& counter_key) {
  628. CustomCounterPtr counter = getCounter(counter_key);
  629. return ++(*counter);
  630. }
  631. /// \brief Adds new packet to the sent packets list.
  632. ///
  633. /// Method adds new packet to the sent packets list.
  634. /// Packets are added to the list sequentially and
  635. /// most often read sequentially.
  636. ///
  637. /// \param xchg_type exchange type.
  638. /// \param packet packet to be added to the list
  639. /// \throw isc::BadValue if invalid exchange type specified or
  640. /// packet is null.
  641. void passSentPacket(const ExchangeType xchg_type,
  642. const boost::shared_ptr<T> packet) {
  643. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  644. xchg_stats->appendSent(packet);
  645. }
  646. /// \brief Add new received packet and match with sent packet.
  647. ///
  648. /// Method adds new packet to the list of received packets. It
  649. /// also searches for corresponding packet on the list of sent
  650. /// packets. When packets are matched the statistics counters
  651. /// are updated accordingly for the particular exchange type.
  652. ///
  653. /// \param xchg_type exchange type.
  654. /// \param packet received packet
  655. /// \throw isc::BadValue if invalid exchange type specified
  656. /// or packet is null.
  657. /// \throw isc::Unexpected if corresponding packet was not
  658. /// found on the list of sent packets.
  659. void passRcvdPacket(const ExchangeType xchg_type,
  660. const boost::shared_ptr<T> packet) {
  661. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  662. boost::shared_ptr<T> sent_packet
  663. = xchg_stats->findSent(packet);
  664. if (sent_packet) {
  665. xchg_stats->updateDelays(sent_packet, packet);
  666. xchg_stats->appendRcvd(packet);
  667. }
  668. }
  669. /// \brief Return minumum delay between sent and received packet.
  670. ///
  671. /// Method returns minimum delay between sent and received packet
  672. /// for specified exchange type.
  673. ///
  674. /// \param xchg_type exchange type.
  675. /// \throw isc::BadValue if invalid exchange type specified.
  676. /// \return minimum delay between packets.
  677. double getMinDelay(const ExchangeType xchg_type) const {
  678. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  679. return xchg_stats->getMinDelay();
  680. }
  681. /// \brief Return maxmimum delay between sent and received packet.
  682. ///
  683. /// Method returns maximum delay between sent and received packet
  684. /// for specified exchange type.
  685. ///
  686. /// \param xchg_type exchange type.
  687. /// \throw isc::BadValue if invalid exchange type specified.
  688. /// \return maximum delay between packets.
  689. double getMaxDelay(const ExchangeType xchg_type) const {
  690. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  691. return xchg_stats->getMaxDelay();
  692. }
  693. /// \brief Return avarage packet delay.
  694. ///
  695. /// Method returns average packet delay for specified
  696. /// exchange type.
  697. ///
  698. /// \return average packet delay.
  699. double getAvgDelay(const ExchangeType xchg_type) const {
  700. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  701. return xchg_stats->getAvgDelay();
  702. }
  703. /// \brief Return standard deviation of packet delay.
  704. ///
  705. /// Method returns standard deviation of packet delay
  706. /// for specified exchange type.
  707. ///
  708. /// \return standard deviation of packet delay.
  709. double getStdDevDelay(const ExchangeType xchg_type) const {
  710. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  711. return xchg_stats->getStdDevDelay();
  712. }
  713. /// \brief Return number of orphant packets.
  714. ///
  715. /// Method returns number of orphant packets for specified
  716. /// exchange type.
  717. ///
  718. /// \param xchg_type exchange type.
  719. /// \throw isc::BadValue if invalid exchange type specified.
  720. /// \return number of orphant packets so far.
  721. unsigned long long getOrphans(const ExchangeType xchg_type) const {
  722. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  723. return xchg_stats->getOrphans();
  724. }
  725. /// \brief Return average unordered lookup set size.
  726. ///
  727. /// Method returns average unordered lookup set size.
  728. /// This value changes every time \ref ExchangeStats::findSent
  729. /// function performs unordered packet lookup.
  730. ///
  731. /// \param xchg_type exchange type.
  732. /// \throw isc::BadValue if invalid exchange type specified.
  733. /// \return average unordered lookup set size.
  734. double getAvgUnorderedLookupSetSize(const ExchangeType xchg_type) const {
  735. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  736. return xchg_stats->getAvgUnorderedLookupSetSize();
  737. }
  738. /// \brief Return number of unordered sent packets lookups
  739. ///
  740. /// Method returns number of unordered sent packet lookups.
  741. /// Unordered lookup is used when received packet was sent
  742. /// out of order by server - transaction id of received
  743. /// packet does not match transaction id of next sent packet.
  744. ///
  745. /// \param xchg_type exchange type.
  746. /// \throw isc::BadValue if invalid exchange type specified.
  747. /// \return number of unordered lookups.
  748. unsigned long long getUnorderedLookups(const ExchangeType xchg_type) const {
  749. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  750. return xchg_stats->getUnorderedLookups();
  751. }
  752. /// \brief Return number of ordered sent packets lookups
  753. ///
  754. /// Method returns number of ordered sent packet lookups.
  755. /// Ordered lookup is used when packets are received in the
  756. /// same order as they were sent to the server.
  757. /// If packets are skipped or received out of order, lookup
  758. /// function will use unordered lookup (with hash table).
  759. ///
  760. /// \param xchg_type exchange type.
  761. /// \throw isc::BadValue if invalid exchange type specified.
  762. /// \return number of ordered lookups.
  763. unsigned long long getOrderedLookups(const ExchangeType xchg_type) const {
  764. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  765. return xchg_stats->getOrderedLookups();
  766. }
  767. /// \brief Return total number of sent packets
  768. ///
  769. /// Method returns total number of sent packets for specified
  770. /// exchange type.
  771. ///
  772. /// \param xchg_type exchange type.
  773. /// \throw isc::BadValue if invalid exchange type specified.
  774. /// \return number of sent packets.
  775. unsigned long long getSentPacketsNum(const ExchangeType xchg_type) const {
  776. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  777. return xchg_stats->getSentPacketsNum();
  778. }
  779. /// \brief Return total number of received packets
  780. ///
  781. /// Method returns total number of received packets for specified
  782. /// exchange type.
  783. ///
  784. /// \param xchg_type exchange type.
  785. /// \throw isc::BadValue if invalid exchange type specified.
  786. /// \return number of received packets.
  787. unsigned long long getRcvdPacketsNum(const ExchangeType xchg_type) const {
  788. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  789. return xchg_stats->getRcvdPacketsNum();
  790. }
  791. /// \brief Return name of the exchange.
  792. ///
  793. /// Method returns name of the specified exchange type.
  794. /// This function is mainly for logging purposes.
  795. ///
  796. /// \param xchg_type exchange type.
  797. /// \return string representing name of the exchange.
  798. std::string exchangeToString(ExchangeType xchg_type) const {
  799. switch(xchg_type) {
  800. case XCHG_DO:
  801. return "DISCOVER-OFFER";
  802. case XCHG_RA:
  803. return "REQUEST-ACK";
  804. case XCHG_SA:
  805. return "SOLICIT-ADVERTISE";
  806. case XCHG_RR:
  807. return "REQUEST-REPLY";
  808. default:
  809. return "Unknown exchange type";
  810. }
  811. }
  812. /// \brief Print main statistics for all exchange types.
  813. ///
  814. /// Method prints main statistics for all exchange types.
  815. /// Statistics includes: number of sent and received packets,
  816. /// number of dropped packets and number of orphans.
  817. void printMainStats() const {
  818. for (ExchangesMapIterator it = exchanges_.begin();
  819. it != exchanges_.end();
  820. ++it) {
  821. ExchangeStatsPtr xchg_stats = it->second;
  822. printf("***Statistics for packet exchange %s***\n"
  823. "sent: %llu, received: %llu\n"
  824. "drops: %lld, orphans: %llu\n\n",
  825. exchangeToString(it->first).c_str(),
  826. xchg_stats->getSentPacketsNum(),
  827. xchg_stats->getRcvdPacketsNum(),
  828. xchg_stats->getRcvdPacketsNum()
  829. - xchg_stats->getSentPacketsNum(),
  830. xchg_stats->getOrphans());
  831. }
  832. }
  833. /// \brief Print round trip time packets statistics.
  834. ///
  835. /// Method prints round trip time packets statistics. Statistics
  836. /// includes minimum packet delay, maximum packet delay, average
  837. /// packet delay and standard deviation of delays. Packet delay
  838. /// is a duration between sending a packet to server and receiving
  839. /// response from server.
  840. void printRTTStats() const {
  841. for (ExchangesMapIterator it = exchanges_.begin();
  842. it != exchanges_.end();
  843. ++it) {
  844. ExchangeStatsPtr xchg_stats = it->second;
  845. printf("***Round trip time Statistics for packet exchange %s***\n"
  846. "min delay: %.3f\n"
  847. "avg delay: %.3f\n"
  848. "max delay: %.3f\n"
  849. "std deviation: %.3f\n",
  850. exchangeToString(it->first).c_str(),
  851. xchg_stats->getMinDelay(),
  852. xchg_stats->getAvgDelay(),
  853. xchg_stats->getMaxDelay(),
  854. xchg_stats->getStdDevDelay());
  855. }
  856. }
  857. /// \brief Print timestamps of all packets.
  858. ///
  859. /// Method prints timestamps of all sent and received
  860. /// packets for all defined exchange types.
  861. ///
  862. /// \throw isc::InvalidOperation if one of the packets has
  863. /// no timestamp value set.
  864. void printTimestamps() const {
  865. for (ExchangesMapIterator it = exchanges_.begin();
  866. it != exchanges_.end();
  867. ++it) {
  868. ExchangeStatsPtr xchg_stats = it->second;
  869. printf("***Timestamps for packets in exchange %s***\n",
  870. exchangeToString(it->first).c_str());
  871. xchg_stats->printTimestamps();
  872. }
  873. }
  874. /// \brief Print names and values of custom counters.
  875. ///
  876. /// Method prints names and values of custom counters. Custom counters
  877. /// are defined by client class for tracking different statistics.
  878. void printCustomCounters() const {
  879. if (custom_counters_.size() > 0) {
  880. printf("***Various statistics counters***\n");
  881. }
  882. for (CustomCountersMapIterator it = custom_counters_.begin();
  883. it != custom_counters_.end();
  884. ++it) {
  885. CustomCounterPtr counter = it->second;
  886. printf("%s: %llu\n", counter->getName().c_str(),
  887. counter->getValue());
  888. }
  889. }
  890. private:
  891. /// \brief Return exchange stats object for given exchange type
  892. ///
  893. /// Method returns exchange stats object for given exchange type.
  894. ///
  895. /// \param xchg_type exchange type.
  896. /// \throw isc::BadValue if invalid exchange type specified.
  897. /// \return exchange stats object.
  898. ExchangeStatsPtr getExchangeStats(const ExchangeType xchg_type) const {
  899. ExchangesMapIterator it = exchanges_.find(xchg_type);
  900. if (it == exchanges_.end()) {
  901. isc_throw(BadValue, "Packets exchange not specified");
  902. }
  903. ExchangeStatsPtr xchg_stats = it->second;
  904. return xchg_stats;
  905. }
  906. ExchangesMap exchanges_; ///< Map of exchange types.
  907. CustomCountersMap custom_counters_; ///< Map with custom counters.
  908. };
  909. } // namespace perfdhcp
  910. } // namespace isc
  911. #endif // __STATS_MGR_H