test_control.h 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  1. // Copyright (C) 2012-2014 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 "rate_control.h"
  18. #include "stats_mgr.h"
  19. #include <dhcp/iface_mgr.h>
  20. #include <dhcp/dhcp6.h>
  21. #include <dhcp/pkt4.h>
  22. #include <dhcp/pkt6.h>
  23. #include <boost/noncopyable.hpp>
  24. #include <boost/shared_ptr.hpp>
  25. #include <boost/function.hpp>
  26. #include <boost/date_time/posix_time/posix_time.hpp>
  27. #include <string>
  28. #include <vector>
  29. namespace isc {
  30. namespace perfdhcp {
  31. /// Default transaction id offset in the packet template.
  32. static const size_t DHCPV4_TRANSID_OFFSET = 4;
  33. /// Default offset of MAC's last octet in the packet template..
  34. static const size_t DHCPV4_RANDOMIZATION_OFFSET = 35;
  35. /// Default elapsed time offset in the packet template.
  36. static const size_t DHCPV4_ELAPSED_TIME_OFFSET = 8;
  37. /// Default server id offset in the packet template.
  38. static const size_t DHCPV4_SERVERID_OFFSET = 54;
  39. /// Default requested ip offset in the packet template.
  40. static const size_t DHCPV4_REQUESTED_IP_OFFSET = 240;
  41. /// Default DHCPV6 transaction id offset in t the packet template.
  42. static const size_t DHCPV6_TRANSID_OFFSET = 1;
  43. /// Default DHCPV6 randomization offset (last octet of DUID)
  44. /// in the packet template.
  45. static const size_t DHCPV6_RANDOMIZATION_OFFSET = 21;
  46. /// Default DHCPV6 elapsed time offset in the packet template.
  47. static const size_t DHCPV6_ELAPSED_TIME_OFFSET = 84;
  48. /// Default DHCPV6 server id offset in the packet template.
  49. static const size_t DHCPV6_SERVERID_OFFSET = 22;
  50. /// Default DHCPV6 IA_NA offset in the packet template.
  51. static const size_t DHCPV6_IA_NA_OFFSET = 40;
  52. /// @brief Exception thrown when the required option is not found in a packet.
  53. class OptionNotFound : public Exception {
  54. public:
  55. OptionNotFound(const char* file, size_t line, const char* what) :
  56. isc::Exception(file, line, what) { };
  57. };
  58. /// \brief Test Control class.
  59. ///
  60. /// This singleton class is used to run the performance test with
  61. /// with \ref TestControl::run function. This function can be executed
  62. /// multiple times if desired because it resets TestControl's internal
  63. /// state every time it is executed. Prior to running \ref TestControl::run,
  64. /// one must make sure to parse command line options by calling
  65. /// \ref CommandOptions::parse. Failing to do this will result in an exception.
  66. ///
  67. /// The following major stages of the test are performed by this class:
  68. /// - set default transaction id and MAC address generators - the generator
  69. /// is an object of \ref TestControl::NumberGenerator type and it provides
  70. /// the custom randomization algorithms,
  71. /// - print command line arguments,
  72. /// - register option factory functions which are used to generate DHCP options
  73. /// being sent to a server,
  74. /// - create the socket for communication with a server,
  75. /// - read packet templates if user specified template files with '-T' command
  76. /// line option,
  77. /// - set the interrupt handler (invoked when ^C is pressed) which makes
  78. /// perfdhcp stop gracefully and print the test results before exiting,
  79. /// - executes an external command (if specified '-w' option), e.g. if user
  80. /// specified -w ./foo in the command line then program will execute
  81. /// "./foo start" at the beginning of the test and "./foo stop" when the test
  82. /// ends,
  83. /// - initialize the Statistics Manager,
  84. /// - executes the main loop:
  85. /// - calculate how many packets must be send to satisfy desired rate,
  86. /// - receive incoming packets from the server,
  87. /// - check the exit conditions - terminate the program if the exit criteria
  88. /// are fulfilled, e.g. reached maximum number of packet drops,
  89. /// - send the number of packets appropriate to satisfy the desired rate,
  90. /// - optionally print intermediate reports,
  91. /// - print statistics, e.g. achieved rate,
  92. /// - optionally print some diagnostics.
  93. ///
  94. /// With the '-w' command line option user may specify the external application
  95. /// or script to be executed. This is executed twice, first when the test starts
  96. /// and second time when the test ends. This external script or application must
  97. /// accept 'start' and 'stop' arguments. The first time it is called, it is
  98. /// called with the argument 'start' and the second time with the argument
  99. /// 'stop'.
  100. ///
  101. /// The application is executed by calling fork() to fork the current perfdhcp
  102. /// process and then call execlp() to replace the current process image with
  103. /// the new one.
  104. ///
  105. /// Option factory functions are registered using
  106. /// \ref dhcp::LibDHCP::OptionFactoryRegister. Registered factory functions
  107. /// provide a way to create options of the same type in the same way.
  108. /// When a new option instance is needed, the corresponding factory
  109. /// function is called to create it. This is done by calling
  110. /// \ref dhcp::Option::factory with DHCP message type specified as one of
  111. /// parameters. Some of the parameters passed to factory function
  112. /// may be ignored (e.g. option buffer).
  113. /// Please note that naming convention for factory functions within this
  114. /// class is as follows:
  115. /// - factoryABC4 - factory function for DHCPv4 option,
  116. /// - factoryDEF6 - factory function for DHCPv6 option,
  117. /// - factoryGHI - factory function that can be used to create either
  118. /// DHCPv4 or DHCPv6 option.
  119. class TestControl : public boost::noncopyable {
  120. public:
  121. /// Statistics Manager for DHCPv4.
  122. typedef StatsMgr<dhcp::Pkt4> StatsMgr4;
  123. /// Pointer to Statistics Manager for DHCPv4;
  124. typedef boost::shared_ptr<StatsMgr4> StatsMgr4Ptr;
  125. /// Statictics Manager for DHCPv6.
  126. typedef StatsMgr<dhcp::Pkt6> StatsMgr6;
  127. /// Pointer to Statistics Manager for DHCPv6.
  128. typedef boost::shared_ptr<StatsMgr6> StatsMgr6Ptr;
  129. /// Packet exchange type.
  130. typedef StatsMgr<>::ExchangeType ExchangeType;
  131. /// Packet template buffer.
  132. typedef std::vector<uint8_t> TemplateBuffer;
  133. /// Packet template buffers list.
  134. typedef std::vector<TemplateBuffer> TemplateBufferCollection;
  135. /// \brief Socket wrapper structure.
  136. ///
  137. /// This is the wrapper that holds descriptor of the socket
  138. /// used to run DHCP test. The wrapped socket is closed in
  139. /// the destructor. This prevents resource leaks when when
  140. /// function that created the socket ends (normally or
  141. /// when exception occurs). This structure extends parent
  142. /// structure with new field ifindex_ that holds interface
  143. /// index where socket is bound to.
  144. struct TestControlSocket : public dhcp::SocketInfo {
  145. /// Interface index.
  146. uint16_t ifindex_;
  147. /// Is socket valid. It will not be valid if the provided socket
  148. /// descriptor does not point to valid socket.
  149. bool valid_;
  150. /// \brief Constructor of socket wrapper class.
  151. ///
  152. /// This constructor uses provided socket descriptor to
  153. /// find the name of the interface where socket has been
  154. /// bound to. If provided socket descriptor is invalid then
  155. /// valid_ field is set to false;
  156. ///
  157. /// \param socket socket descriptor.
  158. TestControlSocket(const int socket);
  159. /// \brief Destructor of the socket wrapper class.
  160. ///
  161. /// Destructor closes wrapped socket.
  162. ~TestControlSocket();
  163. private:
  164. /// \brief Initialize socket data.
  165. ///
  166. /// This method initializes members of the class that Interface
  167. /// Manager holds: interface name, local address.
  168. ///
  169. /// \throw isc::BadValue if interface for specified socket
  170. /// descriptor does not exist.
  171. void initSocketData();
  172. };
  173. /// \brief Number generator class.
  174. ///
  175. /// This is default numbers generator class. The member function is
  176. /// used to generate uint32_t values. Other generator classes should
  177. /// derive from this one to implement generation algorithms
  178. /// (e.g. sequential or based on random function).
  179. class NumberGenerator {
  180. public:
  181. /// \brief Destructor.
  182. virtual ~NumberGenerator() { }
  183. /// \brief Generate number.
  184. ///
  185. /// \return Generate number.
  186. virtual uint32_t generate() = 0;
  187. };
  188. /// The default generator pointer.
  189. typedef boost::shared_ptr<NumberGenerator> NumberGeneratorPtr;
  190. /// \brief Sequential numbers generator class.
  191. class SequentialGenerator : public NumberGenerator {
  192. public:
  193. /// \brief Constructor.
  194. ///
  195. /// \param range maximum number generated. If 0 is given then
  196. /// range defaults to maximum uint32_t value.
  197. SequentialGenerator(uint32_t range = 0xFFFFFFFF) :
  198. NumberGenerator(),
  199. num_(0),
  200. range_(range) {
  201. if (range_ == 0) {
  202. range_ = 0xFFFFFFFF;
  203. }
  204. }
  205. /// \brief Generate number sequentially.
  206. ///
  207. /// \return generated number.
  208. virtual uint32_t generate() {
  209. uint32_t num = num_;
  210. num_ = (num_ + 1) % range_;
  211. return (num);
  212. }
  213. private:
  214. uint32_t num_; ///< Current number.
  215. uint32_t range_; ///< Number of unique numbers generated.
  216. };
  217. /// \brief Length of the Ethernet HW address (MAC) in bytes.
  218. ///
  219. /// \todo Make this variable length as there are cases when HW
  220. /// address is longer than this (e.g. 20 bytes).
  221. static const uint8_t HW_ETHER_LEN = 6;
  222. /// TestControl is a singleton class. This method returns reference
  223. /// to its sole instance.
  224. ///
  225. /// \return the only existing instance of test control
  226. static TestControl& instance();
  227. /// brief\ Run performance test.
  228. ///
  229. /// Method runs whole performance test. Command line options must
  230. /// be parsed prior to running this function. Otherwise function will
  231. /// throw exception.
  232. ///
  233. /// \throw isc::InvalidOperation if command line options are not parsed.
  234. /// \throw isc::Unexpected if internal Test Controller error occured.
  235. /// \return error_code, 3 if number of received packets is not equal
  236. /// to number of sent packets, 0 if everything is ok.
  237. int run();
  238. /// \brief Set new transaction id generator.
  239. ///
  240. /// \param generator generator object to be used.
  241. void setTransidGenerator(const NumberGeneratorPtr& generator) {
  242. transid_gen_.reset();
  243. transid_gen_ = generator;
  244. }
  245. /// \brief Set new MAC address generator.
  246. ///
  247. /// Set numbers generator that will be used to generate various
  248. /// MAC addresses to simulate number of clients.
  249. ///
  250. /// \param generator object to be used.
  251. void setMacAddrGenerator(const NumberGeneratorPtr& generator) {
  252. macaddr_gen_.reset();
  253. macaddr_gen_ = generator;
  254. }
  255. // We would really like following methods and members to be private but
  256. // they have to be accessible for unit-testing. Another, possibly better,
  257. // solution is to make this class friend of test class but this is not
  258. // what's followed in other classes.
  259. protected:
  260. /// \brief Default constructor.
  261. ///
  262. /// Default constructor is protected as the object can be created
  263. /// only via \ref instance method.
  264. TestControl();
  265. /// \brief Check if test exit conditions fulfilled.
  266. ///
  267. /// Method checks if the test exit conditions are fulfilled.
  268. /// Exit conditions are checked periodically from the
  269. /// main loop. Program should break the main loop when
  270. /// this method returns true. It is calling function
  271. /// responsibility to break main loop gracefully and
  272. /// cleanup after test execution.
  273. ///
  274. /// \return true if any of the exit conditions is fulfilled.
  275. bool checkExitConditions() const;
  276. /// \brief Removes cached DHCPv6 Reply packets every second.
  277. ///
  278. /// This function wipes cached Reply packets from the storage.
  279. /// The number of packets left in the storage after the call
  280. /// to this function should guarantee that the Renew packets
  281. /// can be sent at the given rate. Note that the Renew packets
  282. /// are generated for the existing leases, represented here as
  283. /// replies from the server.
  284. /// @todo Instead of cleaning packets periodically we could
  285. /// just stop adding new packets when the certain threshold
  286. /// has been reached.
  287. void cleanCachedPackets();
  288. /// \brief Creates DHCPv6 message from the Reply packet.
  289. ///
  290. /// This function creates DHCPv6 Renew or Release message using the
  291. /// data from the Reply message by copying options from the Reply
  292. /// message.
  293. ///
  294. /// \param msg_type A type of the message to be createad.
  295. /// \param reply An instance of the Reply packet which contents should
  296. /// be used to create an instance of the new message.
  297. ///
  298. /// \return created Release or Renew message
  299. /// \throw isc::BadValue if the msg_type is neither DHCPV6_RENEW nor
  300. /// DHCPV6_RELEASE or if the reply is NULL.
  301. /// \throw isc::Unexpected if mandatory options are missing in the
  302. /// Reply message.
  303. dhcp::Pkt6Ptr createMessageFromReply(const uint16_t msg_type,
  304. const dhcp::Pkt6Ptr& reply);
  305. /// \brief Factory function to create DHCPv6 ELAPSED_TIME option.
  306. ///
  307. /// This factory function creates DHCPv6 ELAPSED_TIME option instance.
  308. /// If empty buffer is passed the option buffer will be initialized
  309. /// to length 2 and values will be initialized to zeros. Otherwise
  310. /// function will initialize option buffer with values in passed buffer.
  311. ///
  312. /// \param u universe (ignored)
  313. /// \param type option-type (ignored).
  314. /// \param buf option-buffer containing option content (2 bytes) or
  315. /// empty buffer if option content has to be set to default (0) value.
  316. /// \throw if elapsed time buffer size is neither 2 nor 0.
  317. /// \return instance o the option.
  318. static dhcp::OptionPtr
  319. factoryElapsedTime6(dhcp::Option::Universe u,
  320. uint16_t type,
  321. const dhcp::OptionBuffer& buf);
  322. /// \brief Factory function to create generic option.
  323. ///
  324. /// This factory function creates option with specified universe,
  325. /// type and buf. It does not have any additional logic validating
  326. /// the buffer contents, size etc.
  327. ///
  328. /// \param u universe (V6 or V4).
  329. /// \param type option-type (ignored).
  330. /// \param buf option-buffer.
  331. /// \return instance o the option.
  332. static dhcp::OptionPtr factoryGeneric(dhcp::Option::Universe u,
  333. uint16_t type,
  334. const dhcp::OptionBuffer& buf);
  335. /// \brief Factory function to create IA_NA option.
  336. ///
  337. /// This factory function creates DHCPv6 IA_NA option instance.
  338. ///
  339. /// \todo add support for IA Address options.
  340. ///
  341. /// \param u universe (ignored).
  342. /// \param type option-type (ignored).
  343. /// \param buf option-buffer carrying IANA suboptions.
  344. /// \return instance of IA_NA option.
  345. static dhcp::OptionPtr factoryIana6(dhcp::Option::Universe u,
  346. uint16_t type,
  347. const dhcp::OptionBuffer& buf);
  348. /// \brief Factory function to create IA_PD option.
  349. ///
  350. /// this factory function creates DHCPv6 IA_PD option instance.
  351. ///
  352. /// \param u universe (ignored).
  353. /// \param type option-type (ignored).
  354. /// \param buf option-buffer carrying sub-options.
  355. static dhcp::OptionPtr factoryIapd6(dhcp::Option::Universe u,
  356. uint16_t type,
  357. const dhcp::OptionBuffer& buf);
  358. /// \brief Factory function to create DHCPv6 ORO option.
  359. ///
  360. /// This factory function creates DHCPv6 Option Request Option instance.
  361. /// The created option will contain the following set of requested options:
  362. /// - D6O_NAME_SERVERS
  363. /// - D6O_DOMAIN_SEARCH
  364. ///
  365. /// \param u universe (ignored).
  366. /// \param type option-type (ignored).
  367. /// \param buf option-buffer (ignored).
  368. /// \return instance of ORO option.
  369. static dhcp::OptionPtr
  370. factoryOptionRequestOption6(dhcp::Option::Universe u,
  371. uint16_t type,
  372. const dhcp::OptionBuffer& buf);
  373. /// \brief Factory function to create DHCPv6 RAPID_COMMIT option instance.
  374. ///
  375. /// This factory function creates DHCPv6 RAPID_COMMIT option instance.
  376. /// The buffer passed to this option must be empty because option does
  377. /// not have any payload.
  378. ///
  379. /// \param u universe (ignored).
  380. /// \param type option-type (ignored).
  381. /// \param buf option-buffer (ignored).
  382. /// \return instance of RAPID_COMMIT option..
  383. static dhcp::OptionPtr factoryRapidCommit6(dhcp::Option::Universe u,
  384. uint16_t type,
  385. const dhcp::OptionBuffer& buf);
  386. /// \brief Factory function to create DHCPv4 Request List option.
  387. ///
  388. /// This factory function creates DHCPv4 PARAMETER_REQUEST_LIST option
  389. /// instance with the following set of requested options:
  390. /// - DHO_SUBNET_MASK,
  391. /// - DHO_BROADCAST_ADDRESS,
  392. /// - DHO_TIME_OFFSET,
  393. /// - DHO_ROUTERS,
  394. /// - DHO_DOMAIN_NAME,
  395. /// - DHO_DOMAIN_NAME_SERVERS,
  396. /// - DHO_HOST_NAME.
  397. ///
  398. /// \param u universe (ignored).
  399. /// \param type option-type (ignored).
  400. /// \param buf option-buffer (ignored).
  401. /// \return instance o the generic option.
  402. static dhcp::OptionPtr factoryRequestList4(dhcp::Option::Universe u,
  403. uint16_t type,
  404. const dhcp::OptionBuffer& buf);
  405. /// \brief Generate DUID.
  406. ///
  407. /// Method generates unique DUID. The number of DUIDs it can generate
  408. /// depends on the number of simulated clients, which is specified
  409. /// from the command line. It uses \ref CommandOptions object to retrieve
  410. /// number of clients. Since the last six octets of DUID are constructed
  411. /// from the MAC address, this function uses \ref generateMacAddress
  412. /// internally to randomize the DUID.
  413. ///
  414. /// \todo add support for other types of DUID.
  415. ///
  416. /// \param [out] randomized number of bytes randomized (initial value
  417. /// is ignored).
  418. /// \throw isc::BadValue if \ref generateMacAddress throws.
  419. /// \return vector representing DUID.
  420. std::vector<uint8_t> generateDuid(uint8_t& randomized) const;
  421. /// \brief Generate MAC address.
  422. ///
  423. /// This method generates MAC address. The number of unique
  424. /// MAC addresses it can generate is determined by the number
  425. /// simulated DHCP clients specified from command line. It uses
  426. /// \ref CommandOptions object to retrieve number of clients.
  427. /// Based on this the random value is generated and added to
  428. /// the MAC address template (default MAC address).
  429. ///
  430. /// \param [out] randomized number of bytes randomized (initial
  431. /// value is ignored).
  432. /// \throw isc::BadValue if MAC address template (default or specified
  433. /// from the command line) has invalid size (expected 6 octets).
  434. /// \return generated MAC address.
  435. std::vector<uint8_t> generateMacAddress(uint8_t& randomized) const;
  436. /// \brief generate transaction id.
  437. ///
  438. /// Generate transaction id value (32-bit for DHCPv4,
  439. /// 24-bit for DHCPv6).
  440. ///
  441. /// \return generated transaction id.
  442. uint32_t generateTransid() {
  443. return (transid_gen_->generate());
  444. }
  445. /// \brief Returns a timeout for packet reception.
  446. ///
  447. /// The calculation is based on the value of the timestamp
  448. /// when the next set of packets is to be sent. If no packet is
  449. /// received until then, new packets are sent.
  450. ///
  451. /// \return A current timeout in microseconds.
  452. uint32_t getCurrentTimeout() const;
  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 or Release messages to the server.
  676. ///
  677. /// \param socket An object representing socket to be used to send packets.
  678. /// \param msg_type A type of the messages to be sent (DHCPV6_RENEW or
  679. /// DHCPV6_RELEASE).
  680. /// \param msg_num A number of messages to be sent.
  681. ///
  682. /// \return A number of messages actually sent.
  683. uint64_t sendMultipleMessages6(const TestControlSocket& socket,
  684. const uint32_t msg_type,
  685. const uint64_t msg_num);
  686. /// \brief Send DHCPv6 Renew or Release message using specified socket.
  687. ///
  688. /// This method will select an existing lease from the Reply packet cache
  689. /// If there is no lease that can be renewed or released this method will
  690. /// return false.
  691. ///
  692. /// \param msg_type A type of the message to be sent (DHCPV6_RENEW or
  693. /// DHCPV6_RELEASE).
  694. /// \param socket An object encapsulating socket to be used to send
  695. /// a packet.
  696. ///
  697. /// \return true if the message has been sent, false otherwise.
  698. bool sendMessageFromReply(const uint16_t msg_type,
  699. const TestControlSocket& socket);
  700. /// \brief Send DHCPv4 REQUEST message.
  701. ///
  702. /// Method creates and sends DHCPv4 REQUEST message to the server.
  703. /// Copy of sent packet is stored in the stats_mgr4_ object to
  704. /// update statistics.
  705. ///
  706. /// \param socket socket to be used to send message.
  707. /// \param discover_pkt4 DISCOVER packet sent.
  708. /// \param offer_pkt4 OFFER packet object.
  709. ///
  710. /// \throw isc::Unexpected if unexpected error occured.
  711. /// \throw isc::InvalidOperation if Statistics Manager has not been
  712. /// initialized.
  713. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  714. void sendRequest4(const TestControlSocket& socket,
  715. const dhcp::Pkt4Ptr& discover_pkt4,
  716. const dhcp::Pkt4Ptr& offer_pkt4);
  717. /// \brief Send DHCPv4 REQUEST message from template.
  718. ///
  719. /// Method sends DHCPv4 REQUEST message from template.
  720. /// Copy of sent packet is stored in the stats_mgr4_ object to
  721. /// update statistics.
  722. ///
  723. /// \param socket socket to be used to send message.
  724. /// \param template_buf buffer holding template packet.
  725. /// \param discover_pkt4 DISCOVER packet sent.
  726. /// \param offer_pkt4 OFFER packet received.
  727. ///
  728. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  729. void sendRequest4(const TestControlSocket& socket,
  730. const std::vector<uint8_t>& template_buf,
  731. const dhcp::Pkt4Ptr& discover_pkt4,
  732. const dhcp::Pkt4Ptr& offer_pkt4);
  733. /// \brief Send DHCPv6 REQUEST message.
  734. ///
  735. /// Method creates and sends DHCPv6 REQUEST message to the server
  736. /// with the following options:
  737. /// - D6O_ELAPSED_TIME
  738. /// - D6O_CLIENTID
  739. /// - D6O_SERVERID
  740. /// Copy of sent packet is stored in the stats_mgr6_ object to
  741. /// update statistics.
  742. ///
  743. /// \param socket socket to be used to send message.
  744. /// \param advertise_pkt6 ADVERTISE packet object.
  745. /// \throw isc::Unexpected if unexpected error occured.
  746. /// \throw isc::InvalidOperation if Statistics Manager has not been
  747. /// initialized.
  748. ///
  749. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  750. void sendRequest6(const TestControlSocket& socket,
  751. const dhcp::Pkt6Ptr& advertise_pkt6);
  752. /// \brief Send DHCPv6 REQUEST message from template.
  753. ///
  754. /// Method sends DHCPv6 REQUEST message from template.
  755. /// Copy of sent packet is stored in the stats_mgr6_ object to
  756. /// update statistics.
  757. ///
  758. /// \param socket socket to be used to send message.
  759. /// \param template_buf packet template buffer.
  760. /// \param advertise_pkt6 ADVERTISE packet object.
  761. ///
  762. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  763. void sendRequest6(const TestControlSocket& socket,
  764. const std::vector<uint8_t>& template_buf,
  765. const dhcp::Pkt6Ptr& advertise_pkt6);
  766. /// \brief Send DHCPv6 SOLICIT message.
  767. ///
  768. /// Method creates and sends DHCPv6 SOLICIT message to the server
  769. /// with the following options:
  770. /// - D6O_ELAPSED_TIME,
  771. /// - D6O_RAPID_COMMIT if rapid commit is requested in command line,
  772. /// - D6O_CLIENTID,
  773. /// - D6O_ORO (Option Request Option),
  774. /// - D6O_IA_NA.
  775. /// Copy of sent packet is stored in the stats_mgr6_ object to
  776. /// update statistics.
  777. ///
  778. /// \param socket socket to be used to send the message.
  779. /// \param preload mode, packets not included in statistics.
  780. ///
  781. /// \throw isc::Unexpected if failed to create new packet instance.
  782. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  783. void sendSolicit6(const TestControlSocket& socket,
  784. const bool preload = false);
  785. /// \brief Send DHCPv6 SOLICIT message from template.
  786. ///
  787. /// Method sends DHCPv6 SOLICIT message from template.
  788. /// Copy of sent packet is stored in the stats_mgr6_ object to
  789. /// update statistics.
  790. ///
  791. /// \param socket socket to be used to send the message.
  792. /// \param template_buf packet template buffer.
  793. /// \param preload mode, packets not included in statistics.
  794. ///
  795. /// \throw isc::dhcp::SocketWriteError if failed to send the packet.
  796. void sendSolicit6(const TestControlSocket& socket,
  797. const std::vector<uint8_t>& template_buf,
  798. const bool preload = false);
  799. /// \brief Set default DHCPv4 packet parameters.
  800. ///
  801. /// This method sets default parameters on the DHCPv4 packet:
  802. /// - interface name,
  803. /// - local port = 68 (DHCP client port),
  804. /// - remote port = 67 (DHCP server port),
  805. /// - server's address,
  806. /// - GIADDR = local address where socket is bound to,
  807. /// - hops = 1 (pretending that we are a relay)
  808. ///
  809. /// \param socket socket used to send the packet.
  810. /// \param pkt reference to packet to be configured.
  811. void setDefaults4(const TestControlSocket& socket,
  812. const dhcp::Pkt4Ptr& pkt);
  813. /// \brief Set default DHCPv6 packet parameters.
  814. ///
  815. /// This method sets default parameters on the DHCPv6 packet:
  816. /// - interface name,
  817. /// - interface index,
  818. /// - local port,
  819. /// - remote port,
  820. /// - local address,
  821. /// - remote address (server).
  822. ///
  823. /// \param socket socket used to send the packet.
  824. /// \param pkt reference to packet to be configured.
  825. void setDefaults6(const TestControlSocket& socket,
  826. const dhcp::Pkt6Ptr& pkt);
  827. /// \brief Find if diagnostic flag has been set.
  828. ///
  829. /// \param diag diagnostic flag (a,e,i,s,r,t,T).
  830. /// \return true if diagnostics flag has been set.
  831. bool testDiags(const char diag) const;
  832. protected:
  833. /// \brief Increments counter of late sent messages if required.
  834. ///
  835. /// This function checks if the message or set of messages of a given type,
  836. /// were sent later than their due time. If they were sent late, it is
  837. /// an indication that the perfdhcp doesn't catch up with the desired rate
  838. /// for sending messages.
  839. ///
  840. /// \param rate_control An object tracking due times for a particular
  841. /// type of messages.
  842. void checkLateMessages(RateControl& rate_control);
  843. /// \brief Copies IA_NA or IA_PD option from one packet to another.
  844. ///
  845. /// This function checks the lease-type specified in the command line
  846. /// with option -e<lease-type>. If 'address-only' value has been specified
  847. /// this function expects that IA_NA option is present in the packet
  848. /// encapsulated by pkt_from object. If 'prefix-only' value has been
  849. /// specified, this function expects that IA_PD option is present in the
  850. /// packet encapsulated by pkt_to object.
  851. ///
  852. /// \param [in] pkt_from A packet from which options should be copied.
  853. /// \param [out] pkt_to A packet to which options should be copied.
  854. ///
  855. /// \throw isc::perfdhcp::OptionNotFound if a required option is not
  856. /// found in the packet from which options should be copied.
  857. /// \throw isc::BadValue if any of the specified pointers to packets
  858. /// is NULL.
  859. void copyIaOptions(const dhcp::Pkt6Ptr& pkt_from, dhcp::Pkt6Ptr& pkt_to);
  860. /// \brief Convert binary value to hex string.
  861. ///
  862. /// \todo Consider moving this function to src/lib/util.
  863. ///
  864. /// \param b byte to convert.
  865. /// \return hex string.
  866. std::string byte2Hex(const uint8_t b) const;
  867. /// \brief Calculate elapsed time between two packets.
  868. ///
  869. /// This function calculates the time elapsed between two packets. If
  870. /// the timestamp of the pkt2 is greater than timestamp of the pkt1,
  871. /// the positive value is returned. If the pkt2 timestamp is equal or
  872. /// less than pkt1 timestamp, 0 is returned.
  873. ///
  874. /// \tparam T Pkt4Ptr or Pkt6Ptr class.
  875. /// \param pkt1 first packet.
  876. /// \param pkt2 second packet.
  877. /// \throw InvalidOperation if packet timestamps are invalid.
  878. /// \return elapsed time in milliseconds between pkt1 and pkt2.
  879. template<class T>
  880. uint32_t getElapsedTime(const T& pkt1, const T& pkt2);
  881. /// \brief Return elapsed time offset in a packet.
  882. ///
  883. /// \return elapsed time offset in packet.
  884. int getElapsedTimeOffset() const;
  885. /// \brief Return randomization offset in a packet.
  886. ///
  887. /// \return randomization offset in packet.
  888. int getRandomOffset(const int arg_idx) const;
  889. /// \brief Return requested ip offset in a packet.
  890. ///
  891. /// \return randomization offset in a packet.
  892. int getRequestedIpOffset() const;
  893. /// \brief Return server id offset in a packet.
  894. ///
  895. /// \return server id offset in packet.
  896. int getServerIdOffset() const;
  897. /// \brief Return transaction id offset in a packet.
  898. ///
  899. /// \param arg_idx command line argument index to be used.
  900. /// If multiple -X parameters specifed it points to the
  901. /// one to be used.
  902. /// \return transaction id offset in packet.
  903. int getTransactionIdOffset(const int arg_idx) const;
  904. /// \brief Get number of received packets.
  905. ///
  906. /// Get the number of received packets from the Statistics Manager.
  907. /// Function may throw if Statistics Manager object is not
  908. /// initialized.
  909. /// \param xchg_type packet exchange type.
  910. /// \return number of received packets.
  911. uint64_t getRcvdPacketsNum(const ExchangeType xchg_type) const;
  912. /// \brief Get number of sent packets.
  913. ///
  914. /// Get the number of sent packets from the Statistics Manager.
  915. /// Function may throw if Statistics Manager object is not
  916. /// initialized.
  917. /// \param xchg_type packet exchange type.
  918. /// \return number of sent packets.
  919. uint64_t getSentPacketsNum(const ExchangeType xchg_type) const;
  920. /// \brief Handle child signal.
  921. ///
  922. /// Function handles child signal by waiting for
  923. /// the process to complete.
  924. ///
  925. /// \param sig signal (ignored)
  926. static void handleChild(int sig);
  927. /// \brief Handle interrupt signal.
  928. ///
  929. /// Function sets flag indicating that program has been
  930. /// interrupted.
  931. ///
  932. /// \param sig signal (ignored)
  933. static void handleInterrupt(int sig);
  934. /// \brief Print main diagnostics data.
  935. ///
  936. /// Method prints main diagnostics data.
  937. void printDiagnostics() const;
  938. /// \brief Print template information
  939. ///
  940. /// \param packet_type packet type.
  941. void printTemplate(const uint8_t packet_type) const;
  942. /// \brief Print templates information.
  943. ///
  944. /// Method prints information about data offsets
  945. /// in packet templates and their contents.
  946. void printTemplates() const;
  947. /// \brief Read DHCP message template from file.
  948. ///
  949. /// Method reads DHCP message template from file and
  950. /// converts it to binary format. Read data is appended
  951. /// to template_buffers_ vector.
  952. ///
  953. /// \param file_name name of the packet template file.
  954. /// \throw isc::OutOfRange if file is empty or has odd number
  955. /// of hexadecimal digits.
  956. /// \throw isc::BadValue if file contains characters other than
  957. /// spaces or hexadecimal digits.
  958. void readPacketTemplate(const std::string& file_name);
  959. /// \brief Run wrapped command.
  960. ///
  961. /// \param do_stop execute wrapped command with "stop" argument.
  962. void runWrapped(bool do_stop = false) const;
  963. /// \brief Convert vector in hexadecimal string.
  964. ///
  965. /// \todo Consider moving this function to src/lib/util.
  966. ///
  967. /// \param vec vector to be converted.
  968. /// \param separator separator.
  969. std::string vector2Hex(const std::vector<uint8_t>& vec,
  970. const std::string& separator = "") const;
  971. /// \brief A rate control class for Discover and Solicit messages.
  972. RateControl basic_rate_control_;
  973. /// \brief A rate control class for Renew messages.
  974. RateControl renew_rate_control_;
  975. /// \brief A rate control class for Release messages.
  976. RateControl release_rate_control_;
  977. boost::posix_time::ptime last_report_; ///< Last intermediate report time.
  978. StatsMgr4Ptr stats_mgr4_; ///< Statistics Manager 4.
  979. StatsMgr6Ptr stats_mgr6_; ///< Statistics Manager 6.
  980. PacketStorage<dhcp::Pkt6> reply_storage_; ///< A storage for reply messages.
  981. NumberGeneratorPtr transid_gen_; ///< Transaction id generator.
  982. NumberGeneratorPtr macaddr_gen_; ///< Numbers generator for MAC address.
  983. /// Buffer holding server id received in first packet
  984. dhcp::OptionBuffer first_packet_serverid_;
  985. /// Packet template buffers.
  986. TemplateBufferCollection template_buffers_;
  987. /// First packets send. They are used at the end of the test
  988. /// to print packet templates when diagnostics flag T is specifed.
  989. std::map<uint8_t, dhcp::Pkt4Ptr> template_packets_v4_;
  990. std::map<uint8_t, dhcp::Pkt6Ptr> template_packets_v6_;
  991. static bool interrupted_; ///< Is program interrupted.
  992. };
  993. } // namespace perfdhcp
  994. } // namespace isc
  995. #endif // TEST_CONTROL_H