test_control.h 39 KB

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