stats_mgr.h 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  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. uint64_t getValue() const { return(counter_); }
  82. /// \brief Return counter name.
  83. ///
  84. /// Method returns counter name.
  85. ///
  86. /// \return counter name.
  87. const std::string& getName() const { return(name_); }
  88. private:
  89. /// \brief Default constructor.
  90. ///
  91. /// Default constrcutor is private because we don't want client
  92. /// class to call it because we want client class to specify
  93. /// counter's name.
  94. CustomCounter() { };
  95. uint64_t counter_; ///< Counter's value.
  96. std::string name_; ///< Counter's name.
  97. };
  98. typedef typename boost::shared_ptr<CustomCounter> CustomCounterPtr;
  99. /// DHCP packet exchange types.
  100. enum ExchangeType {
  101. XCHG_DO, ///< DHCPv4 DISCOVER-OFFER
  102. XCHG_RA, ///< DHCPv4 REQUEST-ACK
  103. XCHG_SA, ///< DHCPv6 SOLICIT-ADVERTISE
  104. XCHG_RR ///< DHCPv6 REQUEST-REPLY
  105. };
  106. /// \brief Exchange Statistics.
  107. ///
  108. /// This class collects statistics for exchanges. Parent class
  109. /// may define number of different packet exchanges like:
  110. /// DHCPv4 DISCOVER-OFFER, DHCPv6 SOLICIT-ADVERTISE etc. Performance
  111. /// statistics will be collected for each of those separately in
  112. /// corresponding instance of ExchangeStats.
  113. class ExchangeStats {
  114. public:
  115. /// \brief Hash transaction id of the packet.
  116. ///
  117. /// Function hashes transaction id of the packet. Hashing is
  118. /// non-unique. Many packets may have the same hash value and thus
  119. /// they belong to the same packet buckets. Packet buckets are
  120. /// used for unordered packets search with multi index container.
  121. ///
  122. /// \param packet packet which transaction id is to be hashed.
  123. /// \throw isc::BadValue if packet is null.
  124. /// \return transaction id hash.
  125. static uint32_t hashTransid(const boost::shared_ptr<const T>& packet) {
  126. if (!packet) {
  127. isc_throw(BadValue, "Packet is null");
  128. }
  129. return(packet->getTransid() & 1023);
  130. }
  131. /// \brief List of packets (sent or received).
  132. ///
  133. /// List of packets based on multi index container allows efficient
  134. /// search of packets based on their sequence (order in which they
  135. /// were inserted) as well as based on their hashed transaction id.
  136. /// The first index (sequenced) provides the way to use container
  137. /// as a regular list (including iterators, removal of elements from
  138. /// the middle of the collection etc.). This index is meant to be used
  139. /// more frequently than the latter one and it is based on the
  140. /// assumption that responses from the DHCP server are received in
  141. /// order. In this case, when next packet is received it can be
  142. /// matched with next packet on the list of sent packets. This
  143. /// prevents intensive searches on the list of sent packets every
  144. /// time new packet arrives. In many cases however packets can be
  145. /// dropped by the server or may be sent out of order and we still
  146. /// want to have ability to search packets using transaction id.
  147. /// The second index can be used for this purpose. This index is
  148. /// hashing transaction ids using custom function \ref hashTransid.
  149. /// Note that other possibility would be to simply specify index
  150. /// that uses transaction id directly (instead of hashing with
  151. /// \ref hashTransid). In this case however we have chosen to use
  152. /// hashing function because it shortens the index size to just
  153. /// 1023 values maximum. Search operation on this index generally
  154. /// returns the range of packets that have the same transaction id
  155. /// hash assigned but most often these ranges will be short so further
  156. /// search within a range to find a packet with pacrticular transaction
  157. /// id will not be intensive.
  158. ///
  159. /// Example 1: Add elements to the list
  160. /// \code
  161. /// PktList packets_collection();
  162. /// boost::shared_ptr<Pkt4> pkt1(new Pkt4(...));
  163. /// boost::shared_ptr<Pkt4> pkt2(new Pkt4(...));
  164. /// // Add new packet to the container, it will be available through
  165. /// // both indexes
  166. /// packets_collection.push_back(pkt1);
  167. /// // Here is another way to add packet to the container. The result
  168. /// // is exactly the same as previously.
  169. /// packets_collection.template get<0>().push_back(pkt2);
  170. /// \endcode
  171. ///
  172. /// Example 2: Access elements through sequencial index
  173. /// \code
  174. /// PktList packets_collection();
  175. /// ... # Add elements to the container
  176. /// for (PktListIterator it = packets_collection.begin();
  177. /// it != packets_collection.end();
  178. /// ++it) {
  179. /// boost::shared_ptr<Pkt4> pkt = *it;
  180. /// # Do something with packet;
  181. /// }
  182. /// \endcode
  183. ///
  184. /// Example 3: Access elements through hashed index
  185. /// \code
  186. /// // Get the instance of the second search index.
  187. /// PktListTransidHashIndex& idx = sent_packets_.template get<1>();
  188. /// // Get the range (bucket) of packets sharing the same transaction
  189. /// // id hash.
  190. /// std::pair<PktListTransidHashIterator,PktListTransidHashIterator> p =
  191. /// idx.equal_range(hashTransid(rcvd_packet));
  192. /// // Iterate through the returned bucket.
  193. /// for (PktListTransidHashIterator it = p.first; it != p.second;
  194. /// ++it) {
  195. /// boost::shared_ptr pkt = *it;
  196. /// ... # Do something with the packet (e.g. check transaction id)
  197. /// }
  198. /// \endcode
  199. typedef boost::multi_index_container<
  200. boost::shared_ptr<const T>,
  201. boost::multi_index::indexed_by<
  202. boost::multi_index::sequenced<>,
  203. boost::multi_index::hashed_non_unique<
  204. boost::multi_index::global_fun<
  205. const boost::shared_ptr<const T>&,
  206. uint32_t,
  207. &ExchangeStats::hashTransid
  208. >
  209. >
  210. >
  211. > PktList;
  212. /// Packet list iterator for sequencial access to elements.
  213. typedef typename PktList::const_iterator PktListIterator;
  214. /// Packet list index to search packets using transaction id hash.
  215. typedef typename PktList::template nth_index<1>::type
  216. PktListTransidHashIndex;
  217. /// Packet list iterator to access packets using transaction id hash.
  218. typedef typename PktListTransidHashIndex::const_iterator
  219. PktListTransidHashIterator;
  220. /// \brief Constructor
  221. ///
  222. /// \param xchg_type exchange type
  223. /// \param archive_enabled if true packets archive mode is enabled.
  224. /// In this mode all packets are stored throughout the test execution.
  225. ExchangeStats(const ExchangeType xchg_type, const bool archive_enabled)
  226. : xchg_type_(xchg_type),
  227. sent_packets_(),
  228. rcvd_packets_(),
  229. archived_packets_(),
  230. archive_enabled_(archive_enabled),
  231. min_delay_(std::numeric_limits<double>::max()),
  232. max_delay_(0.),
  233. sum_delay_(0.),
  234. sum_delay_squared_(0.),
  235. orphans_(0),
  236. unordered_lookup_size_sum_(0),
  237. unordered_lookups_(0),
  238. ordered_lookups_(0),
  239. sent_packets_num_(0),
  240. rcvd_packets_num_(0)
  241. {
  242. next_sent_ = sent_packets_.begin();
  243. }
  244. /// \brief Add new packet to list of sent packets.
  245. ///
  246. /// Method adds new packet to list of sent packets.
  247. ///
  248. /// \param packet packet object to be added.
  249. /// \throw isc::BadValue if packet is null.
  250. void appendSent(const boost::shared_ptr<const T>& packet) {
  251. if (!packet) {
  252. isc_throw(BadValue, "Packet is null");
  253. }
  254. ++sent_packets_num_;
  255. sent_packets_.template get<0>().push_back(packet);
  256. }
  257. /// \brief Add new packet to list of received packets.
  258. ///
  259. /// Method adds new packet to list of received packets.
  260. ///
  261. /// \param packet packet object to be added.
  262. /// \throw isc::BadValue if packet is null.
  263. void appendRcvd(const boost::shared_ptr<const T>& packet) {
  264. if (!packet) {
  265. isc_throw(BadValue, "Packet is null");
  266. }
  267. rcvd_packets_.push_back(packet);
  268. }
  269. /// \brief Update delay counters.
  270. ///
  271. /// Method updates delay counters based on timestamps of
  272. /// sent and received packets.
  273. ///
  274. /// \param sent_packet sent packet
  275. /// \param rcvd_packet received packet
  276. /// \throw isc::BadValue if sent or received packet is null.
  277. /// \throw isc::Unexpected if failed to calculate timestamps
  278. void updateDelays(const boost::shared_ptr<const T>& sent_packet,
  279. const boost::shared_ptr<const T>& rcvd_packet) {
  280. if (!sent_packet) {
  281. isc_throw(BadValue, "Sent packet is null");
  282. }
  283. if (!rcvd_packet) {
  284. isc_throw(BadValue, "Received packet is null");
  285. }
  286. boost::posix_time::ptime sent_time = sent_packet->getTimestamp();
  287. boost::posix_time::ptime rcvd_time = rcvd_packet->getTimestamp();
  288. if (sent_time.is_not_a_date_time() ||
  289. rcvd_time.is_not_a_date_time()) {
  290. isc_throw(Unexpected,
  291. "Timestamp must be set for sent and "
  292. "received packet to measure RTT");
  293. }
  294. boost::posix_time::time_period period(sent_time, rcvd_time);
  295. // We don't bother calculating deltas in nanoseconds. It is much
  296. // more convenient to use seconds instead because we are going to
  297. // sum them up.
  298. double delta =
  299. static_cast<double>(period.length().total_nanoseconds()) / 1e9;
  300. if (delta < 0) {
  301. isc_throw(Unexpected, "Sent packet's timestamp must not be "
  302. "greater than received packet's timestamp");
  303. }
  304. // Record the minimum delay between sent and received packets.
  305. if (delta < min_delay_) {
  306. min_delay_ = delta;
  307. }
  308. // Record the maximum delay between sent and received packets.
  309. if (delta > max_delay_) {
  310. max_delay_ = delta;
  311. }
  312. // Update delay sum and square sum. That will be used to calculate
  313. // mean delays.
  314. sum_delay_ += delta;
  315. sum_delay_squared_ += delta * delta;
  316. }
  317. /// \brief Match received packet with the corresponding sent packet.
  318. ///
  319. /// Method finds packet with specified transaction id on the list
  320. /// of sent packets. It is used to match received packet with
  321. /// corresponding sent packet.
  322. /// Since packets from the server most often come in the same order
  323. /// as they were sent by client, this method will first check if
  324. /// next sent packet matches. If it doesn't, function will search
  325. /// the packet using indexing by transaction id. This reduces
  326. /// packet search time significantly.
  327. ///
  328. /// \param rcvd_packet received packet to be matched with sent packet.
  329. /// \throw isc::BadValue if received packet is null.
  330. /// \return packet having specified transaction or NULL if packet
  331. /// not found
  332. boost::shared_ptr<const T> matchPackets(const boost::shared_ptr<const T>& rcvd_packet) {
  333. if (!rcvd_packet) {
  334. isc_throw(BadValue, "Received packet is null");
  335. }
  336. if (sent_packets_.size() == 0) {
  337. // List of sent packets is empty so there is no sense
  338. // to continue looking fo the packet. It also means
  339. // that the received packet we got has no corresponding
  340. // sent packet so orphans counter has to be updated.
  341. ++orphans_;
  342. return(boost::shared_ptr<const T>());
  343. } else if (next_sent_ == sent_packets_.end()) {
  344. // Even if there are still many unmatched packets on the
  345. // list we might hit the end of it because of unordered
  346. // lookups. The next logical step is to reset iterator.
  347. next_sent_ = sent_packets_.begin();
  348. }
  349. // With this variable we will be signalling success or failure
  350. // to find the packet.
  351. bool packet_found = false;
  352. // Most likely responses are sent from the server in the same
  353. // order as client's requests to the server. We are caching
  354. // next sent packet and first try to match it with the next
  355. // incoming packet. We are successful if there is no
  356. // packet drop or out of order packets sent. This is actually
  357. // the fastest way to look for packets.
  358. if ((*next_sent_)->getTransid() == rcvd_packet->getTransid()) {
  359. ++ordered_lookups_;
  360. packet_found = true;
  361. } else {
  362. // If we are here, it means that we were unable to match the
  363. // next incoming packet with next sent packet so we need to
  364. // take a little more expensive approach to look packets using
  365. // alternative index (transaction id & 1023).
  366. PktListTransidHashIndex& idx = sent_packets_.template get<1>();
  367. // Packets are grouped using trasaction id masked with value
  368. // of 1023. For instance, packets with transaction id equal to
  369. // 1, 1024 ... will belong to the same group (a.k.a. bucket).
  370. // When using alternative index we don't find the packet but
  371. // bucket of packets and we need to iterate through the bucket
  372. // to find the one that has desired transaction id.
  373. std::pair<PktListTransidHashIterator,PktListTransidHashIterator> p =
  374. idx.equal_range(hashTransid(rcvd_packet));
  375. // We want to keep statistics of unordered lookups to make
  376. // sure that there is a right balance between number of
  377. // unordered lookups and ordered lookups. If number of unordered
  378. // lookups is high it may mean that many packets are lost or
  379. // sent out of order.
  380. ++unordered_lookups_;
  381. // We also want to keep the mean value of the bucket. The lower
  382. // bucket size the better. If bucket sizes appear to big we
  383. // might want to increase number of buckets.
  384. unordered_lookup_size_sum_ += std::distance(p.first, p.second);
  385. for (PktListTransidHashIterator it = p.first; it != p.second;
  386. ++it) {
  387. if ((*it)->getTransid() == rcvd_packet->getTransid()) {
  388. packet_found = true;
  389. next_sent_ =
  390. sent_packets_.template project<0>(it);
  391. break;
  392. }
  393. }
  394. }
  395. if (!packet_found) {
  396. // If we are here, it means that both ordered lookup and
  397. // unordered lookup failed. Searched packet is not on the list.
  398. ++orphans_;
  399. return(boost::shared_ptr<const T>());
  400. }
  401. // Packet is matched so we count it. We don't count unmatched packets
  402. // as they are counted as orphans with a separate counter.
  403. ++rcvd_packets_num_;
  404. boost::shared_ptr<const T> sent_packet(*next_sent_);
  405. // If packet was found, we assume it will be never searched
  406. // again. We want to delete this packet from the list to
  407. // improve performance of future searches.
  408. next_sent_ = eraseSent(next_sent_);
  409. return(sent_packet);
  410. }
  411. /// \brief Return minumum delay between sent and received packet.
  412. ///
  413. /// Method returns minimum delay between sent and received packet.
  414. ///
  415. /// \return minimum delay between packets.
  416. double getMinDelay() const { return(min_delay_); }
  417. /// \brief Return maxmimum delay between sent and received packet.
  418. ///
  419. /// Method returns maximum delay between sent and received packet.
  420. ///
  421. /// \return maximum delay between packets.
  422. double getMaxDelay() const { return(max_delay_); }
  423. /// \brief Return avarage packet delay.
  424. ///
  425. /// Method returns average packet delay. If no packets have been
  426. /// received for this exchange avg delay can't be calculated and
  427. /// thus method throws exception.
  428. ///
  429. /// \throw isc::InvalidOperation if no packets for this exchange
  430. /// have been received yet.
  431. /// \return average packet delay.
  432. double getAvgDelay() const {
  433. if (rcvd_packets_num_ == 0) {
  434. isc_throw(InvalidOperation, "no packets received");
  435. }
  436. return(sum_delay_ / rcvd_packets_num_);
  437. }
  438. /// \brief Return standard deviation of packet delay.
  439. ///
  440. /// Method returns standard deviation of packet delay. If no
  441. /// packets have been received for this exchange, the standard
  442. /// deviation can't be calculated and thus method throws
  443. /// exception.
  444. ///
  445. /// \throw isc::InvalidOperation if number of received packets
  446. /// for the exchange is equal to zero.
  447. /// \return standard deviation of packet delay.
  448. double getStdDevDelay() const {
  449. if (rcvd_packets_num_ == 0) {
  450. isc_throw(InvalidOperation, "no packets received");
  451. }
  452. return(sqrt(sum_delay_squared_ / rcvd_packets_num_ -
  453. getAvgDelay() * getAvgDelay()));
  454. }
  455. /// \brief Return number of orphant packets.
  456. ///
  457. /// Method returns number of received packets that had no matching
  458. /// sent packet. It is possible that such packet was late or not
  459. /// for us.
  460. ///
  461. /// \return number of orphant received packets.
  462. uint64_t getOrphans() const { return(orphans_); }
  463. /// \brief Return average unordered lookup set size.
  464. ///
  465. /// Method returns average unordered lookup set size.
  466. /// This value changes every time \ref ExchangeStats::matchPackets
  467. /// function performs unordered packet lookup.
  468. ///
  469. /// \throw isc::InvalidOperation if there have been no unordered
  470. /// lookups yet.
  471. /// \return average unordered lookup set size.
  472. double getAvgUnorderedLookupSetSize() const {
  473. if (unordered_lookups_ == 0) {
  474. isc_throw(InvalidOperation, "no unordered lookups");
  475. }
  476. return(static_cast<double>(unordered_lookup_size_sum_) /
  477. static_cast<double>(unordered_lookups_));
  478. }
  479. /// \brief Return number of unordered sent packets lookups
  480. ///
  481. /// Method returns number of unordered sent packet lookups.
  482. /// Unordered lookup is used when received packet was sent
  483. /// out of order by server - transaction id of received
  484. /// packet does not match transaction id of next sent packet.
  485. ///
  486. /// \return number of unordered lookups.
  487. uint64_t getUnorderedLookups() const { return(unordered_lookups_); }
  488. /// \brief Return number of ordered sent packets lookups
  489. ///
  490. /// Method returns number of ordered sent packet lookups.
  491. /// Ordered lookup is used when packets are received in the
  492. /// same order as they were sent to the server.
  493. /// If packets are skipped or received out of order, lookup
  494. /// function will use unordered lookup (with hash table).
  495. ///
  496. /// \return number of ordered lookups.
  497. uint64_t getOrderedLookups() const { return(ordered_lookups_); }
  498. /// \brief Return total number of sent packets
  499. ///
  500. /// Method returns total number of sent packets.
  501. ///
  502. /// \return number of sent packets.
  503. uint64_t getSentPacketsNum() const { return(sent_packets_num_); }
  504. /// \brief Return total number of received packets
  505. ///
  506. /// Method returns total number of received packets.
  507. ///
  508. /// \return number of received packets.
  509. uint64_t getRcvdPacketsNum() const { return(rcvd_packets_num_); }
  510. /// \brief Print main statistics for packet exchange.
  511. ///
  512. /// Method prints main statistics for particular exchange.
  513. /// Statistics includes: number of sent and received packets,
  514. /// number of dropped packets and number of orphans.
  515. void printMainStats() const {
  516. using namespace std;
  517. uint64_t drops = 0;
  518. if (getRcvdPacketsNum() >= getSentPacketsNum()) {
  519. drops = getRcvdPacketsNum() - getSentPacketsNum();
  520. }
  521. cout << "sent packets: " << getSentPacketsNum() << endl
  522. << "received packets: " << getRcvdPacketsNum() << endl
  523. << "drops: " << drops << endl
  524. << "orphans: " << getOrphans() << endl;
  525. }
  526. /// \brief Print round trip time packets statistics.
  527. ///
  528. /// Method prints round trip time packets statistics. Statistics
  529. /// includes minimum packet delay, maximum packet delay, average
  530. /// packet delay and standard deviation of delays. Packet delay
  531. /// is a duration between sending a packet to server and receiving
  532. /// response from server.
  533. void printRTTStats() const {
  534. using namespace std;
  535. try {
  536. cout << fixed << setprecision(3)
  537. << "min delay: " << getMinDelay() * 1e3 << " ms" << endl
  538. << "avg delay: " << getAvgDelay() * 1e3 << " ms" << endl
  539. << "max delay: " << getMaxDelay() * 1e3 << " ms" << endl
  540. << "std deviation: " << getStdDevDelay() * 1e3 << " ms"
  541. << endl;
  542. } catch (const Exception& e) {
  543. cout << "Unavailable! No packets received." << endl;
  544. }
  545. }
  546. //// \brief Print timestamps for sent and received packets.
  547. ///
  548. /// Method prints timestamps for all sent and received packets for
  549. /// packet exchange. In order to run this method the packets
  550. /// archiving mode has to be enabled during object constructions.
  551. /// Otherwise sent packets are not stored during tests execution
  552. /// and this method has no ability to get and print their timestamps.
  553. ///
  554. /// \throw isc::InvalidOperation if found packet with no timestamp or
  555. /// if packets archive mode is disabled.
  556. void printTimestamps() {
  557. // If archive mode is disabled there is no sense to proceed
  558. // because we don't have packets and their timestamps.
  559. if (!archive_enabled_) {
  560. isc_throw(isc::InvalidOperation,
  561. "packets archive mode is disabled");
  562. }
  563. if (rcvd_packets_num_ == 0) {
  564. std::cout << "Unavailable! No packets received." << std::endl;
  565. }
  566. // We will be using boost::posix_time extensivelly here
  567. using namespace boost::posix_time;
  568. // Iterate through all received packets.
  569. for (PktListIterator it = rcvd_packets_.begin();
  570. it != rcvd_packets_.end();
  571. ++it) {
  572. boost::shared_ptr<const T> rcvd_packet = *it;
  573. PktListTransidHashIndex& idx =
  574. archived_packets_.template get<1>();
  575. std::pair<PktListTransidHashIterator,
  576. PktListTransidHashIterator> p =
  577. idx.equal_range(hashTransid(rcvd_packet));
  578. for (PktListTransidHashIterator it_archived = p.first;
  579. it_archived != p.second;
  580. ++it) {
  581. if ((*it_archived)->getTransid() ==
  582. rcvd_packet->getTransid()) {
  583. boost::shared_ptr<const T> sent_packet = *it_archived;
  584. // Get sent and received packet times.
  585. ptime sent_time = sent_packet->getTimestamp();
  586. ptime rcvd_time = rcvd_packet->getTimestamp();
  587. // All sent and received packets should have timestamps
  588. // set but if there is a bug somewhere and packet does
  589. // not have timestamp we want to catch this here.
  590. if (sent_time.is_not_a_date_time() ||
  591. rcvd_time.is_not_a_date_time()) {
  592. isc_throw(InvalidOperation,
  593. "packet time is not set");
  594. }
  595. // Calculate durations of packets from beginning of epoch.
  596. ptime epoch_time(min_date_time);
  597. time_period sent_period(epoch_time, sent_time);
  598. time_period rcvd_period(epoch_time, rcvd_time);
  599. // Print timestamps for sent and received packet.
  600. std::cout << "sent / received: "
  601. << to_iso_string(sent_period.length())
  602. << " / "
  603. << to_iso_string(rcvd_period.length())
  604. << std::endl;
  605. break;
  606. }
  607. }
  608. }
  609. }
  610. private:
  611. /// \brief Private default constructor.
  612. ///
  613. /// Default constructor is private because we want the client
  614. /// class to specify exchange type explicitely.
  615. ExchangeStats();
  616. /// \brief Erase packet from the list of sent packets.
  617. ///
  618. /// Method erases packet from the list of sent packets.
  619. ///
  620. /// \param it iterator pointing to packet to be erased.
  621. /// \return iterator pointing to packet following erased
  622. /// packet or sent_packets_.end() if packet not found.
  623. PktListIterator eraseSent(const PktListIterator it) {
  624. if (archive_enabled_) {
  625. // We don't want to keep list of all sent packets
  626. // because it will affect packet lookup performance.
  627. // If packet is matched with received packet we
  628. // move it to list of archived packets. List of
  629. // archived packets may be used for diagnostics
  630. // when test is completed.
  631. archived_packets_.push_back(*it);
  632. }
  633. // get<0>() template returns sequencial index to
  634. // container.
  635. return(sent_packets_.template get<0>().erase(it));
  636. }
  637. ExchangeType xchg_type_; ///< Packet exchange type.
  638. PktList sent_packets_; ///< List of sent packets.
  639. /// Iterator pointing to the packet on sent list which will most
  640. /// likely match next received packet. This is based on the
  641. /// assumption that server responds in order to incoming packets.
  642. PktListIterator next_sent_;
  643. PktList rcvd_packets_; ///< List of received packets.
  644. /// List of archived packets. All sent packets that have
  645. /// been matched with received packet are moved to this
  646. /// list for diagnostics purposes.
  647. PktList archived_packets_;
  648. /// Indicates all packets have to be preserved after matching.
  649. /// By default this is disabled which means that when received
  650. /// packet is matched with sent packet both are deleted. This
  651. /// is important when test is executed for extended period of
  652. /// time and high memory usage might be the issue.
  653. /// When timestamps listing is specified from the command line
  654. /// (using diagnostics selector), all packets have to be preserved
  655. /// so as the printing method may read their timestamps and
  656. /// print it to user. In such usage model it will be rare to
  657. /// run test for extended period of time so it should be fine
  658. /// to keep all packets archived throughout the test.
  659. bool archive_enabled_;
  660. double min_delay_; ///< Minimum delay between sent
  661. ///< and received packets.
  662. double max_delay_; ///< Maximum delay between sent
  663. ///< and received packets.
  664. double sum_delay_; ///< Sum of delays between sent
  665. ///< and received packets.
  666. double sum_delay_squared_; ///< Squared sum of delays between
  667. ///< sent and recived packets.
  668. uint64_t orphans_; ///< Number of orphant received packets.
  669. /// Sum of unordered lookup sets. Needed to calculate mean size of
  670. /// lookup set. It is desired that number of unordered lookups is
  671. /// minimal for performance reasons. Tracking number of lookups and
  672. /// mean size of the lookup set should give idea of packets serach
  673. /// complexity.
  674. uint64_t unordered_lookup_size_sum_;
  675. uint64_t unordered_lookups_; ///< Number of unordered sent packets
  676. ///< lookups.
  677. uint64_t ordered_lookups_; ///< Number of ordered sent packets
  678. ///< lookups.
  679. uint64_t sent_packets_num_; ///< Total number of sent packets.
  680. uint64_t rcvd_packets_num_; ///< Total number of received packets.
  681. };
  682. /// Pointer to ExchangeStats.
  683. typedef boost::shared_ptr<ExchangeStats> ExchangeStatsPtr;
  684. /// Map containing all specified exchange types.
  685. typedef typename std::map<ExchangeType, ExchangeStatsPtr> ExchangesMap;
  686. /// Iterator poiting to \ref ExchangesMap
  687. typedef typename ExchangesMap::const_iterator ExchangesMapIterator;
  688. /// Map containing custom counters.
  689. typedef typename std::map<std::string, CustomCounterPtr> CustomCountersMap;
  690. /// Iterator for \ref CustomCountersMap.
  691. typedef typename CustomCountersMap::const_iterator CustomCountersMapIterator;
  692. /// \brief Constructor.
  693. ///
  694. /// This constructor by default disables packets archiving mode.
  695. /// In this mode all packets from the list of sent packets are
  696. /// moved to list of archived packets once they have been matched
  697. /// with received packets. This is required if it has been selected
  698. /// from the command line to print timestamps for all packets after
  699. /// the test. If this is not selected archiving should be disabled
  700. /// for performance reasons and to avoid waste of memory for storing
  701. /// large list of archived packets.
  702. ///
  703. /// \param archive_enabled true indicates that packets
  704. /// archive mode is enabled.
  705. StatsMgr(const bool archive_enabled = false) :
  706. exchanges_(),
  707. custom_counters_(),
  708. archive_enabled_(archive_enabled) {
  709. }
  710. /// \brief Specify new exchange type.
  711. ///
  712. /// This method creates new \ref ExchangeStats object that will
  713. /// collect statistics data from packets exchange of the specified
  714. /// type.
  715. ///
  716. /// \param xchg_type exchange type.
  717. /// \throw isc::BadValue if exchange of specified type exists.
  718. void addExchangeStats(const ExchangeType xchg_type) {
  719. if (exchanges_.find(xchg_type) != exchanges_.end()) {
  720. isc_throw(BadValue, "Exchange of specified type already added.");
  721. }
  722. exchanges_[xchg_type] =
  723. ExchangeStatsPtr(new ExchangeStats(xchg_type, archive_enabled_));
  724. }
  725. /// \brief Add named custom uint64 counter.
  726. ///
  727. /// Method creates new named counter and stores in counter's map under
  728. /// key specified here as short_name.
  729. ///
  730. /// \param short_name key to use to access counter in the map.
  731. /// \param long_name name of the counter presented in the log file.
  732. void addCustomCounter(const std::string& short_name,
  733. const std::string& long_name) {
  734. if (custom_counters_.find(short_name) != custom_counters_.end()) {
  735. isc_throw(BadValue,
  736. "Custom counter " << short_name << " already added.");
  737. }
  738. custom_counters_[short_name] =
  739. CustomCounterPtr(new CustomCounter(long_name));
  740. }
  741. /// \brief Return specified counter.
  742. ///
  743. /// Method returns specified counter.
  744. ///
  745. /// \param counter_key key poiting to the counter in the counters map.
  746. /// The short counter name has to be used to access counter.
  747. /// \return pointer to specified counter object.
  748. CustomCounterPtr getCounter(const std::string& counter_key) {
  749. CustomCountersMapIterator it = custom_counters_.find(counter_key);
  750. if (it == custom_counters_.end()) {
  751. isc_throw(BadValue,
  752. "Custom counter " << counter_key << "does not exist");
  753. }
  754. return(it->second);
  755. }
  756. /// \brief Increment specified counter.
  757. ///
  758. /// Increement counter value by one.
  759. ///
  760. /// \param counter_key key poitinh to the counter in the counters map.
  761. /// \return pointer to specified counter after incrementation.
  762. const CustomCounter& IncrementCounter(const std::string& counter_key) {
  763. CustomCounterPtr counter = getCounter(counter_key);
  764. return(++(*counter));
  765. }
  766. /// \brief Adds new packet to the sent packets list.
  767. ///
  768. /// Method adds new packet to the sent packets list.
  769. /// Packets are added to the list sequentially and
  770. /// most often read sequentially.
  771. ///
  772. /// \param xchg_type exchange type.
  773. /// \param packet packet to be added to the list
  774. /// \throw isc::BadValue if invalid exchange type specified or
  775. /// packet is null.
  776. void passSentPacket(const ExchangeType xchg_type,
  777. const boost::shared_ptr<const T>& packet) {
  778. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  779. xchg_stats->appendSent(packet);
  780. }
  781. /// \brief Add new received packet and match with sent packet.
  782. ///
  783. /// Method adds new packet to the list of received packets. It
  784. /// also searches for corresponding packet on the list of sent
  785. /// packets. When packets are matched the statistics counters
  786. /// are updated accordingly for the particular exchange type.
  787. ///
  788. /// \param xchg_type exchange type.
  789. /// \param packet received packet
  790. /// \throw isc::BadValue if invalid exchange type specified
  791. /// or packet is null.
  792. /// \throw isc::Unexpected if corresponding packet was not
  793. /// found on the list of sent packets.
  794. void passRcvdPacket(const ExchangeType xchg_type,
  795. const boost::shared_ptr<const T>& packet) {
  796. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  797. boost::shared_ptr<const T> sent_packet
  798. = xchg_stats->matchPackets(packet);
  799. if (sent_packet) {
  800. xchg_stats->updateDelays(sent_packet, packet);
  801. if (archive_enabled_) {
  802. xchg_stats->appendRcvd(packet);
  803. }
  804. }
  805. }
  806. /// \brief Return minumum delay between sent and received packet.
  807. ///
  808. /// Method returns minimum delay between sent and received packet
  809. /// for specified exchange type.
  810. ///
  811. /// \param xchg_type exchange type.
  812. /// \throw isc::BadValue if invalid exchange type specified.
  813. /// \return minimum delay between packets.
  814. double getMinDelay(const ExchangeType xchg_type) const {
  815. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  816. return(xchg_stats->getMinDelay());
  817. }
  818. /// \brief Return maxmimum delay between sent and received packet.
  819. ///
  820. /// Method returns maximum delay between sent and received packet
  821. /// for specified exchange type.
  822. ///
  823. /// \param xchg_type exchange type.
  824. /// \throw isc::BadValue if invalid exchange type specified.
  825. /// \return maximum delay between packets.
  826. double getMaxDelay(const ExchangeType xchg_type) const {
  827. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  828. return(xchg_stats->getMaxDelay());
  829. }
  830. /// \brief Return avarage packet delay.
  831. ///
  832. /// Method returns average packet delay for specified
  833. /// exchange type.
  834. ///
  835. /// \return average packet delay.
  836. double getAvgDelay(const ExchangeType xchg_type) const {
  837. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  838. return(xchg_stats->getAvgDelay());
  839. }
  840. /// \brief Return standard deviation of packet delay.
  841. ///
  842. /// Method returns standard deviation of packet delay
  843. /// for specified exchange type.
  844. ///
  845. /// \return standard deviation of packet delay.
  846. double getStdDevDelay(const ExchangeType xchg_type) const {
  847. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  848. return(xchg_stats->getStdDevDelay());
  849. }
  850. /// \brief Return number of orphant packets.
  851. ///
  852. /// Method returns number of orphant packets for specified
  853. /// exchange type.
  854. ///
  855. /// \param xchg_type exchange type.
  856. /// \throw isc::BadValue if invalid exchange type specified.
  857. /// \return number of orphant packets so far.
  858. uint64_t getOrphans(const ExchangeType xchg_type) const {
  859. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  860. return(xchg_stats->getOrphans());
  861. }
  862. /// \brief Return average unordered lookup set size.
  863. ///
  864. /// Method returns average unordered lookup set size.
  865. /// This value changes every time \ref ExchangeStats::matchPackets
  866. /// function performs unordered packet lookup.
  867. ///
  868. /// \param xchg_type exchange type.
  869. /// \throw isc::BadValue if invalid exchange type specified.
  870. /// \return average unordered lookup set size.
  871. double getAvgUnorderedLookupSetSize(const ExchangeType xchg_type) const {
  872. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  873. return(xchg_stats->getAvgUnorderedLookupSetSize());
  874. }
  875. /// \brief Return number of unordered sent packets lookups
  876. ///
  877. /// Method returns number of unordered sent packet lookups.
  878. /// Unordered lookup is used when received packet was sent
  879. /// out of order by server - transaction id of received
  880. /// packet does not match transaction id of next sent packet.
  881. ///
  882. /// \param xchg_type exchange type.
  883. /// \throw isc::BadValue if invalid exchange type specified.
  884. /// \return number of unordered lookups.
  885. uint64_t getUnorderedLookups(const ExchangeType xchg_type) const {
  886. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  887. return(xchg_stats->getUnorderedLookups());
  888. }
  889. /// \brief Return number of ordered sent packets lookups
  890. ///
  891. /// Method returns number of ordered sent packet lookups.
  892. /// Ordered lookup is used when packets are received in the
  893. /// same order as they were sent to the server.
  894. /// If packets are skipped or received out of order, lookup
  895. /// function will use unordered lookup (with hash table).
  896. ///
  897. /// \param xchg_type exchange type.
  898. /// \throw isc::BadValue if invalid exchange type specified.
  899. /// \return number of ordered lookups.
  900. uint64_t getOrderedLookups(const ExchangeType xchg_type) const {
  901. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  902. return(xchg_stats->getOrderedLookups());
  903. }
  904. /// \brief Return total number of sent packets
  905. ///
  906. /// Method returns total number of sent packets for specified
  907. /// exchange type.
  908. ///
  909. /// \param xchg_type exchange type.
  910. /// \throw isc::BadValue if invalid exchange type specified.
  911. /// \return number of sent packets.
  912. uint64_t getSentPacketsNum(const ExchangeType xchg_type) const {
  913. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  914. return(xchg_stats->getSentPacketsNum());
  915. }
  916. /// \brief Return total number of received packets
  917. ///
  918. /// Method returns total number of received packets for specified
  919. /// exchange type.
  920. ///
  921. /// \param xchg_type exchange type.
  922. /// \throw isc::BadValue if invalid exchange type specified.
  923. /// \return number of received packets.
  924. uint64_t getRcvdPacketsNum(const ExchangeType xchg_type) const {
  925. ExchangeStatsPtr xchg_stats = getExchangeStats(xchg_type);
  926. return(xchg_stats->getRcvdPacketsNum());
  927. }
  928. /// \brief Return name of the exchange.
  929. ///
  930. /// Method returns name of the specified exchange type.
  931. /// This function is mainly for logging purposes.
  932. ///
  933. /// \param xchg_type exchange type.
  934. /// \return string representing name of the exchange.
  935. std::string exchangeToString(ExchangeType xchg_type) const {
  936. switch(xchg_type) {
  937. case XCHG_DO:
  938. return("DISCOVER-OFFER");
  939. case XCHG_RA:
  940. return("REQUEST-ACK");
  941. case XCHG_SA:
  942. return("SOLICIT-ADVERTISE");
  943. case XCHG_RR:
  944. return("REQUEST-REPLY");
  945. default:
  946. return("Unknown exchange type");
  947. }
  948. }
  949. /// \brief Print statistics counters for all exchange types.
  950. ///
  951. /// Method prints statistics for all exchange types.
  952. /// Statistics includes:
  953. /// - number of sent and received packets
  954. /// - number of dropped packets and number of orphans
  955. /// - minimum packets delay,
  956. /// - average packets delay,
  957. /// - maximum packets delay,
  958. /// - standard deviation of packets delay.
  959. ///
  960. /// \throw isc::InvalidOperation if no exchange type added to
  961. /// track statistics.
  962. void printStats() const {
  963. if (exchanges_.size() == 0) {
  964. isc_throw(isc::InvalidOperation,
  965. "no exchange type added for tracking");
  966. }
  967. for (ExchangesMapIterator it = exchanges_.begin();
  968. it != exchanges_.end();
  969. ++it) {
  970. ExchangeStatsPtr xchg_stats = it->second;
  971. std::cout << "***Statistics for: " << exchangeToString(it->first)
  972. << "***" << std::endl;
  973. xchg_stats->printMainStats();
  974. std::cout << std::endl;
  975. xchg_stats->printRTTStats();
  976. std::cout << std::endl;
  977. }
  978. }
  979. /// \brief Print timestamps of all packets.
  980. ///
  981. /// Method prints timestamps of all sent and received
  982. /// packets for all defined exchange types.
  983. ///
  984. /// \throw isc::InvalidOperation if one of the packets has
  985. /// no timestamp value set or if packets archive mode is
  986. /// disabled.
  987. ///
  988. /// \throw isc::InvalidOperation if no exchange type added to
  989. /// track statistics or packets archive mode is disabled.
  990. void printTimestamps() const {
  991. if (exchanges_.size() == 0) {
  992. isc_throw(isc::InvalidOperation,
  993. "no exchange type added for tracking");
  994. }
  995. for (ExchangesMapIterator it = exchanges_.begin();
  996. it != exchanges_.end();
  997. ++it) {
  998. ExchangeStatsPtr xchg_stats = it->second;
  999. std::cout << "***Timestamps for packets: "
  1000. << exchangeToString(it->first)
  1001. << "***" << std::endl;
  1002. xchg_stats->printTimestamps();
  1003. std::cout << std::endl;
  1004. }
  1005. }
  1006. /// \brief Print names and values of custom counters.
  1007. ///
  1008. /// Method prints names and values of custom counters. Custom counters
  1009. /// are defined by client class for tracking different statistics.
  1010. ///
  1011. /// \throw isc::InvalidOperation if no custom counters added for tracking.
  1012. void printCustomCounters() const {
  1013. if (custom_counters_.size() == 0) {
  1014. isc_throw(isc::InvalidOperation, "no custom counters specified");
  1015. }
  1016. for (CustomCountersMapIterator it = custom_counters_.begin();
  1017. it != custom_counters_.end();
  1018. ++it) {
  1019. CustomCounterPtr counter = it->second;
  1020. std::cout << counter->getName() << ": " << counter->getValue()
  1021. << std::endl;
  1022. }
  1023. }
  1024. private:
  1025. /// \brief Return exchange stats object for given exchange type
  1026. ///
  1027. /// Method returns exchange stats object for given exchange type.
  1028. ///
  1029. /// \param xchg_type exchange type.
  1030. /// \throw isc::BadValue if invalid exchange type specified.
  1031. /// \return exchange stats object.
  1032. ExchangeStatsPtr getExchangeStats(const ExchangeType xchg_type) const {
  1033. ExchangesMapIterator it = exchanges_.find(xchg_type);
  1034. if (it == exchanges_.end()) {
  1035. isc_throw(BadValue, "Packets exchange not specified");
  1036. }
  1037. ExchangeStatsPtr xchg_stats = it->second;
  1038. return(xchg_stats);
  1039. }
  1040. ExchangesMap exchanges_; ///< Map of exchange types.
  1041. CustomCountersMap custom_counters_; ///< Map with custom counters.
  1042. /// Indicates that packets from list of sent packets should be
  1043. /// archived (moved to list of archived packets) once they are
  1044. /// matched with received packets. This is required when it has
  1045. /// been selected from the command line to print packets'
  1046. /// timestamps after test. This may affect performance and
  1047. /// consume large amount of memory when the test is running
  1048. /// for extended period of time and many packets have to be
  1049. /// archived.
  1050. bool archive_enabled_;
  1051. };
  1052. } // namespace perfdhcp
  1053. } // namespace isc
  1054. #endif // __STATS_MGR_H