test_control.h 44 KB

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