test_control.h 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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 TEST_CONTROL_H
  15. #define TEST_CONTROL_H
  16. #include "packet_storage.h"
  17. #include "stats_mgr.h"
  18. #include <dhcp/iface_mgr.h>
  19. #include <dhcp/dhcp6.h>
  20. #include <dhcp/pkt4.h>
  21. #include <dhcp/pkt6.h>
  22. #include <boost/noncopyable.hpp>
  23. #include <boost/shared_ptr.hpp>
  24. #include <boost/function.hpp>
  25. #include <boost/date_time/posix_time/posix_time.hpp>
  26. #include <string>
  27. #include <vector>
  28. namespace isc {
  29. namespace perfdhcp {
  30. /// Default transaction id offset in the packet template.
  31. static const size_t DHCPV4_TRANSID_OFFSET = 4;
  32. /// Default offset of MAC's last octet in the packet template..
  33. static const size_t DHCPV4_RANDOMIZATION_OFFSET = 35;
  34. /// Default elapsed time offset in the packet template.
  35. static const size_t DHCPV4_ELAPSED_TIME_OFFSET = 8;
  36. /// Default server id offset in the packet template.
  37. static const size_t DHCPV4_SERVERID_OFFSET = 54;
  38. /// Default requested ip offset in the packet template.
  39. static const size_t DHCPV4_REQUESTED_IP_OFFSET = 240;
  40. /// Default DHCPV6 transaction id offset in t the packet template.
  41. static const size_t DHCPV6_TRANSID_OFFSET = 1;
  42. /// Default DHCPV6 randomization offset (last octet of DUID)
  43. /// in the packet template.
  44. static const size_t DHCPV6_RANDOMIZATION_OFFSET = 21;
  45. /// Default DHCPV6 elapsed time offset in the packet template.
  46. static const size_t DHCPV6_ELAPSED_TIME_OFFSET = 84;
  47. /// Default DHCPV6 server id offset in the packet template.
  48. static const size_t DHCPV6_SERVERID_OFFSET = 22;
  49. /// Default DHCPV6 IA_NA offset in the packet template.
  50. static const size_t DHCPV6_IA_NA_OFFSET = 40;
  51. /// @brief Exception thrown when the required option is not found in a packet.
  52. class OptionNotFound : public Exception {
  53. public:
  54. OptionNotFound(const char* file, size_t line, const char* what) :
  55. isc::Exception(file, line, what) { };
  56. };
  57. /// \brief Test Control class.
  58. ///
  59. /// This singleton class is used to run the performance test with
  60. /// with \ref TestControl::run function. This function can be executed
  61. /// multiple times if desired because it resets TestControl's internal
  62. /// state every time it is executed. Prior to running \ref TestControl::run,
  63. /// one must make sure to parse command line options by calling
  64. /// \ref CommandOptions::parse. Failing to do this will result in an exception.
  65. ///
  66. /// The following major stages of the test are performed by this class:
  67. /// - set default transaction id and MAC address generators - the generator
  68. /// is an object of \ref TestControl::NumberGenerator type and it provides
  69. /// the custom randomization algorithms,
  70. /// - print command line arguments,
  71. /// - register option factory functions which are used to generate DHCP options
  72. /// being sent to a server,
  73. /// - create the socket for communication with a server,
  74. /// - read packet templates if user specified template files with '-T' command
  75. /// line option,
  76. /// - set the interrupt handler (invoked when ^C is pressed) which makes
  77. /// perfdhcp stop gracefully and print the test results before exiting,
  78. /// - executes an external command (if specified '-w' option), e.g. if user
  79. /// specified -w ./foo in the command line then program will execute
  80. /// "./foo start" at the beginning of the test and "./foo stop" when the test
  81. /// ends,
  82. /// - initialize the Statistics Manager,
  83. /// - executes the main loop:
  84. /// - calculate how many packets must be send to satisfy desired rate,
  85. /// - receive incoming packets from the server,
  86. /// - check the exit conditions - terminate the program if the exit criteria
  87. /// are fulfilled, e.g. reached maximum number of packet drops,
  88. /// - send the number of packets appropriate to satisfy the desired rate,
  89. /// - optionally print intermediate reports,
  90. /// - print statistics, e.g. achieved rate,
  91. /// - optionally print some diagnostics.
  92. ///
  93. /// With the '-w' command line option user may specify the external application
  94. /// or script to be executed. This is executed twice, first when the test starts
  95. /// and second time when the test ends. This external script or application must
  96. /// accept 'start' and 'stop' arguments. The first time it is called, it is
  97. /// called with the argument 'start' and the second time with the argument
  98. /// 'stop'.
  99. ///
  100. /// The application is executed by calling fork() to fork the current perfdhcp
  101. /// process and then call execlp() to replace the current process image with
  102. /// the new one.
  103. ///
  104. /// Option factory functions are registered using
  105. /// \ref dhcp::LibDHCP::OptionFactoryRegister. Registered factory functions
  106. /// provide a way to create options of the same type in the same way.
  107. /// When a new option instance is needed, the corresponding factory
  108. /// function is called to create it. This is done by calling
  109. /// \ref dhcp::Option::factory with DHCP message type specified as one of
  110. /// parameters. Some of the parameters passed to factory function
  111. /// may be ignored (e.g. option buffer).
  112. /// Please note that naming convention for factory functions within this
  113. /// class is as follows:
  114. /// - factoryABC4 - factory function for DHCPv4 option,
  115. /// - factoryDEF6 - factory function for DHCPv6 option,
  116. /// - factoryGHI - factory function that can be used to create either
  117. /// DHCPv4 or DHCPv6 option.
  118. class TestControl : public boost::noncopyable {
  119. public:
  120. /// Statistics Manager for DHCPv4.
  121. typedef StatsMgr<dhcp::Pkt4> StatsMgr4;
  122. /// Pointer to Statistics Manager for DHCPv4;
  123. typedef boost::shared_ptr<StatsMgr4> StatsMgr4Ptr;
  124. /// Statictics Manager for DHCPv6.
  125. typedef StatsMgr<dhcp::Pkt6> StatsMgr6;
  126. /// Pointer to Statistics Manager for DHCPv6.
  127. typedef boost::shared_ptr<StatsMgr6> StatsMgr6Ptr;
  128. /// Packet exchange type.
  129. typedef StatsMgr<>::ExchangeType ExchangeType;
  130. /// Packet template buffer.
  131. typedef std::vector<uint8_t> TemplateBuffer;
  132. /// Packet template buffers list.
  133. typedef std::vector<TemplateBuffer> TemplateBufferCollection;
  134. /// \brief Socket wrapper structure.
  135. ///
  136. /// This is the wrapper that holds descriptor of the socket
  137. /// used to run DHCP test. The wrapped socket is closed in
  138. /// the destructor. This prevents resource leaks when when
  139. /// function that created the socket ends (normally or
  140. /// when exception occurs). This structure extends parent
  141. /// structure with new field ifindex_ that holds interface
  142. /// index where socket is bound to.
  143. struct TestControlSocket : public dhcp::SocketInfo {
  144. /// Interface index.
  145. uint16_t ifindex_;
  146. /// Is socket valid. It will not be valid if the provided socket
  147. /// descriptor does not point to valid socket.
  148. bool valid_;
  149. /// \brief Constructor of socket wrapper class.
  150. ///
  151. /// This constructor uses provided socket descriptor to
  152. /// find the name of the interface where socket has been
  153. /// bound to. If provided socket descriptor is invalid then
  154. /// valid_ field is set to false;
  155. ///
  156. /// \param socket socket descriptor.
  157. TestControlSocket(const int socket);
  158. /// \brief Destructor of the socket wrapper class.
  159. ///
  160. /// Destructor closes wrapped socket.
  161. ~TestControlSocket();
  162. private:
  163. /// \brief Initialize socket data.
  164. ///
  165. /// This method initializes members of the class that Interface
  166. /// Manager holds: interface name, local address.
  167. ///
  168. /// \throw isc::BadValue if interface for specified socket
  169. /// descriptor does not exist.
  170. void initSocketData();
  171. };
  172. /// \brief Number generator class.
  173. ///
  174. /// This is default numbers generator class. The member function is
  175. /// used to generate uint32_t values. Other generator classes should
  176. /// derive from this one to implement generation algorithms
  177. /// (e.g. sequential or based on random function).
  178. class NumberGenerator {
  179. public:
  180. /// \brief Destructor.
  181. virtual ~NumberGenerator() { }
  182. /// \brief Generate number.
  183. ///
  184. /// \return Generate number.
  185. virtual uint32_t generate() = 0;
  186. };
  187. /// The default generator pointer.
  188. typedef boost::shared_ptr<NumberGenerator> NumberGeneratorPtr;
  189. /// \brief Sequential numbers generator class.
  190. class SequentialGenerator : public NumberGenerator {
  191. public:
  192. /// \brief Constructor.
  193. ///
  194. /// \param range maximum number generated. If 0 is given then
  195. /// range defaults to maximum uint32_t value.
  196. SequentialGenerator(uint32_t range = 0xFFFFFFFF) :
  197. NumberGenerator(),
  198. num_(0),
  199. range_(range) {
  200. if (range_ == 0) {
  201. range_ = 0xFFFFFFFF;
  202. }
  203. }
  204. /// \brief Generate number sequentially.
  205. ///
  206. /// \return generated number.
  207. virtual uint32_t generate() {
  208. uint32_t num = num_;
  209. num_ = (num_ + 1) % range_;
  210. return (num);
  211. }
  212. private:
  213. uint32_t num_; ///< Current number.
  214. uint32_t range_; ///< Number of unique numbers generated.
  215. };
  216. /// \brief Length of the Ethernet HW address (MAC) in bytes.
  217. ///
  218. /// \todo Make this variable length as there are cases when HW
  219. /// address is longer than this (e.g. 20 bytes).
  220. static const uint8_t HW_ETHER_LEN = 6;
  221. /// TestControl is a singleton class. This method returns reference
  222. /// to its sole instance.
  223. ///
  224. /// \return the only existing instance of test control
  225. static TestControl& instance();
  226. /// brief\ Run performance test.
  227. ///
  228. /// Method runs whole performance test. Command line options must
  229. /// be parsed prior to running this function. Otherwise function will
  230. /// throw exception.
  231. ///
  232. /// \throw isc::InvalidOperation if command line options are not parsed.
  233. /// \throw isc::Unexpected if internal Test Controller error occured.
  234. /// \return error_code, 3 if number of received packets is not equal
  235. /// to number of sent packets, 0 if everything is ok.
  236. int run();
  237. /// \brief Set new transaction id generator.
  238. ///
  239. /// \param generator generator object to be used.
  240. void setTransidGenerator(const NumberGeneratorPtr& generator) {
  241. transid_gen_.reset();
  242. transid_gen_ = generator;
  243. }
  244. /// \brief Set new MAC address generator.
  245. ///
  246. /// Set numbers generator that will be used to generate various
  247. /// MAC addresses to simulate number of clients.
  248. ///
  249. /// \param generator object to be used.
  250. void setMacAddrGenerator(const NumberGeneratorPtr& generator) {
  251. macaddr_gen_.reset();
  252. macaddr_gen_ = generator;
  253. }
  254. // We would really like following methods and members to be private but
  255. // they have to be accessible for unit-testing. Another, possibly better,
  256. // solution is to make this class friend of test class but this is not
  257. // what's followed in other classes.
  258. protected:
  259. /// \brief Default constructor.
  260. ///
  261. /// Default constructor is protected as the object can be created
  262. /// only via \ref instance method.
  263. TestControl();
  264. /// \brief Check if test exit conditions fulfilled.
  265. ///
  266. /// Method checks if the test exit conditions are fulfilled.
  267. /// Exit conditions are checked periodically from the
  268. /// main loop. Program should break the main loop when
  269. /// this method returns true. It is calling function
  270. /// responsibility to break main loop gracefully and
  271. /// cleanup after test execution.
  272. ///
  273. /// \return true if any of the exit conditions is fulfilled.
  274. bool checkExitConditions() const;
  275. /// \brief Removes cached DHCPv6 Reply packets every second.
  276. ///
  277. /// This function wipes cached Reply packets from the storage.
  278. /// The number of packets left in the storage after the call
  279. /// to this function should guarantee that the Renew packets
  280. /// can be sent at the given rate. Note that the Renew packets
  281. /// are generated for the existing leases, represented here as
  282. /// replies from the server.
  283. /// @todo Instead of cleaning packets periodically we could
  284. /// just stop adding new packets when the certain threshold
  285. /// has been reached.
  286. void cleanCachedPackets();
  287. /// \brief Creates IPv6 packet using options from Reply packet.
  288. ///
  289. /// \param reply An instance of the Reply packet which contents should
  290. /// be used to create an instance of the Renew packet.
  291. ///
  292. /// \return created Renew packet.
  293. dhcp::Pkt6Ptr createRenew(const dhcp::Pkt6Ptr& reply);
  294. /// \brief Factory function to create DHCPv6 ELAPSED_TIME option.
  295. ///
  296. /// This factory function creates DHCPv6 ELAPSED_TIME option instance.
  297. /// If empty buffer is passed the option buffer will be initialized
  298. /// to length 2 and values will be initialized to zeros. Otherwise
  299. /// function will initialize option buffer with values in passed buffer.
  300. ///
  301. /// \param u universe (ignored)
  302. /// \param type option-type (ignored).
  303. /// \param buf option-buffer containing option content (2 bytes) or
  304. /// empty buffer if option content has to be set to default (0) value.
  305. /// \throw if elapsed time buffer size is neither 2 nor 0.
  306. /// \return instance o the option.
  307. static dhcp::OptionPtr
  308. factoryElapsedTime6(dhcp::Option::Universe u,
  309. uint16_t type,
  310. const dhcp::OptionBuffer& buf);
  311. /// \brief Factory function to create generic option.
  312. ///
  313. /// This factory function creates option with specified universe,
  314. /// type and buf. It does not have any additional logic validating
  315. /// the buffer contents, size etc.
  316. ///
  317. /// \param u universe (V6 or V4).
  318. /// \param type option-type (ignored).
  319. /// \param buf option-buffer.
  320. /// \return instance o the option.
  321. static dhcp::OptionPtr factoryGeneric(dhcp::Option::Universe u,
  322. uint16_t type,
  323. const dhcp::OptionBuffer& buf);
  324. /// \brief Factory function to create IA_NA option.
  325. ///
  326. /// This factory function creates DHCPv6 IA_NA option instance.
  327. ///
  328. /// \todo add support for IA Address options.
  329. ///
  330. /// \param u universe (ignored).
  331. /// \param type option-type (ignored).
  332. /// \param buf option-buffer carrying IANA suboptions.
  333. /// \return instance of IA_NA option.
  334. static dhcp::OptionPtr factoryIana6(dhcp::Option::Universe u,
  335. uint16_t type,
  336. const dhcp::OptionBuffer& buf);
  337. /// \brief Factory function to create IA_PD option.
  338. ///
  339. /// this factory function creates DHCPv6 IA_PD option instance.
  340. ///
  341. /// \param u universe (ignored).
  342. /// \param type option-type (ignored).
  343. /// \param buf option-buffer carrying sub-options.
  344. static dhcp::OptionPtr factoryIapd6(dhcp::Option::Universe u,
  345. uint16_t type,
  346. const dhcp::OptionBuffer& buf);
  347. /// \brief Factory function to create DHCPv6 ORO option.
  348. ///
  349. /// This factory function creates DHCPv6 Option Request Option instance.
  350. /// The created option will contain the following set of requested options:
  351. /// - D6O_NAME_SERVERS
  352. /// - D6O_DOMAIN_SEARCH
  353. ///
  354. /// \param u universe (ignored).
  355. /// \param type option-type (ignored).
  356. /// \param buf option-buffer (ignored).
  357. /// \return instance of ORO option.
  358. static dhcp::OptionPtr
  359. factoryOptionRequestOption6(dhcp::Option::Universe u,
  360. uint16_t type,
  361. const dhcp::OptionBuffer& buf);
  362. /// \brief Factory function to create DHCPv6 RAPID_COMMIT option instance.
  363. ///
  364. /// This factory function creates DHCPv6 RAPID_COMMIT option instance.
  365. /// The buffer passed to this option must be empty because option does
  366. /// not have any payload.
  367. ///
  368. /// \param u universe (ignored).
  369. /// \param type option-type (ignored).
  370. /// \param buf option-buffer (ignored).
  371. /// \return instance of RAPID_COMMIT option..
  372. static dhcp::OptionPtr factoryRapidCommit6(dhcp::Option::Universe u,
  373. uint16_t type,
  374. const dhcp::OptionBuffer& buf);
  375. /// \brief Factory function to create DHCPv4 Request List option.
  376. ///
  377. /// This factory function creates DHCPv4 PARAMETER_REQUEST_LIST option
  378. /// instance with the following set of requested options:
  379. /// - DHO_SUBNET_MASK,
  380. /// - DHO_BROADCAST_ADDRESS,
  381. /// - DHO_TIME_OFFSET,
  382. /// - DHO_ROUTERS,
  383. /// - DHO_DOMAIN_NAME,
  384. /// - DHO_DOMAIN_NAME_SERVERS,
  385. /// - DHO_HOST_NAME.
  386. ///
  387. /// \param u universe (ignored).
  388. /// \param type option-type (ignored).
  389. /// \param buf option-buffer (ignored).
  390. /// \return instance o the generic option.
  391. static dhcp::OptionPtr factoryRequestList4(dhcp::Option::Universe u,
  392. uint16_t type,
  393. const dhcp::OptionBuffer& buf);
  394. /// \brief Generate DUID.
  395. ///
  396. /// Method generates unique DUID. The number of DUIDs it can generate
  397. /// depends on the number of simulated clients, which is specified
  398. /// from the command line. It uses \ref CommandOptions object to retrieve
  399. /// number of clients. Since the last six octets of DUID are constructed
  400. /// from the MAC address, this function uses \ref generateMacAddress
  401. /// internally to randomize the DUID.
  402. ///
  403. /// \todo add support for other types of DUID.
  404. ///
  405. /// \param [out] randomized number of bytes randomized (initial value
  406. /// is ignored).
  407. /// \throw isc::BadValue if \ref generateMacAddress throws.
  408. /// \return vector representing DUID.
  409. std::vector<uint8_t> generateDuid(uint8_t& randomized) const;
  410. /// \brief Generate MAC address.
  411. ///
  412. /// This method generates MAC address. The number of unique
  413. /// MAC addresses it can generate is determined by the number
  414. /// simulated DHCP clients specified from command line. It uses
  415. /// \ref CommandOptions object to retrieve number of clients.
  416. /// Based on this the random value is generated and added to
  417. /// the MAC address template (default MAC address).
  418. ///
  419. /// \param [out] randomized number of bytes randomized (initial
  420. /// value is ignored).
  421. /// \throw isc::BadValue if MAC address template (default or specified
  422. /// from the command line) has invalid size (expected 6 octets).
  423. /// \return generated MAC address.
  424. std::vector<uint8_t> generateMacAddress(uint8_t& randomized) const;
  425. /// \brief generate transaction id.
  426. ///
  427. /// Generate transaction id value (32-bit for DHCPv4,
  428. /// 24-bit for DHCPv6).
  429. ///
  430. /// \return generated transaction id.
  431. uint32_t generateTransid() {
  432. return (transid_gen_->generate());
  433. }
  434. /// \brief Returns a timeout for packet reception.
  435. ///
  436. /// The calculation is based on the value of the timestamp
  437. /// when the next set of packets is to be sent. If no packet is
  438. /// received until then, new packets are sent.
  439. ///
  440. /// \return A current timeout in microseconds.
  441. uint32_t getCurrentTimeout() const;
  442. /// \brief Returns number of exchanges to be started.
  443. ///
  444. /// Method returns number of new exchanges to be started as soon
  445. /// as possible to satisfy expected rate. Calculation used here
  446. /// is based on current time, due time calculated with
  447. /// \ref updateSendDue function and expected rate.
  448. ///
  449. /// \param send_due Due time to initiate next chunk set exchanges.
  450. /// \param rate A rate at which exchanges are initiated.
  451. ///
  452. /// \return number of exchanges to be started immediately.
  453. static uint64_t
  454. getNextExchangesNum(const boost::posix_time::ptime& send_due,
  455. const int rate);
  456. /// \brief Return template buffer.
  457. ///
  458. /// Method returns template buffer at specified index.
  459. ///
  460. /// \param idx index of template buffer.
  461. /// \throw isc::OutOfRange if buffer index out of bounds.
  462. /// \return reference to template buffer.
  463. TemplateBuffer getTemplateBuffer(const size_t idx) const;
  464. /// \brief Reads packet templates from files.
  465. ///
  466. /// Method iterates through all specified template files, reads
  467. /// their content and stores it in class internal buffers. Template
  468. /// file names are specified from the command line with -T option.
  469. ///
  470. /// \throw isc::BadValue if any of the template files does not exist,
  471. /// contains characters other than hexadecimal digits or spaces.
  472. /// \throw OutOfRange if any of the template files is empty or has
  473. /// odd number of hexadecimal digits.
  474. void initPacketTemplates();
  475. /// \brief Initializes Statistics Manager.
  476. ///
  477. /// This function initializes Statistics Manager. If there is
  478. /// the one initialized already it is released.
  479. void initializeStatsMgr();
  480. /// \brief Open socket to communicate with DHCP server.
  481. ///
  482. /// Method opens socket and binds it to local address. Function will
  483. /// use either interface name, local address or server address
  484. /// to create a socket, depending on what is available (specified
  485. /// from the command line). If socket can't be created for any
  486. /// reason, exception is thrown.
  487. /// If destination address is broadcast (for DHCPv4) or multicast
  488. /// (for DHCPv6) than broadcast or multicast option is set on
  489. /// the socket. Opened socket is registered and managed by IfaceMgr.
  490. ///
  491. /// \throw isc::BadValue if socket can't be created for given
  492. /// interface, local address or remote address.
  493. /// \throw isc::InvalidOperation if broadcast option can't be
  494. /// set for the v4 socket or if multicast option can't be set
  495. /// for the v6 socket.
  496. /// \throw isc::Unexpected if interal unexpected error occured.
  497. /// \return socket descriptor.
  498. int openSocket() const;
  499. /// \brief Print intermediate statistics.
  500. ///
  501. /// Print brief statistics regarding number of sent packets,
  502. /// received packets and dropped packets so far.
  503. void printIntermediateStats();
  504. /// \brief Print rate statistics.
  505. ///
  506. /// Method print packet exchange rate statistics.
  507. void printRate() const;
  508. /// \brief Print performance statistics.
  509. ///
  510. /// Method prints performance statistics.
  511. /// \throws isc::InvalidOperation if Statistics Manager was
  512. /// not initialized.
  513. void printStats() const;
  514. /// \brief Process received DHCPv4 packet.
  515. ///
  516. /// Method performs processing of the received DHCPv4 packet,
  517. /// updates statistics and responds to the server if required,
  518. /// e.g. when OFFER packet arrives, this function will initiate
  519. /// REQUEST message to the server.
  520. ///
  521. /// \warning this method does not check if provided socket is
  522. /// valid (specifically if v4 socket for received v4 packet).
  523. ///
  524. /// \param [in] socket socket to be used.
  525. /// \param [in] pkt4 object representing DHCPv4 packet received.
  526. /// \throw isc::BadValue if unknown message type received.
  527. /// \throw isc::Unexpected if unexpected error occured.
  528. void processReceivedPacket4(const TestControlSocket& socket,
  529. const dhcp::Pkt4Ptr& pkt4);
  530. /// \brief Process received DHCPv6 packet.
  531. ///
  532. /// Method performs processing of the received DHCPv6 packet,
  533. /// updates statistics and responds to the server if required,
  534. /// e.g. when ADVERTISE packet arrives, this function will initiate
  535. /// REQUEST message to the server.
  536. ///
  537. /// \warning this method does not check if provided socket is
  538. /// valid (specifically if v4 socket for received v4 packet).
  539. ///
  540. /// \param [in] socket socket to be used.
  541. /// \param [in] pkt6 object representing DHCPv6 packet received.
  542. /// \throw isc::BadValue if unknown message type received.
  543. /// \throw isc::Unexpected if unexpected error occured.
  544. void processReceivedPacket6(const TestControlSocket& socket,
  545. const dhcp::Pkt6Ptr& pkt6);
  546. /// \brief Receive DHCPv4 or DHCPv6 packets from the server.
  547. ///
  548. /// Method receives DHCPv4 or DHCPv6 packets from the server.
  549. /// This function will call \ref processReceivedPacket4 or
  550. /// \ref processReceivedPacket6 depending if DHCPv4 or DHCPv6 packet
  551. /// has arrived.
  552. ///
  553. /// \warning this method does not check if provided socket is
  554. /// valid. Ensure that it is valid prior to calling it.
  555. ///
  556. /// \param socket socket to be used.
  557. /// \throw isc::BadValue if unknown message type received.
  558. /// \throw isc::Unexpected if unexpected error occured.
  559. /// \return number of received packets.
  560. uint64_t receivePackets(const TestControlSocket& socket);
  561. /// \brief Register option factory functions for DHCPv4
  562. ///
  563. /// Method registers option factory functions for DHCPv4.
  564. /// These functions are called to create instances of DHCPv4
  565. /// options. Call \ref dhcp::Option::factory to invoke factory
  566. /// function for particular option. Don't use this function directly.
  567. /// Use \ref registerOptionFactories instead.
  568. void registerOptionFactories4() const;
  569. /// \brief Register option factory functions for DHCPv6
  570. ///
  571. /// Method registers option factory functions for DHCPv6.
  572. /// These functions are called to create instances of DHCPv6
  573. /// options. Call \ref dhcp::Option::factory to invoke factory
  574. /// function for particular option. Don't use this function directly.
  575. /// Use \ref registerOptionFactories instead.
  576. void registerOptionFactories6() const;
  577. /// \brief Register option factory functions for DHCPv4 or DHCPv6.
  578. ///
  579. /// Method registers option factory functions for DHCPv4 or DHCPv6,
  580. /// depending in which mode test is currently running.
  581. void registerOptionFactories() const;
  582. /// \brief Resets internal state of the object.
  583. ///
  584. /// Method resets internal state of the object. It has to be
  585. /// called before new test is started.
  586. void reset();
  587. /// \brief Save the first DHCPv4 sent packet of the specified type.
  588. ///
  589. /// This method saves first packet of the specified being sent
  590. /// to the server if user requested diagnostics flag 'T'. In
  591. /// such case program has to print contents of selected packets
  592. /// being sent to the server. It collects first packets of each
  593. /// type and keeps them around until test finishes. Then they
  594. /// are printed to the user. If packet of specified type has
  595. /// been already stored this function perfroms no operation.
  596. /// This function does not perform sanity check if packet
  597. /// pointer is valid. Make sure it is before calling it.
  598. ///
  599. /// \param pkt packet to be stored.
  600. inline void saveFirstPacket(const dhcp::Pkt4Ptr& pkt);
  601. /// \brief Save the first DHCPv6 sent packet of the specified type.
  602. ///
  603. /// This method saves first packet of the specified being sent
  604. /// to the server if user requested diagnostics flag 'T'. In
  605. /// such case program has to print contents of selected packets
  606. /// being sent to the server. It collects first packets of each
  607. /// type and keeps them around until test finishes. Then they
  608. /// are printed to the user. If packet of specified type has
  609. /// been already stored this function perfroms no operation.
  610. /// This function does not perform sanity check if packet
  611. /// pointer is valid. Make sure it is before calling it.
  612. ///
  613. /// \param pkt packet to be stored.
  614. inline void saveFirstPacket(const dhcp::Pkt6Ptr& pkt);
  615. /// \brief Send DHCPv4 DISCOVER message.
  616. ///
  617. /// Method creates and sends DHCPv4 DISCOVER message to the server
  618. /// with the following options:
  619. /// - MESSAGE_TYPE set to DHCPDISCOVER
  620. /// - PARAMETER_REQUEST_LIST with the same list of requested options
  621. /// as described in \ref factoryRequestList4.
  622. /// The transaction id and MAC address are randomly generated for
  623. /// the message. Range of unique MAC addresses generated depends
  624. /// on the number of clients specified from the command line.
  625. /// Copy of sent packet is stored in the stats_mgr4_ object to
  626. /// update statistics.
  627. ///
  628. /// \param socket socket to be used to send the message.
  629. /// \param preload preload mode, packets not included in statistics.
  630. ///
  631. /// \throw isc::Unexpected if failed to create new packet instance.
  632. /// \throw isc::BadValue if MAC address has invalid length.
  633. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  634. void sendDiscover4(const TestControlSocket& socket,
  635. const bool preload = false);
  636. /// \brief Send DHCPv4 DISCOVER message from template.
  637. ///
  638. /// Method sends DHCPv4 DISCOVER message from template. The
  639. /// template data is expected to be in binary format. Provided
  640. /// buffer is copied and parts of it are replaced with actual
  641. /// data (e.g. MAC address, transaction id etc.).
  642. /// Copy of sent packet is stored in the stats_mgr4_ object to
  643. /// update statistics.
  644. ///
  645. /// \param socket socket to be used to send the message.
  646. /// \param template_buf buffer holding template packet.
  647. /// \param preload preload mode, packets not included in statistics.
  648. ///
  649. /// \throw isc::OutOfRange if randomization offset is out of bounds.
  650. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  651. void sendDiscover4(const TestControlSocket& socket,
  652. const std::vector<uint8_t>& template_buf,
  653. const bool preload = false);
  654. /// \brief Send number of packets to initiate new exchanges.
  655. ///
  656. /// Method initiates the new DHCP exchanges by sending number
  657. /// of DISCOVER (DHCPv4) or SOLICIT (DHCPv6) packets. If preload
  658. /// mode was requested sent packets will not be counted in
  659. /// the statistics. The responses from the server will be
  660. /// received and counted as orphans because corresponding sent
  661. /// packets are not included in StatsMgr for match.
  662. /// When preload mode is disabled and diagnostics flag 'i' is
  663. /// specified then function will be trying to receive late packets
  664. /// before new packets are sent to the server. Statistics of
  665. /// late received packets is updated accordingly.
  666. ///
  667. /// \todo do not count responses in preload mode as orphans.
  668. ///
  669. /// \param socket socket to be used to send packets.
  670. /// \param packets_num number of packets to be sent.
  671. /// \param preload preload mode, packets not included in statistics.
  672. /// \throw isc::Unexpected if thrown by packet sending method.
  673. /// \throw isc::InvalidOperation if thrown by packet sending method.
  674. /// \throw isc::OutOfRange if thrown by packet sending method.
  675. void sendPackets(const TestControlSocket &socket,
  676. const uint64_t packets_num,
  677. const bool preload = false);
  678. /// \brief Send number of DHCPv6 Renew packets to the server.
  679. ///
  680. /// \param socket An object representing socket to be used to send packets.
  681. /// \param packets_num A number of Renew packets to be send.
  682. ///
  683. /// \return A number of packets actually sent.
  684. uint64_t sendRenewPackets(const TestControlSocket& socket,
  685. const uint64_t packets_num);
  686. /// \brief Send a renew message using provided socket.
  687. ///
  688. /// This method will select an existing lease from the Reply packet cache
  689. /// If there is no lease that can be renewed this method will return false.
  690. ///
  691. /// \param socket An object encapsulating socket to be used to send
  692. /// a packet.
  693. ///
  694. /// \return true if packet has been sent, false otherwise.
  695. bool sendRenew(const TestControlSocket& socket);
  696. /// \brief Send DHCPv4 REQUEST message.
  697. ///
  698. /// Method creates and sends DHCPv4 REQUEST message to the server.
  699. /// Copy of sent packet is stored in the stats_mgr4_ object to
  700. /// update statistics.
  701. ///
  702. /// \param socket socket to be used to send message.
  703. /// \param discover_pkt4 DISCOVER packet sent.
  704. /// \param offer_pkt4 OFFER packet object.
  705. ///
  706. /// \throw isc::Unexpected if unexpected error occured.
  707. /// \throw isc::InvalidOperation if Statistics Manager has not been
  708. /// initialized.
  709. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  710. void sendRequest4(const TestControlSocket& socket,
  711. const dhcp::Pkt4Ptr& discover_pkt4,
  712. const dhcp::Pkt4Ptr& offer_pkt4);
  713. /// \brief Send DHCPv4 REQUEST message from template.
  714. ///
  715. /// Method sends DHCPv4 REQUEST message from template.
  716. /// Copy of sent packet is stored in the stats_mgr4_ object to
  717. /// update statistics.
  718. ///
  719. /// \param socket socket to be used to send message.
  720. /// \param template_buf buffer holding template packet.
  721. /// \param discover_pkt4 DISCOVER packet sent.
  722. /// \param offer_pkt4 OFFER packet received.
  723. ///
  724. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  725. void sendRequest4(const TestControlSocket& socket,
  726. const std::vector<uint8_t>& template_buf,
  727. const dhcp::Pkt4Ptr& discover_pkt4,
  728. const dhcp::Pkt4Ptr& offer_pkt4);
  729. /// \brief Send DHCPv6 REQUEST message.
  730. ///
  731. /// Method creates and sends DHCPv6 REQUEST message to the server
  732. /// with the following options:
  733. /// - D6O_ELAPSED_TIME
  734. /// - D6O_CLIENTID
  735. /// - D6O_SERVERID
  736. /// Copy of sent packet is stored in the stats_mgr6_ object to
  737. /// update statistics.
  738. ///
  739. /// \param socket socket to be used to send message.
  740. /// \param advertise_pkt6 ADVERTISE packet object.
  741. /// \throw isc::Unexpected if unexpected error occured.
  742. /// \throw isc::InvalidOperation if Statistics Manager has not been
  743. /// initialized.
  744. ///
  745. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  746. void sendRequest6(const TestControlSocket& socket,
  747. const dhcp::Pkt6Ptr& advertise_pkt6);
  748. /// \brief Send DHCPv6 REQUEST message from template.
  749. ///
  750. /// Method sends DHCPv6 REQUEST message from template.
  751. /// Copy of sent packet is stored in the stats_mgr6_ object to
  752. /// update statistics.
  753. ///
  754. /// \param socket socket to be used to send message.
  755. /// \param template_buf packet template buffer.
  756. /// \param advertise_pkt6 ADVERTISE packet object.
  757. ///
  758. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  759. void sendRequest6(const TestControlSocket& socket,
  760. const std::vector<uint8_t>& template_buf,
  761. const dhcp::Pkt6Ptr& advertise_pkt6);
  762. /// \brief Send DHCPv6 SOLICIT message.
  763. ///
  764. /// Method creates and sends DHCPv6 SOLICIT message to the server
  765. /// with the following options:
  766. /// - D6O_ELAPSED_TIME,
  767. /// - D6O_RAPID_COMMIT if rapid commit is requested in command line,
  768. /// - D6O_CLIENTID,
  769. /// - D6O_ORO (Option Request Option),
  770. /// - D6O_IA_NA.
  771. /// Copy of sent packet is stored in the stats_mgr6_ object to
  772. /// update statistics.
  773. ///
  774. /// \param socket socket to be used to send the message.
  775. /// \param preload mode, packets not included in statistics.
  776. ///
  777. /// \throw isc::Unexpected if failed to create new packet instance.
  778. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  779. void sendSolicit6(const TestControlSocket& socket,
  780. const bool preload = false);
  781. /// \brief Send DHCPv6 SOLICIT message from template.
  782. ///
  783. /// Method sends DHCPv6 SOLICIT message from template.
  784. /// Copy of sent packet is stored in the stats_mgr6_ object to
  785. /// update statistics.
  786. ///
  787. /// \param socket socket to be used to send the message.
  788. /// \param template_buf packet template buffer.
  789. /// \param preload mode, packets not included in statistics.
  790. ///
  791. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  792. void sendSolicit6(const TestControlSocket& socket,
  793. const std::vector<uint8_t>& template_buf,
  794. const bool preload = false);
  795. /// \brief Set default DHCPv4 packet parameters.
  796. ///
  797. /// This method sets default parameters on the DHCPv4 packet:
  798. /// - interface name,
  799. /// - local port = 68 (DHCP client port),
  800. /// - remote port = 67 (DHCP server port),
  801. /// - server's address,
  802. /// - GIADDR = local address where socket is bound to,
  803. /// - hops = 1 (pretending that we are a relay)
  804. ///
  805. /// \param socket socket used to send the packet.
  806. /// \param pkt reference to packet to be configured.
  807. void setDefaults4(const TestControlSocket& socket,
  808. const dhcp::Pkt4Ptr& pkt);
  809. /// \brief Set default DHCPv6 packet parameters.
  810. ///
  811. /// This method sets default parameters on the DHCPv6 packet:
  812. /// - interface name,
  813. /// - interface index,
  814. /// - local port,
  815. /// - remote port,
  816. /// - local address,
  817. /// - remote address (server).
  818. ///
  819. /// \param socket socket used to send the packet.
  820. /// \param pkt reference to packet to be configured.
  821. void setDefaults6(const TestControlSocket& socket,
  822. const dhcp::Pkt6Ptr& pkt);
  823. /// \brief Find if diagnostic flag has been set.
  824. ///
  825. /// \param diag diagnostic flag (a,e,i,s,r,t,T).
  826. /// \return true if diagnostics flag has been set.
  827. bool testDiags(const char diag) const;
  828. /// \brief Update due time to initiate next chunk of exchanges.
  829. ///
  830. /// Method updates due time to initiate next chunk of exchanges.
  831. /// Function takes current time, last sent packet's time and
  832. /// expected rate in its calculations.
  833. ///
  834. /// \param last_sent A time when the last exchange was initiated.
  835. /// \param rate A rate at which exchangesa re initiated
  836. /// \param [out] send_due A reference to the time object to be updated
  837. /// with the next due time.
  838. void updateSendDue(const boost::posix_time::ptime& last_sent,
  839. const int rate,
  840. boost::posix_time::ptime& send_due);
  841. private:
  842. /// \brief Copies IA_NA or IA_PD option from one packet to another.
  843. ///
  844. /// This function checks the lease-type specified in the command line
  845. /// with option -e<lease-type>. If 'address-only' value has been specified
  846. /// this function expects that IA_NA option is present in the packet
  847. /// encapsulated by pkt_from object. If 'prefix-only' value has been
  848. /// specified, this function expects that IA_PD option is present in the
  849. /// packet encapsulated by pkt_to object.
  850. ///
  851. /// \param [in] pkt_from A packet from which options should be copied.
  852. /// \param [out] pkt_to A packet to which options should be copied.
  853. ///
  854. /// \throw isc::perfdhcp::OptionNotFound if a required option is not
  855. /// found in the packet from which options should be copied.
  856. /// \throw isc::BadValue if any of the specified pointers to packets
  857. /// is NULL.
  858. void copyIaOptions(const dhcp::Pkt6Ptr& pkt_from, dhcp::Pkt6Ptr& pkt_to);
  859. /// \brief Convert binary value to hex string.
  860. ///
  861. /// \todo Consider moving this function to src/lib/util.
  862. ///
  863. /// \param b byte to convert.
  864. /// \return hex string.
  865. std::string byte2Hex(const uint8_t b) const;
  866. /// \brief Calculate elapsed time between two packets.
  867. ///
  868. /// \param T Pkt4Ptr or Pkt6Ptr class.
  869. /// \param pkt1 first packet.
  870. /// \param pkt2 second packet.
  871. /// \throw InvalidOperation if packet timestamps are invalid.
  872. /// \return elapsed time in milliseconds between pkt1 and pkt2.
  873. template<class T>
  874. uint32_t getElapsedTime(const T& pkt1, const T& pkt2);
  875. /// \brief Return elapsed time offset in a packet.
  876. ///
  877. /// \return elapsed time offset in packet.
  878. int getElapsedTimeOffset() const;
  879. /// \brief Return randomization offset in a packet.
  880. ///
  881. /// \return randomization offset in packet.
  882. int getRandomOffset(const int arg_idx) const;
  883. /// \brief Return requested ip offset in a packet.
  884. ///
  885. /// \return randomization offset in a packet.
  886. int getRequestedIpOffset() const;
  887. /// \brief Return server id offset in a packet.
  888. ///
  889. /// \return server id offset in packet.
  890. int getServerIdOffset() const;
  891. /// \brief Return transaction id offset in a packet.
  892. ///
  893. /// \param arg_idx command line argument index to be used.
  894. /// If multiple -X parameters specifed it points to the
  895. /// one to be used.
  896. /// \return transaction id offset in packet.
  897. int getTransactionIdOffset(const int arg_idx) const;
  898. /// \brief Get number of received packets.
  899. ///
  900. /// Get the number of received packets from the Statistics Manager.
  901. /// Function may throw if Statistics Manager object is not
  902. /// initialized.
  903. /// \param xchg_type packet exchange type.
  904. /// \return number of received packets.
  905. uint64_t getRcvdPacketsNum(const ExchangeType xchg_type) const;
  906. /// \brief Get number of sent packets.
  907. ///
  908. /// Get the number of sent packets from the Statistics Manager.
  909. /// Function may throw if Statistics Manager object is not
  910. /// initialized.
  911. /// \param xchg_type packet exchange type.
  912. /// \return number of sent packets.
  913. uint64_t getSentPacketsNum(const ExchangeType xchg_type) const;
  914. /// \brief Handle child signal.
  915. ///
  916. /// Function handles child signal by waiting for
  917. /// the process to complete.
  918. ///
  919. /// \param sig signal (ignored)
  920. static void handleChild(int sig);
  921. /// \brief Handle interrupt signal.
  922. ///
  923. /// Function sets flag indicating that program has been
  924. /// interrupted.
  925. ///
  926. /// \param sig signal (ignored)
  927. static void handleInterrupt(int sig);
  928. /// \brief Print main diagnostics data.
  929. ///
  930. /// Method prints main diagnostics data.
  931. void printDiagnostics() const;
  932. /// \brief Print template information
  933. ///
  934. /// \param packet_type packet type.
  935. void printTemplate(const uint8_t packet_type) const;
  936. /// \brief Print templates information.
  937. ///
  938. /// Method prints information about data offsets
  939. /// in packet templates and their contents.
  940. void printTemplates() const;
  941. /// \brief Read DHCP message template from file.
  942. ///
  943. /// Method reads DHCP message template from file and
  944. /// converts it to binary format. Read data is appended
  945. /// to template_buffers_ vector.
  946. ///
  947. /// \param file_name name of the packet template file.
  948. /// \throw isc::OutOfRange if file is empty or has odd number
  949. /// of hexadecimal digits.
  950. /// \throw isc::BadValue if file contains characters other than
  951. /// spaces or hexadecimal digits.
  952. void readPacketTemplate(const std::string& file_name);
  953. /// \brief Run wrapped command.
  954. ///
  955. /// \param do_stop execute wrapped command with "stop" argument.
  956. void runWrapped(bool do_stop = false) const;
  957. /// \brief Convert vector in hexadecimal string.
  958. ///
  959. /// \todo Consider moving this function to src/lib/util.
  960. ///
  961. /// \param vec vector to be converted.
  962. /// \param separator separator.
  963. std::string vector2Hex(const std::vector<uint8_t>& vec,
  964. const std::string& separator = "") const;
  965. boost::posix_time::ptime send_due_; ///< Due time to initiate next chunk
  966. ///< of exchanges.
  967. boost::posix_time::ptime last_sent_; ///< Indicates when the last exchange
  968. ///< was initiated.
  969. boost::posix_time::ptime renew_due_; ///< Due time to send next set of
  970. ///< Renew requests.
  971. boost::posix_time::ptime last_renew_; ///< Indicates when the last Renew
  972. ///< was attempted.
  973. boost::posix_time::ptime last_report_; ///< Last intermediate report time.
  974. StatsMgr4Ptr stats_mgr4_; ///< Statistics Manager 4.
  975. StatsMgr6Ptr stats_mgr6_; ///< Statistics Manager 6.
  976. PacketStorage<dhcp::Pkt6> reply_storage_; ///< A storage for reply messages.
  977. NumberGeneratorPtr transid_gen_; ///< Transaction id generator.
  978. NumberGeneratorPtr macaddr_gen_; ///< Numbers generator for MAC address.
  979. /// Buffer holding server id received in first packet
  980. dhcp::OptionBuffer first_packet_serverid_;
  981. /// Packet template buffers.
  982. TemplateBufferCollection template_buffers_;
  983. /// First packets send. They are used at the end of the test
  984. /// to print packet templates when diagnostics flag T is specifed.
  985. std::map<uint8_t, dhcp::Pkt4Ptr> template_packets_v4_;
  986. std::map<uint8_t, dhcp::Pkt6Ptr> template_packets_v6_;
  987. static bool interrupted_; ///< Is program interrupted.
  988. };
  989. } // namespace perfdhcp
  990. } // namespace isc
  991. #endif // TEST_CONTROL_H