test_control.h 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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. void cleanCachedPackets();
  284. /// \brief Creates IPv6 packet using options from Reply packet.
  285. ///
  286. /// \param reply An instance of the Reply packet which contents should
  287. /// be used to create an instance of the Renew packet.
  288. ///
  289. /// \return created Renew packet.
  290. dhcp::Pkt6Ptr createRenew(const dhcp::Pkt6Ptr& reply);
  291. /// \brief Factory function to create DHCPv6 ELAPSED_TIME option.
  292. ///
  293. /// This factory function creates DHCPv6 ELAPSED_TIME option instance.
  294. /// If empty buffer is passed the option buffer will be initialized
  295. /// to length 2 and values will be initialized to zeros. Otherwise
  296. /// function will initialize option buffer with values in passed buffer.
  297. ///
  298. /// \param u universe (ignored)
  299. /// \param type option-type (ignored).
  300. /// \param buf option-buffer containing option content (2 bytes) or
  301. /// empty buffer if option content has to be set to default (0) value.
  302. /// \throw if elapsed time buffer size is neither 2 nor 0.
  303. /// \return instance o the option.
  304. static dhcp::OptionPtr
  305. factoryElapsedTime6(dhcp::Option::Universe u,
  306. uint16_t type,
  307. const dhcp::OptionBuffer& buf);
  308. /// \brief Factory function to create generic option.
  309. ///
  310. /// This factory function creates option with specified universe,
  311. /// type and buf. It does not have any additional logic validating
  312. /// the buffer contents, size etc.
  313. ///
  314. /// \param u universe (V6 or V4).
  315. /// \param type option-type (ignored).
  316. /// \param buf option-buffer.
  317. /// \return instance o the option.
  318. static dhcp::OptionPtr factoryGeneric(dhcp::Option::Universe u,
  319. uint16_t type,
  320. const dhcp::OptionBuffer& buf);
  321. /// \brief Factory function to create IA_NA option.
  322. ///
  323. /// This factory function creates DHCPv6 IA_NA option instance.
  324. ///
  325. /// \todo add support for IA Address options.
  326. ///
  327. /// \param u universe (ignored).
  328. /// \param type option-type (ignored).
  329. /// \param buf option-buffer carrying IANA suboptions.
  330. /// \return instance of IA_NA option.
  331. static dhcp::OptionPtr factoryIana6(dhcp::Option::Universe u,
  332. uint16_t type,
  333. const dhcp::OptionBuffer& buf);
  334. /// \brief Factory function to create IA_PD option.
  335. ///
  336. /// this factory function creates DHCPv6 IA_PD option instance.
  337. ///
  338. /// \param u universe (ignored).
  339. /// \param type option-type (ignored).
  340. /// \param buf option-buffer carrying sub-options.
  341. static dhcp::OptionPtr factoryIapd6(dhcp::Option::Universe u,
  342. uint16_t type,
  343. const dhcp::OptionBuffer& buf);
  344. /// \brief Factory function to create DHCPv6 ORO option.
  345. ///
  346. /// This factory function creates DHCPv6 Option Request Option instance.
  347. /// The created option will contain the following set of requested options:
  348. /// - D6O_NAME_SERVERS
  349. /// - D6O_DOMAIN_SEARCH
  350. ///
  351. /// \param u universe (ignored).
  352. /// \param type option-type (ignored).
  353. /// \param buf option-buffer (ignored).
  354. /// \return instance of ORO option.
  355. static dhcp::OptionPtr
  356. factoryOptionRequestOption6(dhcp::Option::Universe u,
  357. uint16_t type,
  358. const dhcp::OptionBuffer& buf);
  359. /// \brief Factory function to create DHCPv6 RAPID_COMMIT option instance.
  360. ///
  361. /// This factory function creates DHCPv6 RAPID_COMMIT option instance.
  362. /// The buffer passed to this option must be empty because option does
  363. /// not have any payload.
  364. ///
  365. /// \param u universe (ignored).
  366. /// \param type option-type (ignored).
  367. /// \param buf option-buffer (ignored).
  368. /// \return instance of RAPID_COMMIT option..
  369. static dhcp::OptionPtr factoryRapidCommit6(dhcp::Option::Universe u,
  370. uint16_t type,
  371. const dhcp::OptionBuffer& buf);
  372. /// \brief Factory function to create DHCPv4 Request List option.
  373. ///
  374. /// This factory function creates DHCPv4 PARAMETER_REQUEST_LIST option
  375. /// instance with the following set of requested options:
  376. /// - DHO_SUBNET_MASK,
  377. /// - DHO_BROADCAST_ADDRESS,
  378. /// - DHO_TIME_OFFSET,
  379. /// - DHO_ROUTERS,
  380. /// - DHO_DOMAIN_NAME,
  381. /// - DHO_DOMAIN_NAME_SERVERS,
  382. /// - DHO_HOST_NAME.
  383. ///
  384. /// \param u universe (ignored).
  385. /// \param type option-type (ignored).
  386. /// \param buf option-buffer (ignored).
  387. /// \return instance o the generic option.
  388. static dhcp::OptionPtr factoryRequestList4(dhcp::Option::Universe u,
  389. uint16_t type,
  390. const dhcp::OptionBuffer& buf);
  391. /// \brief Generate DUID.
  392. ///
  393. /// Method generates unique DUID. The number of DUIDs it can generate
  394. /// depends on the number of simulated clients, which is specified
  395. /// from the command line. It uses \ref CommandOptions object to retrieve
  396. /// number of clients. Since the last six octets of DUID are constructed
  397. /// from the MAC address, this function uses \ref generateMacAddress
  398. /// internally to randomize the DUID.
  399. ///
  400. /// \todo add support for other types of DUID.
  401. ///
  402. /// \param [out] randomized number of bytes randomized (initial value
  403. /// is ignored).
  404. /// \throw isc::BadValue if \ref generateMacAddress throws.
  405. /// \return vector representing DUID.
  406. std::vector<uint8_t> generateDuid(uint8_t& randomized) const;
  407. /// \brief Generate MAC address.
  408. ///
  409. /// This method generates MAC address. The number of unique
  410. /// MAC addresses it can generate is determined by the number
  411. /// simulated DHCP clients specified from command line. It uses
  412. /// \ref CommandOptions object to retrieve number of clients.
  413. /// Based on this the random value is generated and added to
  414. /// the MAC address template (default MAC address).
  415. ///
  416. /// \param [out] randomized number of bytes randomized (initial
  417. /// value is ignored).
  418. /// \throw isc::BadValue if MAC address template (default or specified
  419. /// from the command line) has invalid size (expected 6 octets).
  420. /// \return generated MAC address.
  421. std::vector<uint8_t> generateMacAddress(uint8_t& randomized) const;
  422. /// \brief generate transaction id.
  423. ///
  424. /// Generate transaction id value (32-bit for DHCPv4,
  425. /// 24-bit for DHCPv6).
  426. ///
  427. /// \return generated transaction id.
  428. uint32_t generateTransid() {
  429. return (transid_gen_->generate());
  430. }
  431. /// \brief Returns a timeout for packet reception.
  432. ///
  433. /// The calculation is based on the value of the timestamp
  434. /// when the next set of packets is to be sent. If no packet is
  435. /// received until then, new packets are sent.
  436. ///
  437. /// \return A current timeout in microseconds.
  438. uint32_t getCurrentTimeout() const;
  439. /// \brief Returns number of exchanges to be started.
  440. ///
  441. /// Method returns number of new exchanges to be started as soon
  442. /// as possible to satisfy expected rate. Calculation used here
  443. /// is based on current time, due time calculated with
  444. /// \ref updateSendDue function and expected rate.
  445. ///
  446. /// \param send_due Due time to initiate next chunk set exchanges.
  447. /// \param rate A rate at which exchanges are initiated.
  448. ///
  449. /// \return number of exchanges to be started immediately.
  450. static uint64_t
  451. getNextExchangesNum(const boost::posix_time::ptime& send_due,
  452. const int rate);
  453. /// \brief Return template buffer.
  454. ///
  455. /// Method returns template buffer at specified index.
  456. ///
  457. /// \param idx index of template buffer.
  458. /// \throw isc::OutOfRange if buffer index out of bounds.
  459. /// \return reference to template buffer.
  460. TemplateBuffer getTemplateBuffer(const size_t idx) const;
  461. /// \brief Reads packet templates from files.
  462. ///
  463. /// Method iterates through all specified template files, reads
  464. /// their content and stores it in class internal buffers. Template
  465. /// file names are specified from the command line with -T option.
  466. ///
  467. /// \throw isc::BadValue if any of the template files does not exist,
  468. /// contains characters other than hexadecimal digits or spaces.
  469. /// \throw OutOfRange if any of the template files is empty or has
  470. /// odd number of hexadecimal digits.
  471. void initPacketTemplates();
  472. /// \brief Initializes Statistics Manager.
  473. ///
  474. /// This function initializes Statistics Manager. If there is
  475. /// the one initialized already it is released.
  476. void initializeStatsMgr();
  477. /// \brief Open socket to communicate with DHCP server.
  478. ///
  479. /// Method opens socket and binds it to local address. Function will
  480. /// use either interface name, local address or server address
  481. /// to create a socket, depending on what is available (specified
  482. /// from the command line). If socket can't be created for any
  483. /// reason, exception is thrown.
  484. /// If destination address is broadcast (for DHCPv4) or multicast
  485. /// (for DHCPv6) than broadcast or multicast option is set on
  486. /// the socket. Opened socket is registered and managed by IfaceMgr.
  487. ///
  488. /// \throw isc::BadValue if socket can't be created for given
  489. /// interface, local address or remote address.
  490. /// \throw isc::InvalidOperation if broadcast option can't be
  491. /// set for the v4 socket or if multicast option can't be set
  492. /// for the v6 socket.
  493. /// \throw isc::Unexpected if interal unexpected error occured.
  494. /// \return socket descriptor.
  495. int openSocket() const;
  496. /// \brief Print intermediate statistics.
  497. ///
  498. /// Print brief statistics regarding number of sent packets,
  499. /// received packets and dropped packets so far.
  500. void printIntermediateStats();
  501. /// \brief Print rate statistics.
  502. ///
  503. /// Method print packet exchange rate statistics.
  504. void printRate() const;
  505. /// \brief Print performance statistics.
  506. ///
  507. /// Method prints performance statistics.
  508. /// \throws isc::InvalidOperation if Statistics Manager was
  509. /// not initialized.
  510. void printStats() const;
  511. /// \brief Process received DHCPv4 packet.
  512. ///
  513. /// Method performs processing of the received DHCPv4 packet,
  514. /// updates statistics and responds to the server if required,
  515. /// e.g. when OFFER packet arrives, this function will initiate
  516. /// REQUEST message to the server.
  517. ///
  518. /// \warning this method does not check if provided socket is
  519. /// valid (specifically if v4 socket for received v4 packet).
  520. ///
  521. /// \param [in] socket socket to be used.
  522. /// \param [in] pkt4 object representing DHCPv4 packet received.
  523. /// \throw isc::BadValue if unknown message type received.
  524. /// \throw isc::Unexpected if unexpected error occured.
  525. void processReceivedPacket4(const TestControlSocket& socket,
  526. const dhcp::Pkt4Ptr& pkt4);
  527. /// \brief Process received DHCPv6 packet.
  528. ///
  529. /// Method performs processing of the received DHCPv6 packet,
  530. /// updates statistics and responds to the server if required,
  531. /// e.g. when ADVERTISE packet arrives, this function will initiate
  532. /// REQUEST message to the server.
  533. ///
  534. /// \warning this method does not check if provided socket is
  535. /// valid (specifically if v4 socket for received v4 packet).
  536. ///
  537. /// \param [in] socket socket to be used.
  538. /// \param [in] pkt6 object representing DHCPv6 packet received.
  539. /// \throw isc::BadValue if unknown message type received.
  540. /// \throw isc::Unexpected if unexpected error occured.
  541. void processReceivedPacket6(const TestControlSocket& socket,
  542. const dhcp::Pkt6Ptr& pkt6);
  543. /// \brief Receive DHCPv4 or DHCPv6 packets from the server.
  544. ///
  545. /// Method receives DHCPv4 or DHCPv6 packets from the server.
  546. /// This function will call \ref processReceivedPacket4 or
  547. /// \ref processReceivedPacket6 depending if DHCPv4 or DHCPv6 packet
  548. /// has arrived.
  549. ///
  550. /// \warning this method does not check if provided socket is
  551. /// valid. Ensure that it is valid prior to calling it.
  552. ///
  553. /// \param socket socket to be used.
  554. /// \throw isc::BadValue if unknown message type received.
  555. /// \throw isc::Unexpected if unexpected error occured.
  556. /// \return number of received packets.
  557. uint64_t receivePackets(const TestControlSocket& socket);
  558. /// \brief Register option factory functions for DHCPv4
  559. ///
  560. /// Method registers option factory functions for DHCPv4.
  561. /// These functions are called to create instances of DHCPv4
  562. /// options. Call \ref dhcp::Option::factory to invoke factory
  563. /// function for particular option. Don't use this function directly.
  564. /// Use \ref registerOptionFactories instead.
  565. void registerOptionFactories4() const;
  566. /// \brief Register option factory functions for DHCPv6
  567. ///
  568. /// Method registers option factory functions for DHCPv6.
  569. /// These functions are called to create instances of DHCPv6
  570. /// options. Call \ref dhcp::Option::factory to invoke factory
  571. /// function for particular option. Don't use this function directly.
  572. /// Use \ref registerOptionFactories instead.
  573. void registerOptionFactories6() const;
  574. /// \brief Register option factory functions for DHCPv4 or DHCPv6.
  575. ///
  576. /// Method registers option factory functions for DHCPv4 or DHCPv6,
  577. /// depending in which mode test is currently running.
  578. void registerOptionFactories() const;
  579. /// \brief Resets internal state of the object.
  580. ///
  581. /// Method resets internal state of the object. It has to be
  582. /// called before new test is started.
  583. void reset();
  584. /// \brief Save the first DHCPv4 sent packet of the specified type.
  585. ///
  586. /// This method saves first packet of the specified being sent
  587. /// to the server if user requested diagnostics flag 'T'. In
  588. /// such case program has to print contents of selected packets
  589. /// being sent to the server. It collects first packets of each
  590. /// type and keeps them around until test finishes. Then they
  591. /// are printed to the user. If packet of specified type has
  592. /// been already stored this function perfroms no operation.
  593. /// This function does not perform sanity check if packet
  594. /// pointer is valid. Make sure it is before calling it.
  595. ///
  596. /// \param pkt packet to be stored.
  597. inline void saveFirstPacket(const dhcp::Pkt4Ptr& pkt);
  598. /// \brief Save the first DHCPv6 sent packet of the specified type.
  599. ///
  600. /// This method saves first packet of the specified being sent
  601. /// to the server if user requested diagnostics flag 'T'. In
  602. /// such case program has to print contents of selected packets
  603. /// being sent to the server. It collects first packets of each
  604. /// type and keeps them around until test finishes. Then they
  605. /// are printed to the user. If packet of specified type has
  606. /// been already stored this function perfroms no operation.
  607. /// This function does not perform sanity check if packet
  608. /// pointer is valid. Make sure it is before calling it.
  609. ///
  610. /// \param pkt packet to be stored.
  611. inline void saveFirstPacket(const dhcp::Pkt6Ptr& pkt);
  612. /// \brief Send DHCPv4 DISCOVER message.
  613. ///
  614. /// Method creates and sends DHCPv4 DISCOVER message to the server
  615. /// with the following options:
  616. /// - MESSAGE_TYPE set to DHCPDISCOVER
  617. /// - PARAMETER_REQUEST_LIST with the same list of requested options
  618. /// as described in \ref factoryRequestList4.
  619. /// The transaction id and MAC address are randomly generated for
  620. /// the message. Range of unique MAC addresses generated depends
  621. /// on the number of clients specified from the command line.
  622. /// Copy of sent packet is stored in the stats_mgr4_ object to
  623. /// update statistics.
  624. ///
  625. /// \param socket socket to be used to send the message.
  626. /// \param preload preload mode, packets not included in statistics.
  627. ///
  628. /// \throw isc::Unexpected if failed to create new packet instance.
  629. /// \throw isc::BadValue if MAC address has invalid length.
  630. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  631. void sendDiscover4(const TestControlSocket& socket,
  632. const bool preload = false);
  633. /// \brief Send DHCPv4 DISCOVER message from template.
  634. ///
  635. /// Method sends DHCPv4 DISCOVER message from template. The
  636. /// template data is expected to be in binary format. Provided
  637. /// buffer is copied and parts of it are replaced with actual
  638. /// data (e.g. MAC address, transaction id etc.).
  639. /// Copy of sent packet is stored in the stats_mgr4_ object to
  640. /// update statistics.
  641. ///
  642. /// \param socket socket to be used to send the message.
  643. /// \param template_buf buffer holding template packet.
  644. /// \param preload preload mode, packets not included in statistics.
  645. ///
  646. /// \throw isc::OutOfRange if randomization offset is out of bounds.
  647. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  648. void sendDiscover4(const TestControlSocket& socket,
  649. const std::vector<uint8_t>& template_buf,
  650. const bool preload = false);
  651. /// \brief Send number of packets to initiate new exchanges.
  652. ///
  653. /// Method initiates the new DHCP exchanges by sending number
  654. /// of DISCOVER (DHCPv4) or SOLICIT (DHCPv6) packets. If preload
  655. /// mode was requested sent packets will not be counted in
  656. /// the statistics. The responses from the server will be
  657. /// received and counted as orphans because corresponding sent
  658. /// packets are not included in StatsMgr for match.
  659. /// When preload mode is disabled and diagnostics flag 'i' is
  660. /// specified then function will be trying to receive late packets
  661. /// before new packets are sent to the server. Statistics of
  662. /// late received packets is updated accordingly.
  663. ///
  664. /// \todo do not count responses in preload mode as orphans.
  665. ///
  666. /// \param socket socket to be used to send packets.
  667. /// \param packets_num number of packets to be sent.
  668. /// \param preload preload mode, packets not included in statistics.
  669. /// \throw isc::Unexpected if thrown by packet sending method.
  670. /// \throw isc::InvalidOperation if thrown by packet sending method.
  671. /// \throw isc::OutOfRange if thrown by packet sending method.
  672. void sendPackets(const TestControlSocket &socket,
  673. const uint64_t packets_num,
  674. const bool preload = false);
  675. /// \brief Send number of DHCPv6 Renew packets to the server.
  676. ///
  677. /// \param socket An object representing socket to be used to send packets.
  678. /// \param packets_num A number of Renew packets to be send.
  679. ///
  680. /// \return A number of packets actually sent.
  681. uint64_t sendRenewPackets(const TestControlSocket& socket,
  682. const uint64_t packets_num);
  683. /// \brief Send a renew message using provided socket.
  684. ///
  685. /// This method will select an existing lease from the Reply packet cache
  686. /// If there is no lease that can be renewed this method will return false.
  687. ///
  688. /// \param socket An object encapsulating socket to be used to send
  689. /// a packet.
  690. ///
  691. /// \return true if packet has been sent, false otherwise.
  692. bool sendRenew(const TestControlSocket& socket);
  693. /// \brief Send DHCPv4 REQUEST message.
  694. ///
  695. /// Method creates and sends DHCPv4 REQUEST message to the server.
  696. /// Copy of sent packet is stored in the stats_mgr4_ object to
  697. /// update statistics.
  698. ///
  699. /// \param socket socket to be used to send message.
  700. /// \param discover_pkt4 DISCOVER packet sent.
  701. /// \param offer_pkt4 OFFER packet object.
  702. ///
  703. /// \throw isc::Unexpected if unexpected error occured.
  704. /// \throw isc::InvalidOperation if Statistics Manager has not been
  705. /// initialized.
  706. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  707. void sendRequest4(const TestControlSocket& socket,
  708. const dhcp::Pkt4Ptr& discover_pkt4,
  709. const dhcp::Pkt4Ptr& offer_pkt4);
  710. /// \brief Send DHCPv4 REQUEST message from template.
  711. ///
  712. /// Method sends DHCPv4 REQUEST message from template.
  713. /// Copy of sent packet is stored in the stats_mgr4_ object to
  714. /// update statistics.
  715. ///
  716. /// \param socket socket to be used to send message.
  717. /// \param template_buf buffer holding template packet.
  718. /// \param discover_pkt4 DISCOVER packet sent.
  719. /// \param offer_pkt4 OFFER packet received.
  720. ///
  721. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  722. void sendRequest4(const TestControlSocket& socket,
  723. const std::vector<uint8_t>& template_buf,
  724. const dhcp::Pkt4Ptr& discover_pkt4,
  725. const dhcp::Pkt4Ptr& offer_pkt4);
  726. /// \brief Send DHCPv6 REQUEST message.
  727. ///
  728. /// Method creates and sends DHCPv6 REQUEST message to the server
  729. /// with the following options:
  730. /// - D6O_ELAPSED_TIME
  731. /// - D6O_CLIENTID
  732. /// - D6O_SERVERID
  733. /// Copy of sent packet is stored in the stats_mgr6_ object to
  734. /// update statistics.
  735. ///
  736. /// \param socket socket to be used to send message.
  737. /// \param advertise_pkt6 ADVERTISE packet object.
  738. /// \throw isc::Unexpected if unexpected error occured.
  739. /// \throw isc::InvalidOperation if Statistics Manager has not been
  740. /// initialized.
  741. ///
  742. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  743. void sendRequest6(const TestControlSocket& socket,
  744. const dhcp::Pkt6Ptr& advertise_pkt6);
  745. /// \brief Send DHCPv6 REQUEST message from template.
  746. ///
  747. /// Method sends DHCPv6 REQUEST message from template.
  748. /// Copy of sent packet is stored in the stats_mgr6_ object to
  749. /// update statistics.
  750. ///
  751. /// \param socket socket to be used to send message.
  752. /// \param template_buf packet template buffer.
  753. /// \param advertise_pkt6 ADVERTISE packet object.
  754. ///
  755. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  756. void sendRequest6(const TestControlSocket& socket,
  757. const std::vector<uint8_t>& template_buf,
  758. const dhcp::Pkt6Ptr& advertise_pkt6);
  759. /// \brief Send DHCPv6 SOLICIT message.
  760. ///
  761. /// Method creates and sends DHCPv6 SOLICIT message to the server
  762. /// with the following options:
  763. /// - D6O_ELAPSED_TIME,
  764. /// - D6O_RAPID_COMMIT if rapid commit is requested in command line,
  765. /// - D6O_CLIENTID,
  766. /// - D6O_ORO (Option Request Option),
  767. /// - D6O_IA_NA.
  768. /// Copy of sent packet is stored in the stats_mgr6_ object to
  769. /// update statistics.
  770. ///
  771. /// \param socket socket to be used to send the message.
  772. /// \param preload mode, packets not included in statistics.
  773. ///
  774. /// \throw isc::Unexpected if failed to create new packet instance.
  775. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  776. void sendSolicit6(const TestControlSocket& socket,
  777. const bool preload = false);
  778. /// \brief Send DHCPv6 SOLICIT message from template.
  779. ///
  780. /// Method sends DHCPv6 SOLICIT message from template.
  781. /// Copy of sent packet is stored in the stats_mgr6_ object to
  782. /// update statistics.
  783. ///
  784. /// \param socket socket to be used to send the message.
  785. /// \param template_buf packet template buffer.
  786. /// \param preload mode, packets not included in statistics.
  787. ///
  788. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  789. void sendSolicit6(const TestControlSocket& socket,
  790. const std::vector<uint8_t>& template_buf,
  791. const bool preload = false);
  792. /// \brief Set default DHCPv4 packet parameters.
  793. ///
  794. /// This method sets default parameters on the DHCPv4 packet:
  795. /// - interface name,
  796. /// - local port = 68 (DHCP client port),
  797. /// - remote port = 67 (DHCP server port),
  798. /// - server's address,
  799. /// - GIADDR = local address where socket is bound to,
  800. /// - hops = 1 (pretending that we are a relay)
  801. ///
  802. /// \param socket socket used to send the packet.
  803. /// \param pkt reference to packet to be configured.
  804. void setDefaults4(const TestControlSocket& socket,
  805. const dhcp::Pkt4Ptr& pkt);
  806. /// \brief Set default DHCPv6 packet parameters.
  807. ///
  808. /// This method sets default parameters on the DHCPv6 packet:
  809. /// - interface name,
  810. /// - interface index,
  811. /// - local port,
  812. /// - remote port,
  813. /// - local address,
  814. /// - remote address (server).
  815. ///
  816. /// \param socket socket used to send the packet.
  817. /// \param pkt reference to packet to be configured.
  818. void setDefaults6(const TestControlSocket& socket,
  819. const dhcp::Pkt6Ptr& pkt);
  820. /// \brief Find if diagnostic flag has been set.
  821. ///
  822. /// \param diag diagnostic flag (a,e,i,s,r,t,T).
  823. /// \return true if diagnostics flag has been set.
  824. bool testDiags(const char diag) const;
  825. /// \brief Update due time to initiate next chunk of exchanges.
  826. ///
  827. /// Method updates due time to initiate next chunk of exchanges.
  828. /// Function takes current time, last sent packet's time and
  829. /// expected rate in its calculations.
  830. ///
  831. /// \param last_sent A time when the last exchange was initiated.
  832. /// \param rate A rate at which exchangesa re initiated
  833. /// \param [out] send_due A reference to the time object to be updated
  834. /// with the next due time.
  835. void updateSendDue(const boost::posix_time::ptime& last_sent,
  836. const int rate,
  837. boost::posix_time::ptime& send_due);
  838. private:
  839. /// \brief Copies IA_NA or IA_PD option from one packet to another.
  840. ///
  841. /// This function checks the lease-type specified in the command line
  842. /// with option -e<lease-type>. If 'address-only' value has been specified
  843. /// this function expects that IA_NA option is present in the packet
  844. /// encapsulated by pkt_from object. If 'prefix-only' value has been
  845. /// specified, this function expects that IA_PD option is present in the
  846. /// packet encapsulated by pkt_to object.
  847. ///
  848. /// \param [in] pkt_from A packet from which options should be copied.
  849. /// \param [out] pkt_to A packet to which options should be copied.
  850. ///
  851. /// \throw isc::perfdhcp::OptionNotFound if a required option is not
  852. /// found in the packet from which options should be copied.
  853. /// \throw isc::BadValue if any of the specified pointers to packets
  854. /// is NULL.
  855. void copyIaOptions(const dhcp::Pkt6Ptr& pkt_from, dhcp::Pkt6Ptr& pkt_to);
  856. /// \brief Convert binary value to hex string.
  857. ///
  858. /// \todo Consider moving this function to src/lib/util.
  859. ///
  860. /// \param b byte to convert.
  861. /// \return hex string.
  862. std::string byte2Hex(const uint8_t b) const;
  863. /// \brief Calculate elapsed time between two packets.
  864. ///
  865. /// \param T Pkt4Ptr or Pkt6Ptr class.
  866. /// \param pkt1 first packet.
  867. /// \param pkt2 second packet.
  868. /// \throw InvalidOperation if packet timestamps are invalid.
  869. /// \return elapsed time in milliseconds between pkt1 and pkt2.
  870. template<class T>
  871. uint32_t getElapsedTime(const T& pkt1, const T& pkt2);
  872. /// \brief Return elapsed time offset in a packet.
  873. ///
  874. /// \return elapsed time offset in packet.
  875. int getElapsedTimeOffset() const;
  876. /// \brief Return randomization offset in a packet.
  877. ///
  878. /// \return randomization offset in packet.
  879. int getRandomOffset(const int arg_idx) const;
  880. /// \brief Return requested ip offset in a packet.
  881. ///
  882. /// \return randomization offset in a packet.
  883. int getRequestedIpOffset() const;
  884. /// \brief Return server id offset in a packet.
  885. ///
  886. /// \return server id offset in packet.
  887. int getServerIdOffset() const;
  888. /// \brief Return transaction id offset in a packet.
  889. ///
  890. /// \param arg_idx command line argument index to be used.
  891. /// If multiple -X parameters specifed it points to the
  892. /// one to be used.
  893. /// \return transaction id offset in packet.
  894. int getTransactionIdOffset(const int arg_idx) const;
  895. /// \brief Get number of received packets.
  896. ///
  897. /// Get the number of received packets from the Statistics Manager.
  898. /// Function may throw if Statistics Manager object is not
  899. /// initialized.
  900. /// \param xchg_type packet exchange type.
  901. /// \return number of received packets.
  902. uint64_t getRcvdPacketsNum(const ExchangeType xchg_type) const;
  903. /// \brief Get number of sent packets.
  904. ///
  905. /// Get the number of sent packets from the Statistics Manager.
  906. /// Function may throw if Statistics Manager object is not
  907. /// initialized.
  908. /// \param xchg_type packet exchange type.
  909. /// \return number of sent packets.
  910. uint64_t getSentPacketsNum(const ExchangeType xchg_type) const;
  911. /// \brief Handle child signal.
  912. ///
  913. /// Function handles child signal by waiting for
  914. /// the process to complete.
  915. ///
  916. /// \param sig signal (ignored)
  917. static void handleChild(int sig);
  918. /// \brief Handle interrupt signal.
  919. ///
  920. /// Function sets flag indicating that program has been
  921. /// interrupted.
  922. ///
  923. /// \param sig signal (ignored)
  924. static void handleInterrupt(int sig);
  925. /// \brief Print main diagnostics data.
  926. ///
  927. /// Method prints main diagnostics data.
  928. void printDiagnostics() const;
  929. /// \brief Print template information
  930. ///
  931. /// \param packet_type packet type.
  932. void printTemplate(const uint8_t packet_type) const;
  933. /// \brief Print templates information.
  934. ///
  935. /// Method prints information about data offsets
  936. /// in packet templates and their contents.
  937. void printTemplates() const;
  938. /// \brief Read DHCP message template from file.
  939. ///
  940. /// Method reads DHCP message template from file and
  941. /// converts it to binary format. Read data is appended
  942. /// to template_buffers_ vector.
  943. ///
  944. /// \param file_name name of the packet template file.
  945. /// \throw isc::OutOfRange if file is empty or has odd number
  946. /// of hexadecimal digits.
  947. /// \throw isc::BadValue if file contains characters other than
  948. /// spaces or hexadecimal digits.
  949. void readPacketTemplate(const std::string& file_name);
  950. /// \brief Run wrapped command.
  951. ///
  952. /// \param do_stop execute wrapped command with "stop" argument.
  953. void runWrapped(bool do_stop = false) const;
  954. /// \brief Convert vector in hexadecimal string.
  955. ///
  956. /// \todo Consider moving this function to src/lib/util.
  957. ///
  958. /// \param vec vector to be converted.
  959. /// \param separator separator.
  960. std::string vector2Hex(const std::vector<uint8_t>& vec,
  961. const std::string& separator = "") const;
  962. boost::posix_time::ptime send_due_; ///< Due time to initiate next chunk
  963. ///< of exchanges.
  964. boost::posix_time::ptime last_sent_; ///< Indicates when the last exchange
  965. ///< was initiated.
  966. boost::posix_time::ptime renew_due_; ///< Due time to send next set of
  967. ///< Renew requests.
  968. boost::posix_time::ptime last_renew_; ///< Indicates when the last Renew
  969. ///< was attempted.
  970. boost::posix_time::ptime last_report_; ///< Last intermediate report time.
  971. StatsMgr4Ptr stats_mgr4_; ///< Statistics Manager 4.
  972. StatsMgr6Ptr stats_mgr6_; ///< Statistics Manager 6.
  973. PacketStorage<dhcp::Pkt6> reply_storage_; ///< A storage for reply messages.
  974. NumberGeneratorPtr transid_gen_; ///< Transaction id generator.
  975. NumberGeneratorPtr macaddr_gen_; ///< Numbers generator for MAC address.
  976. /// Buffer holding server id received in first packet
  977. dhcp::OptionBuffer first_packet_serverid_;
  978. /// Packet template buffers.
  979. TemplateBufferCollection template_buffers_;
  980. /// First packets send. They are used at the end of the test
  981. /// to print packet templates when diagnostics flag T is specifed.
  982. std::map<uint8_t, dhcp::Pkt4Ptr> template_packets_v4_;
  983. std::map<uint8_t, dhcp::Pkt6Ptr> template_packets_v6_;
  984. static bool interrupted_; ///< Is program interrupted.
  985. };
  986. } // namespace perfdhcp
  987. } // namespace isc
  988. #endif // TEST_CONTROL_H