stats_mgr.h 57 KB

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