test_control.h 40 KB

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