test_control.cc 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  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. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <stdint.h>
  17. #include <unistd.h>
  18. #include <boost/date_time/posix_time/posix_time.hpp>
  19. #include <exceptions/exceptions.h>
  20. #include <asiolink/io_address.h>
  21. #include <dhcp/libdhcp++.h>
  22. #include <dhcp/iface_mgr.h>
  23. #include <dhcp/dhcp4.h>
  24. #include "test_control.h"
  25. #include "command_options.h"
  26. using namespace std;
  27. using namespace boost;
  28. using namespace boost::posix_time;
  29. using namespace isc;
  30. using namespace isc::dhcp;
  31. using namespace isc::asiolink;
  32. namespace isc {
  33. namespace perfdhcp {
  34. TestControl::TestControlSocket::TestControlSocket(int socket) :
  35. socket_(socket),
  36. addr_("127.0.0.1") {
  37. initSocketData();
  38. }
  39. TestControl::TestControlSocket::~TestControlSocket() {
  40. IfaceMgr::instance().closeSockets();
  41. }
  42. void
  43. TestControl::TestControlSocket::initSocketData() {
  44. const IfaceMgr::IfaceCollection& ifaces =
  45. IfaceMgr::instance().getIfaces();
  46. for (IfaceMgr::IfaceCollection::const_iterator it = ifaces.begin();
  47. it != ifaces.end();
  48. ++it) {
  49. const IfaceMgr::SocketCollection& socket_collection =
  50. it->getSockets();
  51. for (IfaceMgr::SocketCollection::const_iterator s =
  52. socket_collection.begin();
  53. s != socket_collection.end();
  54. ++s) {
  55. if (s->sockfd_ == socket_) {
  56. iface_ = it->getName();
  57. ifindex_ = it->getIndex();
  58. addr_ = s->addr_;
  59. return;
  60. }
  61. }
  62. }
  63. isc_throw(BadValue, "interface for for specified socket "
  64. "descriptor not found");
  65. }
  66. TestControl&
  67. TestControl::instance() {
  68. static TestControl test_control;
  69. return (test_control);
  70. }
  71. TestControl::TestControl() {
  72. reset();
  73. }
  74. bool
  75. TestControl::checkExitConditions() const {
  76. CommandOptions& options = CommandOptions::instance();
  77. // Check if test period passed..
  78. if (options.getPeriod() != 0) {
  79. if (options.getIpVersion() == 4) {
  80. time_period period(stats_mgr4_->getTestPeriod());
  81. if (period.length().total_seconds() >= options.getPeriod()) {
  82. return true;
  83. }
  84. } else if (options.getIpVersion() == 6) {
  85. time_period period = stats_mgr6_->getTestPeriod();
  86. if (period.length().total_seconds() >= options.getPeriod()) {
  87. return true;
  88. }
  89. }
  90. }
  91. // Check if we reached maximum number of DISCOVER/SOLICIT sent.
  92. if (options.getNumRequests().size() > 0) {
  93. if (options.getIpVersion() == 4) {
  94. if (getSentPacketsNum(StatsMgr4::XCHG_DO) >=
  95. options.getNumRequests()[0]) {
  96. return(true);
  97. }
  98. } else if (options.getIpVersion() == 6) {
  99. if (stats_mgr6_->getSentPacketsNum(StatsMgr6::XCHG_SA) >=
  100. options.getNumRequests()[0]) {
  101. return(true);
  102. }
  103. }
  104. }
  105. // Check if we reached maximum number REQUEST packets.
  106. if (options.getNumRequests().size() == 2) {
  107. if (options.getIpVersion() == 4) {
  108. if (stats_mgr4_->getSentPacketsNum(StatsMgr4::XCHG_RA) >=
  109. options.getNumRequests()[1]) {
  110. return(true);
  111. }
  112. } else if (options.getIpVersion() == 6) {
  113. if (stats_mgr6_->getSentPacketsNum(StatsMgr6::XCHG_RR) >=
  114. options.getNumRequests()[1]) {
  115. return(true);
  116. }
  117. }
  118. }
  119. // Check if we reached maximum number of drops of OFFER/ADVERTISE packets.
  120. if (options.getMaxDrop().size() > 0) {
  121. if (options.getIpVersion() == 4) {
  122. if (stats_mgr4_->getDroppedPacketsNum(StatsMgr4::XCHG_DO) >=
  123. options.getMaxDrop()[0]) {
  124. return(true);
  125. }
  126. } else if (options.getIpVersion() == 6) {
  127. if (stats_mgr6_->getDroppedPacketsNum(StatsMgr6::XCHG_SA) >=
  128. options.getMaxDrop()[0]) {
  129. return(true);
  130. }
  131. }
  132. }
  133. // Check if we reached maximum number of drops of ACK/REPLY packets.
  134. if (options.getMaxDrop().size() == 2) {
  135. if (options.getIpVersion() == 4) {
  136. if (stats_mgr4_->getDroppedPacketsNum(StatsMgr4::XCHG_RA) >=
  137. options.getMaxDrop()[1]) {
  138. return(true);
  139. }
  140. } else if (options.getIpVersion() == 6) {
  141. if (stats_mgr6_->getDroppedPacketsNum(StatsMgr6::XCHG_RR) >=
  142. options.getMaxDrop()[1]) {
  143. return(true);
  144. }
  145. }
  146. }
  147. // Check if we reached maximum drops percentage of OFFER/ADVERTISE packets.
  148. if (options.getMaxDropPercentage().size() > 0) {
  149. if (options.getIpVersion() == 4) {
  150. if ((stats_mgr4_->getSentPacketsNum(StatsMgr4::XCHG_DO) > 10) &&
  151. ((100. * stats_mgr4_->getDroppedPacketsNum(StatsMgr4::XCHG_DO) /
  152. stats_mgr4_->getSentPacketsNum(StatsMgr4::XCHG_DO)) >=
  153. options.getMaxDropPercentage()[0])) {
  154. return(true);
  155. }
  156. } else if (options.getIpVersion() == 6) {
  157. if ((stats_mgr6_->getSentPacketsNum(StatsMgr6::XCHG_SA) > 10) &&
  158. ((100. * stats_mgr6_->getDroppedPacketsNum(StatsMgr6::XCHG_SA) /
  159. stats_mgr6_->getSentPacketsNum(StatsMgr6::XCHG_SA)) >=
  160. options.getMaxDropPercentage()[0])) {
  161. return(true);
  162. }
  163. }
  164. }
  165. // Check if we reached maximum drops percentage of ACK/REPLY packets.
  166. if (options.getMaxDropPercentage().size() == 2) {
  167. if (options.getIpVersion() == 4) {
  168. if ((stats_mgr4_->getSentPacketsNum(StatsMgr4::XCHG_RA) > 10) &&
  169. ((100. * stats_mgr4_->getDroppedPacketsNum(StatsMgr4::XCHG_RA) /
  170. stats_mgr4_->getSentPacketsNum(StatsMgr4::XCHG_RA)) >=
  171. options.getMaxDropPercentage()[1])) {
  172. return(true);
  173. }
  174. } else if (options.getIpVersion() == 6) {
  175. if ((stats_mgr6_->getSentPacketsNum(StatsMgr6::XCHG_RR) > 10) &&
  176. ((100. * stats_mgr6_->getDroppedPacketsNum(StatsMgr6::XCHG_RR) /
  177. stats_mgr6_->getSentPacketsNum(StatsMgr6::XCHG_RR)) >=
  178. options.getMaxDropPercentage()[1])) {
  179. return(true);
  180. }
  181. }
  182. }
  183. return(false);
  184. }
  185. OptionPtr
  186. TestControl::factoryElapsedTime6(Option::Universe, uint16_t,
  187. const OptionBuffer& buf) {
  188. if (buf.size() == 2) {
  189. return OptionPtr(new Option(Option::V6, D6O_ELAPSED_TIME, buf));
  190. } else if (buf.size() == 0) {
  191. return OptionPtr(new Option(Option::V6, D6O_ELAPSED_TIME,
  192. OptionBuffer(2, 0)));
  193. }
  194. isc_throw(isc::BadValue,
  195. "elapsed time option buffer size has to be 0 or 2");
  196. }
  197. OptionPtr
  198. TestControl::factoryGeneric(Option::Universe u, uint16_t type,
  199. const OptionBuffer& buf) {
  200. OptionPtr opt(new Option(u, type, buf));
  201. return opt;
  202. }
  203. OptionPtr
  204. TestControl::factoryIana6(Option::Universe, uint16_t,
  205. const OptionBuffer& buf) {
  206. const uint8_t buf_array[] = {
  207. 0, 0, 0, 1, // IAID = 1
  208. 0, 0, 3600 >> 8, 3600 && 0xff, // T1 = 3600
  209. 0, 0, 5400 >> 8, 5400 & 0xff, // T2 = 5400
  210. };
  211. OptionBuffer buf_ia_na(buf_array, buf_array + sizeof(buf_array));
  212. for (int i = 0; i < buf.size(); ++i) {
  213. buf_ia_na.push_back(buf[i]);
  214. }
  215. return OptionPtr(new Option(Option::V6, D6O_IA_NA, buf_ia_na));
  216. }
  217. OptionPtr
  218. TestControl::factoryRapidCommit6(Option::Universe, uint16_t,
  219. const OptionBuffer&) {
  220. return OptionPtr(new Option(Option::V6, D6O_RAPID_COMMIT, OptionBuffer()));
  221. }
  222. OptionPtr
  223. TestControl::factoryOptionRequestOption6(Option::Universe,
  224. uint16_t,
  225. const OptionBuffer&) {
  226. const uint8_t buf_array[] = {
  227. D6O_NAME_SERVERS,
  228. D6O_DOMAIN_SEARCH
  229. };
  230. OptionBuffer buf_with_options(buf_array, buf_array + sizeof(buf_array));
  231. return OptionPtr(new Option(Option::V6, D6O_ORO, buf_with_options));
  232. }
  233. OptionPtr
  234. TestControl::factoryRequestList4(Option::Universe u,
  235. uint16_t type,
  236. const OptionBuffer& buf) {
  237. const uint8_t buf_array[] = {
  238. DHO_SUBNET_MASK,
  239. DHO_BROADCAST_ADDRESS,
  240. DHO_TIME_OFFSET,
  241. DHO_ROUTERS,
  242. DHO_DOMAIN_NAME,
  243. DHO_DOMAIN_NAME_SERVERS,
  244. DHO_HOST_NAME
  245. };
  246. OptionBuffer buf_with_options(buf_array, buf_array + sizeof(buf_array));
  247. OptionPtr opt(new Option(u, type, buf));
  248. opt->setData(buf_with_options.begin(), buf_with_options.end());
  249. return opt;
  250. }
  251. std::vector<uint8_t>
  252. TestControl::generateMacAddress() const {
  253. CommandOptions& options = CommandOptions::instance();
  254. uint32_t clients_num = options.getClientsNum();
  255. if ((clients_num == 0) || (clients_num == 1)) {
  256. return options.getMacPrefix();
  257. }
  258. // Get the base MAC address. We are going to randomize part of it.
  259. std::vector<uint8_t> mac_addr(options.getMacPrefix());
  260. if (mac_addr.size() != HW_ETHER_LEN) {
  261. isc_throw(BadValue, "invalid MAC address prefix specified");
  262. }
  263. uint32_t r = random();
  264. // The random number must be in the range 0..clients_num. This
  265. // will guarantee that every client has exactly one random MAC
  266. // address assigned.
  267. r %= clients_num;
  268. // Randomize MAC address octets.
  269. for (std::vector<uint8_t>::iterator it = mac_addr.end() - 1;
  270. it >= mac_addr.begin();
  271. --it) {
  272. // Add the random value to the current octet.
  273. (*it) += r;
  274. if (r < 256) {
  275. // If we are here it means that there is no sense
  276. // to randomize the remaining octets of MAC address
  277. // because the following bytes of random value
  278. // are zero and it will have no effect.
  279. break;
  280. }
  281. // Randomize the next octet with the following
  282. // byte of random value.
  283. r >>= 8;
  284. }
  285. return mac_addr;
  286. }
  287. std::vector<uint8_t>
  288. TestControl::generateDuid() const {
  289. CommandOptions& options = CommandOptions::instance();
  290. uint32_t clients_num = options.getClientsNum();
  291. if ((clients_num == 0) || (clients_num == 1)) {
  292. return options.getDuidPrefix();
  293. }
  294. // Get the base DUID. We are going to randomize part of it.
  295. std::vector<uint8_t> duid(options.getDuidPrefix());
  296. std::vector<uint8_t> mac_addr(generateMacAddress());
  297. duid.resize(duid.size() - mac_addr.size());
  298. for (int i = 0; i < mac_addr.size(); ++i) {
  299. duid.push_back(mac_addr[i]);
  300. }
  301. return duid;
  302. }
  303. uint64_t
  304. TestControl::getNextExchangesNum() const {
  305. CommandOptions& options = CommandOptions::instance();
  306. // Reset number of exchanges.
  307. uint64_t due_exchanges = 0;
  308. // Get current time.
  309. ptime now(microsec_clock::universal_time());
  310. // The due time indicates when we should start sending next chunk
  311. // of packets. If it is already due time, we should calculate
  312. // how many packets to send.
  313. if (now >= send_due_) {
  314. // If rate is specified from the command line we have to
  315. // synchornize with it.
  316. if (options.getRate() != 0) {
  317. time_period period(send_due_, now);
  318. time_duration duration = period.length();
  319. // due_factor indicates the number of seconds that
  320. // sending next chunk of packets will take.
  321. double due_factor = duration.fractional_seconds() /
  322. time_duration::ticks_per_second();
  323. due_factor += duration.total_seconds();
  324. // Multiplying due_factor by expected rate gives the number
  325. // of exchanges to be initiated.
  326. due_exchanges = static_cast<uint64_t>(due_factor * options.getRate());
  327. // We want to make sure that at least one packet goes out.
  328. due_exchanges += 1;
  329. // We should not exceed aggressivity as it could have been
  330. // restricted from command line.
  331. if (due_exchanges > options.getAggressivity()) {
  332. due_exchanges = options.getAggressivity();
  333. }
  334. } else {
  335. // Rate is not specified so we rely on aggressivity
  336. // which is the number of packets to be sent in
  337. // one chunk.
  338. due_exchanges = options.getAggressivity();
  339. }
  340. return (due_exchanges);
  341. }
  342. return (0);
  343. }
  344. uint64_t
  345. TestControl::getRcvdPacketsNum(const ExchangeType xchg_type) const {
  346. uint8_t ip_version = CommandOptions::instance().getIpVersion();
  347. if (ip_version == 4) {
  348. return(stats_mgr4_->getRcvdPacketsNum(xchg_type));
  349. }
  350. return(stats_mgr6_->
  351. getRcvdPacketsNum(static_cast<StatsMgr6::ExchangeType>(xchg_type)));
  352. }
  353. uint64_t
  354. TestControl::getSentPacketsNum(const ExchangeType xchg_type) const {
  355. uint8_t ip_version = CommandOptions::instance().getIpVersion();
  356. if (ip_version == 4) {
  357. return(stats_mgr4_->getSentPacketsNum(xchg_type));
  358. }
  359. return(stats_mgr6_->
  360. getSentPacketsNum(static_cast<StatsMgr6::ExchangeType>(xchg_type)));
  361. }
  362. void
  363. TestControl::initPacketTemplates() {
  364. CommandOptions& options = CommandOptions::instance();
  365. std::vector<std::string> template_files = options.getTemplateFiles();
  366. for (std::vector<std::string>::const_iterator it = template_files.begin();
  367. it != template_files.end();
  368. ++it) {
  369. std::cout << "Open file " << *it << std::endl;
  370. }
  371. }
  372. void
  373. TestControl::initializeStatsMgr() {
  374. CommandOptions& options = CommandOptions::instance();
  375. if (options.getIpVersion() == 4) {
  376. stats_mgr4_.reset();
  377. stats_mgr4_ = StatsMgr4Ptr(new StatsMgr4());
  378. stats_mgr4_->addExchangeStats(StatsMgr4::XCHG_DO);
  379. if (options.getExchangeMode() == CommandOptions::DORA_SARR) {
  380. stats_mgr4_->addExchangeStats(StatsMgr4::XCHG_RA);
  381. }
  382. } else if (options.getIpVersion() == 6) {
  383. stats_mgr6_.reset();
  384. stats_mgr6_ = StatsMgr6Ptr(new StatsMgr6());
  385. stats_mgr6_->addExchangeStats(StatsMgr6::XCHG_SA);
  386. if (options.getExchangeMode() == CommandOptions::DORA_SARR) {
  387. stats_mgr6_->addExchangeStats(StatsMgr6::XCHG_RR);
  388. }
  389. }
  390. }
  391. int
  392. TestControl::openSocket() const {
  393. CommandOptions& options = CommandOptions::instance();
  394. std::string localname = options.getLocalName();
  395. std::string servername = options.getServerName();
  396. uint16_t port = options.getLocalPort();
  397. uint8_t family = AF_INET;
  398. int sock = 0;
  399. IOAddress remoteaddr(servername);
  400. if (port == 0) {
  401. if (options.getIpVersion() == 6) {
  402. port = DHCP6_CLIENT_PORT;
  403. } else if (options.getIpVersion() == 4) {
  404. port = 67; // TODO: find out why port 68 is wrong here.
  405. }
  406. }
  407. if (options.getIpVersion() == 6) {
  408. family = AF_INET6;
  409. }
  410. // Local name is specified along with '-l' option.
  411. // It may point to interface name or local address.
  412. if (!localname.empty()) {
  413. // CommandOptions should be already aware wether local name
  414. // is interface name or address because it uses IfaceMgr to
  415. // scan interfaces and get's their names.
  416. if (options.isInterface()) {
  417. sock = IfaceMgr::instance().openSocketFromIface(localname,
  418. port,
  419. family);
  420. } else {
  421. IOAddress localaddr(localname);
  422. sock = IfaceMgr::instance().openSocketFromAddress(localaddr,
  423. port);
  424. }
  425. } else if (!servername.empty()) {
  426. // If only server name is given we will need to try to resolve
  427. // the local address to bind socket to based on remote address.
  428. sock = IfaceMgr::instance().openSocketFromRemoteAddress(remoteaddr,
  429. port);
  430. }
  431. if (sock <= 0) {
  432. isc_throw(BadValue, "unable to open socket to communicate with "
  433. "DHCP server");
  434. }
  435. // IfaceMgr does not set broadcast option on the socket. We rely
  436. // on CommandOptions object to find out if socket has to have
  437. // broadcast enabled.
  438. if ((options.getIpVersion() == 4) && options.isBroadcast()) {
  439. int broadcast_enable = 1;
  440. int ret = setsockopt(sock, SOL_SOCKET, SO_BROADCAST,
  441. &broadcast_enable, sizeof(broadcast_enable));
  442. if (ret < 0) {
  443. isc_throw(InvalidOperation,
  444. "unable to set broadcast option on the socket");
  445. }
  446. } else if (options.getIpVersion() == 6) {
  447. // If remote address is multicast we need to enable it on
  448. // the socket that has been created.
  449. asio::ip::address_v6 remote_v6 = remoteaddr.getAddress().to_v6();
  450. if (remote_v6.is_multicast()) {
  451. int hops = 1;
  452. int ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
  453. &hops, sizeof(hops));
  454. // If user specified interface name with '-l' the
  455. // IPV6_MULTICAST_IF has to be set.
  456. if ((ret >= 0) && options.isInterface()) {
  457. IfaceMgr::Iface* iface =
  458. IfaceMgr::instance().getIface(options.getLocalName());
  459. if (iface == NULL) {
  460. isc_throw(Unexpected, "unknown interface "
  461. << options.getLocalName());
  462. }
  463. int idx = iface->getIndex();
  464. ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_IF,
  465. &idx, sizeof(idx));
  466. }
  467. if (ret < 0) {
  468. isc_throw(InvalidOperation,
  469. "unable to enable multicast on socket " << sock
  470. << ". errno = " << errno);
  471. }
  472. }
  473. }
  474. return(sock);
  475. }
  476. void
  477. TestControl::printRate() const {
  478. double rate = 0;
  479. CommandOptions& options = CommandOptions::instance();
  480. if (options.getIpVersion() == 4) {
  481. double duration =
  482. stats_mgr4_->getTestPeriod().length().total_nanoseconds() / 1e9;
  483. rate = stats_mgr4_->getRcvdPacketsNum(StatsMgr4::XCHG_DO) / duration;
  484. } else if (options.getIpVersion() == 6) {
  485. double duration =
  486. stats_mgr6_->getTestPeriod().length().total_nanoseconds() / 1e9;
  487. rate = stats_mgr6_->getRcvdPacketsNum(StatsMgr6::XCHG_SA) / duration;
  488. }
  489. std::cout << "***Rate statistics***" << std::endl;
  490. if (options.getRate() > 0) {
  491. std::cout << "Rate: " << rate << ", expected rate: "
  492. << options.getRate() << std::endl << std::endl;
  493. } else {
  494. std::cout << "Rate: " << rate << std::endl << std::endl;
  495. }
  496. }
  497. void
  498. TestControl::printIntermediateStats() {
  499. CommandOptions& options = CommandOptions::instance();
  500. int delay = options.getReportDelay();
  501. ptime now = microsec_clock::universal_time();
  502. time_period time_since_report(last_report_, now);
  503. if (time_since_report.length().total_seconds() >= delay) {
  504. if (options.getIpVersion() == 4) {
  505. stats_mgr4_->printIntermediateStats();
  506. } else if (options.getIpVersion() == 6) {
  507. stats_mgr6_->printIntermediateStats();
  508. }
  509. last_report_ = now;
  510. }
  511. }
  512. void
  513. TestControl::printStats() const {
  514. printRate();
  515. CommandOptions& options = CommandOptions::instance();
  516. if (options.getIpVersion() == 4) {
  517. if (!stats_mgr4_) {
  518. isc_throw(InvalidOperation, "Statistics Manager for DHCPv4 "
  519. "hasn't been initialized");
  520. }
  521. stats_mgr4_->printStats();
  522. } else if (options.getIpVersion() == 6) {
  523. if (!stats_mgr6_) {
  524. isc_throw(InvalidOperation, "Statistics Manager for DHCPv6 "
  525. "hasn't been initialized");
  526. }
  527. stats_mgr6_->printStats();
  528. }
  529. }
  530. void
  531. TestControl::receivePacket4(const TestControlSocket& socket,
  532. const Pkt4Ptr& pkt4) {
  533. if (pkt4->getType() == DHCPOFFER) {
  534. Pkt4Ptr discover_pkt4(stats_mgr4_->passRcvdPacket(StatsMgr4::XCHG_DO,
  535. pkt4));
  536. CommandOptions::ExchangeMode xchg_mode =
  537. CommandOptions::instance().getExchangeMode();
  538. if ((xchg_mode == CommandOptions::DORA_SARR) && discover_pkt4) {
  539. sendRequest4(socket, pkt4);
  540. }
  541. } else if (pkt4->getType() == DHCPACK) {
  542. stats_mgr4_->passRcvdPacket(StatsMgr4::XCHG_RA, pkt4);
  543. }
  544. }
  545. void
  546. TestControl::receivePacket6(const TestControlSocket& socket,
  547. const Pkt6Ptr& pkt6) {
  548. uint8_t packet_type = pkt6->getType();
  549. if (packet_type == DHCPV6_ADVERTISE) {
  550. Pkt6Ptr solicit_pkt6(stats_mgr6_->passRcvdPacket(StatsMgr6::XCHG_SA,
  551. pkt6));
  552. CommandOptions::ExchangeMode xchg_mode =
  553. CommandOptions::instance().getExchangeMode();
  554. if ((xchg_mode == CommandOptions::DORA_SARR) && solicit_pkt6) {
  555. sendRequest6(socket, solicit_pkt6, pkt6);
  556. }
  557. } else if (packet_type == DHCPV6_REPLY) {
  558. stats_mgr6_->passRcvdPacket(StatsMgr6::XCHG_RR, pkt6);
  559. }
  560. }
  561. void
  562. TestControl::receivePackets(const TestControlSocket& socket) {
  563. int timeout = 0;
  564. bool receiving = true;
  565. while (receiving) {
  566. if (CommandOptions::instance().getIpVersion() == 4) {
  567. Pkt4Ptr pkt4 = IfaceMgr::instance().receive4(timeout);
  568. if (!pkt4) {
  569. receiving = false;
  570. } else {
  571. pkt4->unpack();
  572. receivePacket4(socket, pkt4);
  573. }
  574. } else if (CommandOptions::instance().getIpVersion() == 6) {
  575. Pkt6Ptr pkt6 = IfaceMgr::instance().receive6(timeout);
  576. if (!pkt6) {
  577. receiving = false;
  578. } else {
  579. if (pkt6->unpack()) {
  580. receivePacket6(socket, pkt6);
  581. }
  582. }
  583. }
  584. }
  585. }
  586. void
  587. TestControl::registerOptionFactories4() const {
  588. static bool factories_registered = false;
  589. if (!factories_registered) {
  590. // DHCP_MESSAGE_TYPE option factory.
  591. LibDHCP::OptionFactoryRegister(Option::V4,
  592. DHO_DHCP_MESSAGE_TYPE,
  593. &TestControl::factoryGeneric);
  594. LibDHCP::OptionFactoryRegister(Option::V4,
  595. DHO_DHCP_SERVER_IDENTIFIER,
  596. &TestControl::factoryGeneric);
  597. // DHCP_PARAMETER_REQUEST_LIST option factory.
  598. LibDHCP::OptionFactoryRegister(Option::V4,
  599. DHO_DHCP_PARAMETER_REQUEST_LIST,
  600. &TestControl::factoryRequestList4);
  601. }
  602. factories_registered = true;
  603. }
  604. void
  605. TestControl::registerOptionFactories6() const {
  606. static bool factories_registered = false;
  607. if (!factories_registered) {
  608. LibDHCP::OptionFactoryRegister(Option::V6,
  609. D6O_ELAPSED_TIME,
  610. &TestControl::factoryElapsedTime6);
  611. LibDHCP::OptionFactoryRegister(Option::V6,
  612. D6O_RAPID_COMMIT,
  613. &TestControl::factoryRapidCommit6);
  614. LibDHCP::OptionFactoryRegister(Option::V6,
  615. D6O_ORO,
  616. &TestControl::factoryOptionRequestOption6);
  617. LibDHCP::OptionFactoryRegister(Option::V6,
  618. D6O_CLIENTID,
  619. &TestControl::factoryGeneric);
  620. LibDHCP::OptionFactoryRegister(Option::V6,
  621. D6O_SERVERID,
  622. &TestControl::factoryGeneric);
  623. LibDHCP::OptionFactoryRegister(Option::V6,
  624. D6O_IA_NA,
  625. &TestControl::factoryIana6);
  626. }
  627. factories_registered = true;
  628. }
  629. void
  630. TestControl::registerOptionFactories() const {
  631. CommandOptions& options = CommandOptions::instance();
  632. switch(options.getIpVersion()) {
  633. case 4:
  634. registerOptionFactories4();
  635. break;
  636. case 6:
  637. registerOptionFactories6();
  638. break;
  639. default:
  640. isc_throw(InvalidOperation, "command line options have to be parsed "
  641. "before DHCP option factories can be registered");
  642. }
  643. }
  644. void
  645. TestControl::reset() {
  646. send_due_ = microsec_clock::universal_time();
  647. last_sent_ = send_due_;
  648. last_report_ = send_due_;
  649. transid_gen_.reset();
  650. transid_gen_ = TransidGeneratorPtr(new TransidGenerator());
  651. first_packet_serverid_.clear();
  652. }
  653. void
  654. TestControl::run() {
  655. sent_packets_0_ = 0;
  656. sent_packets_1_ = 0;
  657. // Reset singleton state before test starts.
  658. reset();
  659. CommandOptions& options = CommandOptions::instance();
  660. // Ip version is not set ONLY in case the command options
  661. // were not parsed. This surely means that parse() function
  662. // was not called prior to starting the test. This is fatal
  663. // error.
  664. if (options.getIpVersion() == 0) {
  665. isc_throw(InvalidOperation,
  666. "command options must be parsed before running a test");
  667. }
  668. registerOptionFactories();
  669. TestControlSocket socket(openSocket());
  670. // Initialize packet templates.
  671. initPacketTemplates();
  672. // Initialize randomization seed.
  673. if (options.isSeeded()) {
  674. srandom(options.getSeed());
  675. }
  676. // Preload server with number of packets.
  677. const bool do_preload = true;
  678. for (int i = 0; i < options.getPreload(); ++i) {
  679. if (options.getIpVersion() == 4) {
  680. sendDiscover4(socket, do_preload);
  681. } else if (options.getIpVersion() == 6) {
  682. sendSolicit6(socket, do_preload);
  683. }
  684. }
  685. initializeStatsMgr();
  686. uint64_t packets_sent = 0;
  687. for (;;) {
  688. updateSendDue();
  689. if (checkExitConditions()) {
  690. break;
  691. }
  692. uint64_t packets_due = getNextExchangesNum();
  693. receivePackets(socket);
  694. for (uint64_t i = packets_due; i > 0; --i) {
  695. if (options.getIpVersion() == 4) {
  696. sendDiscover4(socket);
  697. } else {
  698. sendSolicit6(socket);
  699. }
  700. ++packets_sent;
  701. }
  702. if (options.getReportDelay() > 0) {
  703. printIntermediateStats();
  704. }
  705. }
  706. printStats();
  707. }
  708. void
  709. TestControl::sendDiscover4(const TestControlSocket& socket,
  710. const bool preload /*= false*/) {
  711. ++sent_packets_0_;
  712. last_sent_ = microsec_clock::universal_time();
  713. // Generate the MAC address to be passed in the packet.
  714. std::vector<uint8_t> mac_address = generateMacAddress();
  715. // Generate trasnaction id to be set for the new exchange.
  716. const uint32_t transid = generateTransid();
  717. Pkt4Ptr pkt4(new Pkt4(DHCPDISCOVER, transid));
  718. if (!pkt4) {
  719. isc_throw(Unexpected, "failed to create DISCOVER packet");
  720. }
  721. // Set options: DHCP_MESSAGE_TYPE and DHCP_PARAMETER_REQUEST_LIST
  722. OptionBuffer buf_msg_type;
  723. buf_msg_type.push_back(DHCPDISCOVER);
  724. pkt4->addOption(Option::factory(Option::V4, DHO_DHCP_MESSAGE_TYPE,
  725. buf_msg_type));
  726. pkt4->addOption(Option::factory(Option::V4,
  727. DHO_DHCP_PARAMETER_REQUEST_LIST));
  728. // Set client's and server's ports as well as server's address,
  729. // and local (relay) address.
  730. setDefaults4(socket, pkt4);
  731. pkt4->pack();
  732. IfaceMgr::instance().send(pkt4);
  733. if (!preload) {
  734. if (!stats_mgr4_) {
  735. isc_throw(InvalidOperation, "Statistics Manager for DHCPv4 "
  736. "hasn't been initialized");
  737. }
  738. stats_mgr4_->passSentPacket(StatsMgr4::XCHG_DO, pkt4);
  739. }
  740. }
  741. void
  742. TestControl::sendRequest4(const TestControlSocket& socket,
  743. const dhcp::Pkt4Ptr& offer_pkt4) {
  744. const uint32_t transid = generateTransid();
  745. Pkt4Ptr pkt4(new Pkt4(DHCPREQUEST, transid));
  746. OptionBuffer buf_msg_type;
  747. buf_msg_type.push_back(DHCPREQUEST);
  748. OptionPtr opt_msg_type = Option::factory(Option::V4, DHO_DHCP_MESSAGE_TYPE,
  749. buf_msg_type);
  750. pkt4->addOption(opt_msg_type);
  751. if (first_packet_serverid_.size() > 0) {
  752. pkt4->addOption(Option::factory(Option::V4, DHO_DHCP_SERVER_IDENTIFIER,
  753. first_packet_serverid_));
  754. } else {
  755. OptionPtr opt_serverid =
  756. offer_pkt4->getOption(DHO_DHCP_SERVER_IDENTIFIER);
  757. if (!opt_serverid) {
  758. isc_throw(BadValue, "there is no SERVER_IDENTIFIER option "
  759. << "in OFFER message");
  760. }
  761. if (CommandOptions::instance().isUseFirst() &&
  762. stats_mgr4_->getRcvdPacketsNum(StatsMgr4::XCHG_DO) == 1) {
  763. first_packet_serverid_ = opt_serverid->getData();
  764. }
  765. pkt4->addOption(opt_serverid);
  766. }
  767. /// Set client address.
  768. asiolink::IOAddress yiaddr = offer_pkt4->getYiaddr();
  769. if (!yiaddr.getAddress().is_v4()) {
  770. isc_throw(BadValue, "the YIADDR returned in OFFER packet is not "
  771. " IPv4 address");
  772. }
  773. OptionPtr opt_requested_address =
  774. OptionPtr(new Option(Option::V4, DHO_DHCP_REQUESTED_ADDRESS,
  775. OptionBuffer()));
  776. opt_requested_address->setUint32(yiaddr);
  777. pkt4->addOption(opt_requested_address);
  778. OptionPtr opt_parameter_list =
  779. Option::factory(Option::V4, DHO_DHCP_PARAMETER_REQUEST_LIST);
  780. pkt4->addOption(opt_parameter_list);
  781. // Set client's and server's ports as well as server's address,
  782. // and local (relay) address.
  783. setDefaults4(socket, pkt4);
  784. pkt4->pack();
  785. IfaceMgr::instance().send(pkt4);
  786. if (!stats_mgr4_) {
  787. isc_throw(InvalidOperation, "Statistics Manager for DHCPv4 "
  788. "hasn't been initialized");
  789. }
  790. stats_mgr4_->passSentPacket(StatsMgr4::XCHG_RA, pkt4);
  791. }
  792. void
  793. TestControl::sendRequest6(const TestControlSocket& socket,
  794. const Pkt6Ptr& solicit_pkt6,
  795. const Pkt6Ptr& advertise_pkt6) {
  796. const uint32_t transid = generateTransid();
  797. Pkt6Ptr pkt6(new Pkt6(DHCPV6_REQUEST, transid));
  798. // Calculate elapsed time
  799. ptime solicit_time = solicit_pkt6->getTimestamp();
  800. ptime advertise_time = advertise_pkt6->getTimestamp();
  801. if (solicit_time.is_not_a_date_time()) {
  802. isc_throw(Unexpected, "timestamp was not set for SOLICIT packet");
  803. }
  804. if (advertise_time.is_not_a_date_time()) {
  805. isc_throw(Unexpected, "timestamp was not set for ADVERTISE packet");
  806. }
  807. time_period period(solicit_time, advertise_time);
  808. if (period.is_null()) {
  809. pkt6->addOption(Option::factory(Option::V6, D6O_ELAPSED_TIME));
  810. } else {
  811. OptionBuffer buf();
  812. const uint32_t elapsed_time = period.length().total_seconds();
  813. OptionPtr opt_elapsed_time =
  814. Option::factory(Option::V6, D6O_ELAPSED_TIME);
  815. opt_elapsed_time->setUint16(static_cast<uint16_t>(elapsed_time));
  816. pkt6->addOption(opt_elapsed_time);
  817. }
  818. OptionPtr opt_clientid = advertise_pkt6->getOption(D6O_CLIENTID);
  819. if (!opt_clientid) {
  820. isc_throw(Unexpected, "client id not found in received packet");
  821. }
  822. pkt6->addOption(opt_clientid);
  823. if (first_packet_serverid_.size() > 0) {
  824. pkt6->addOption(Option::factory(Option::V6, D6O_SERVERID,
  825. first_packet_serverid_));
  826. } else {
  827. OptionPtr opt_serverid = advertise_pkt6->getOption(D6O_SERVERID);
  828. if (!opt_serverid) {
  829. isc_throw(Unexpected, "server id not found in received packet");
  830. }
  831. if (CommandOptions::instance().isUseFirst() &&
  832. stats_mgr6_->getRcvdPacketsNum(StatsMgr6::XCHG_SA) == 1) {
  833. first_packet_serverid_ = opt_serverid->getData();
  834. }
  835. pkt6->addOption(opt_serverid);
  836. }
  837. OptionPtr opt_ia_na = advertise_pkt6->getOption(D6O_IA_NA);
  838. if (!opt_ia_na) {
  839. isc_throw(Unexpected, "DHCPv6 IA_NA option not found in received "
  840. "packet");
  841. }
  842. pkt6->addOption(opt_ia_na);
  843. setDefaults6(socket, pkt6);
  844. pkt6->pack();
  845. IfaceMgr::instance().send(pkt6);
  846. if (!stats_mgr6_) {
  847. isc_throw(InvalidOperation, "Statistics Manager for DHCPv6 "
  848. "hasn't been initialized");
  849. }
  850. stats_mgr6_->passSentPacket(StatsMgr6::XCHG_RR, pkt6);
  851. }
  852. void
  853. TestControl::sendSolicit6(const TestControlSocket& socket,
  854. const bool preload /*= false*/) {
  855. ++sent_packets_0_;
  856. last_sent_ = microsec_clock::universal_time();
  857. // Generate the MAC address to be passed in the packet.
  858. std::vector<uint8_t> mac_address = generateMacAddress();
  859. // Generate DUID to be passed to the packet
  860. std::vector<uint8_t> duid = generateDuid();
  861. // Generate trasnaction id to be set for the new exchange.
  862. const uint32_t transid = generateTransid();
  863. Pkt6Ptr pkt6(new Pkt6(DHCPV6_SOLICIT, transid));
  864. if (!pkt6) {
  865. isc_throw(Unexpected, "failed to create SOLICIT packet");
  866. }
  867. pkt6->addOption(Option::factory(Option::V6, D6O_ELAPSED_TIME));
  868. if (CommandOptions::instance().isRapidCommit()) {
  869. pkt6->addOption(Option::factory(Option::V6, D6O_RAPID_COMMIT));
  870. }
  871. pkt6->addOption(Option::factory(Option::V6, D6O_CLIENTID, duid));
  872. pkt6->addOption(Option::factory(Option::V6, D6O_ORO));
  873. pkt6->addOption(Option::factory(Option::V6, D6O_IA_NA));
  874. setDefaults6(socket, pkt6);
  875. pkt6->pack();
  876. IfaceMgr::instance().send(pkt6);
  877. if (!preload) {
  878. if (!stats_mgr6_) {
  879. isc_throw(InvalidOperation, "Statistics Manager for DHCPv6 "
  880. "hasn't been initialized");
  881. }
  882. stats_mgr6_->passSentPacket(StatsMgr6::XCHG_SA, pkt6);
  883. }
  884. }
  885. void
  886. TestControl::setDefaults4(const TestControlSocket& socket,
  887. const Pkt4Ptr& pkt) {
  888. CommandOptions& options = CommandOptions::instance();
  889. // Interface name.
  890. pkt->setIface(socket.getIface());
  891. // Interface index.
  892. pkt->setIndex(socket.getIfIndex());
  893. // Local client's port (68)
  894. pkt->setLocalPort(DHCP4_CLIENT_PORT);
  895. // Server's port (67)
  896. pkt->setRemotePort(DHCP4_SERVER_PORT);
  897. // The remote server's name or IP.
  898. pkt->setRemoteAddr(IOAddress(options.getServerName()));
  899. // Set local addresss.
  900. pkt->setLocalAddr(IOAddress(socket.getAddress()));
  901. // Set relay (GIADDR) address to local address.
  902. pkt->setGiaddr(IOAddress(socket.getAddress()));
  903. std::vector<uint8_t> mac = generateMacAddress();
  904. // Set hardware address
  905. pkt->setHWAddr(HTYPE_ETHER, mac.size(), mac);
  906. // Pretend that we have one relay (which is us).
  907. pkt->setHops(1);
  908. }
  909. void
  910. TestControl::setDefaults6(const TestControlSocket& socket,
  911. const Pkt6Ptr& pkt) {
  912. CommandOptions& options = CommandOptions::instance();
  913. // Interface name.
  914. pkt->setIface(socket.getIface());
  915. // Interface index.
  916. pkt->setIndex(socket.getIfIndex());
  917. // Local client's port (547)
  918. pkt->setLocalPort(DHCP6_CLIENT_PORT);
  919. // Server's port (548)
  920. pkt->setRemotePort(DHCP6_SERVER_PORT);
  921. // Set local address.
  922. pkt->setLocalAddr(socket.getAddress());
  923. // The remote server's name or IP.
  924. pkt->setRemoteAddr(IOAddress(options.getServerName()));
  925. }
  926. void
  927. TestControl::updateSendDue() {
  928. // If default constructor was called, this should not happen but
  929. // if somebody has changed default constructor it is better to
  930. // keep this check.
  931. if (last_sent_.is_not_a_date_time()) {
  932. isc_throw(Unexpected, "time of last sent packet not initialized");
  933. }
  934. // Get the expected exchange rate.
  935. CommandOptions& options = CommandOptions::instance();
  936. int rate = options.getRate();
  937. // If rate was not specified we will wait just one clock tick to
  938. // send next packet. This simulates best effort conditions.
  939. long duration = 1;
  940. if (rate != 0) {
  941. // We use number of ticks instead of nanoseconds because
  942. // nanosecond resolution may not be available on some
  943. // machines. Number of ticks guarantees the highest possible
  944. // timer resolution.
  945. duration = time_duration::ticks_per_second() / rate;
  946. }
  947. // Calculate due time to initate next chunk of exchanges.
  948. send_due_ = last_sent_ + time_duration(0, 0, 0, duration);
  949. }
  950. } // namespace perfdhcp
  951. } // namespace isc