test_control.h 45 KB

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