test_control.h 40 KB

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