stats_mgr.h 56 KB

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