stats_mgr.h 49 KB

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