test_control.h 39 KB

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