test_control.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. addr_ = s->addr_;
  58. return;
  59. }
  60. }
  61. }
  62. isc_throw(BadValue, "interface for for specified socket "
  63. "descriptor not found");
  64. }
  65. TestControl&
  66. TestControl::instance() {
  67. static TestControl test_control;
  68. return (test_control);
  69. }
  70. TestControl::TestControl() :
  71. send_due_(microsec_clock::universal_time()),
  72. last_sent_(send_due_) {
  73. }
  74. bool
  75. TestControl::checkExitConditions() const {
  76. CommandOptions& options = CommandOptions::instance();
  77. if ((options.getNumRequests().size() > 0) &&
  78. (sent_packets_0_ >= options.getNumRequests()[0])) {
  79. return(true);
  80. } else if ((options.getNumRequests().size() == 2) &&
  81. (sent_packets_1_ >= options.getNumRequests()[1])) {
  82. return(true);
  83. }
  84. return(false);
  85. }
  86. OptionPtr
  87. TestControl::factoryGeneric4(Option::Universe u,
  88. uint16_t type,
  89. const OptionBuffer& buf) {
  90. OptionPtr opt(new Option(u, type, buf));
  91. return opt;
  92. }
  93. OptionPtr
  94. TestControl::factoryRequestList4(Option::Universe u,
  95. uint16_t type,
  96. const OptionBuffer& buf) {
  97. const uint8_t buf_array[] = {
  98. DHO_SUBNET_MASK,
  99. DHO_BROADCAST_ADDRESS,
  100. DHO_TIME_OFFSET,
  101. DHO_ROUTERS,
  102. DHO_DOMAIN_NAME,
  103. DHO_DOMAIN_NAME_SERVERS,
  104. DHO_HOST_NAME
  105. };
  106. OptionBuffer buf_with_options(buf_array, buf_array + sizeof(buf_array));
  107. OptionPtr opt(new Option(u, type, buf));
  108. opt->setData(buf_with_options.begin(), buf_with_options.end());
  109. return opt;
  110. }
  111. std::vector<uint8_t>
  112. TestControl::generateMacAddress() const {
  113. CommandOptions& options = CommandOptions::instance();
  114. uint32_t clients_num = options.getClientsNum();
  115. if ((clients_num == 0) || (clients_num == 1)) {
  116. return options.getMacPrefix();
  117. }
  118. // Get the base MAC address. We are going to randomize part of it.
  119. std::vector<uint8_t> mac_addr(options.getMacPrefix());
  120. if (mac_addr.size() != HW_ETHER_LEN) {
  121. isc_throw(BadValue, "invalid MAC address prefix specified");
  122. }
  123. uint32_t r = random();
  124. // The random number must be in the range 0..clients_num. This
  125. // will guarantee that every client has exactly one random MAC
  126. // address assigned.
  127. r %= clients_num;
  128. // Randomize MAC address octets.
  129. for (std::vector<uint8_t>::iterator it = mac_addr.end() - 1;
  130. it >= mac_addr.begin();
  131. --it) {
  132. // Add the random value to the current octet.
  133. (*it) += r;
  134. if (r < 256) {
  135. // If we are here it means that there is no sense
  136. // to randomize the remaining octets of MAC address
  137. // because the following bytes of random value
  138. // are zero and it will have no effect.
  139. break;
  140. }
  141. // Randomize the next octet with the following
  142. // byte of random value.
  143. r >>= 8;
  144. }
  145. return mac_addr;
  146. }
  147. uint64_t
  148. TestControl::getNextExchangesNum() const {
  149. CommandOptions& options = CommandOptions::instance();
  150. // Reset number of exchanges.
  151. uint64_t due_exchanges = 0;
  152. // Get current time.
  153. ptime now(microsec_clock::universal_time());
  154. // The due time indicates when we should start sending next chunk
  155. // of packets. If it is already due time, we should calculate
  156. // how many packets to send.
  157. if (now >= send_due_) {
  158. // If rate is specified from the command line we have to
  159. // synchornize with it.
  160. if (options.getRate() != 0) {
  161. time_period period(send_due_, now);
  162. // Null condition should not occur because we
  163. // have checked it in the first if statement but
  164. // let's keep this check just in case.
  165. if (period.is_null()) {
  166. return (0);
  167. }
  168. time_duration duration = period.length();
  169. // due_factor indicates the number of seconds that
  170. // sending next chunk of packets will take.
  171. double due_factor = duration.fractional_seconds() /
  172. time_duration::ticks_per_second();
  173. due_factor += duration.total_seconds();
  174. // Multiplying due_factor by expected rate gives the number
  175. // of exchanges to be initiated.
  176. due_exchanges = static_cast<uint64_t>(due_factor * options.getRate());
  177. // We want to make sure that at least one packet goes out.
  178. due_exchanges += 1;
  179. // We should not exceed aggressivity as it could have been
  180. // restricted from command line.
  181. if (due_exchanges > options.getAggressivity()) {
  182. due_exchanges = options.getAggressivity();
  183. }
  184. } else {
  185. // Rate is not specified so we rely on aggressivity
  186. // which is the number of packets to be sent in
  187. // one chunk.
  188. due_exchanges = options.getAggressivity();
  189. }
  190. return (due_exchanges);
  191. }
  192. return (0);
  193. }
  194. int
  195. TestControl::openSocket() const {
  196. CommandOptions& options = CommandOptions::instance();
  197. std::string localname = options.getLocalName();
  198. std::string servername = options.getServerName();
  199. uint8_t family = AF_INET;
  200. uint16_t port = 67;
  201. int sock = 0;
  202. if (options.getIpVersion() == 6) {
  203. family = AF_INET6;
  204. port = 547;
  205. }
  206. // Local name is specified along with '-l' option.
  207. // It may point to interface name or local address.
  208. if (!localname.empty()) {
  209. // CommandOptions should be already aware wether local name
  210. // is interface name or address because it uses IfaceMgr to
  211. // scan interfaces and get's their names.
  212. if (options.isInterface()) {
  213. sock = IfaceMgr::instance().openSocketFromIface(localname,
  214. port,
  215. family);
  216. } else {
  217. IOAddress localaddr(localname);
  218. sock = IfaceMgr::instance().openSocketFromAddress(localaddr,
  219. port);
  220. }
  221. } else if (!servername.empty()) {
  222. // If only server name is given we will need to try to resolve
  223. // the local address to bind socket to based on remote address.
  224. IOAddress remoteaddr(servername);
  225. sock = IfaceMgr::instance().openSocketFromRemoteAddress(remoteaddr,
  226. port);
  227. }
  228. if (sock <= 0) {
  229. isc_throw(BadValue, "unable to open socket to communicate with "
  230. "DHCP server");
  231. }
  232. // IfaceMgr does not set broadcast option on the socket. We rely
  233. // on CommandOptions object to find out if socket has to have
  234. // broadcast enabled.
  235. if ((options.getIpVersion() == 4) && options.isBroadcast()) {
  236. int broadcast_enable = 1;
  237. int ret = setsockopt(sock, SOL_SOCKET, SO_BROADCAST,
  238. &broadcast_enable, sizeof(broadcast_enable));
  239. if (ret < 0) {
  240. isc_throw(InvalidOperation,
  241. "unable to set broadcast option on the socket");
  242. }
  243. }
  244. return(sock);
  245. }
  246. void
  247. TestControl::receivePackets() {
  248. int timeout = 0;
  249. bool receiving = true;
  250. while (receiving) {
  251. Pkt4Ptr pkt4 = IfaceMgr::instance().receive4(timeout);
  252. if (!pkt4) {
  253. receiving = false;
  254. } else {
  255. // TODO: replace this with use of StatsMgr to increase
  256. // number of received packets. This can be done once
  257. // the 1958 ticket is reviewed and checked-in.
  258. std::cout << "Received packet" << std::endl;
  259. }
  260. }
  261. }
  262. void
  263. TestControl::registerOptionFactories4() const {
  264. static bool factories_registered = false;
  265. if (!factories_registered) {
  266. // DHCP_MESSAGE_TYPE option factory.
  267. LibDHCP::OptionFactoryRegister(Option::V4,
  268. DHO_DHCP_MESSAGE_TYPE,
  269. &TestControl::factoryGeneric4);
  270. // DHCP_PARAMETER_REQUEST_LIST option factory.
  271. LibDHCP::OptionFactoryRegister(Option::V4,
  272. DHO_DHCP_PARAMETER_REQUEST_LIST,
  273. &TestControl::factoryRequestList4);
  274. }
  275. factories_registered = true;
  276. }
  277. void
  278. TestControl::registerOptionFactories6() const {
  279. static bool factories_registered = false;
  280. if (!factories_registered) {
  281. // This is a placeholder for v6 factories.
  282. }
  283. factories_registered = true;
  284. }
  285. void
  286. TestControl::registerOptionFactories() const {
  287. CommandOptions& options = CommandOptions::instance();
  288. switch(options.getIpVersion()) {
  289. case 4:
  290. registerOptionFactories4();
  291. break;
  292. case 6:
  293. registerOptionFactories6();
  294. break;
  295. default:
  296. isc_throw(InvalidOperation, "command line options have to be parsed "
  297. "before DHCP option factories can be registered");
  298. }
  299. }
  300. void
  301. TestControl::run() {
  302. sent_packets_0_ = 0;
  303. sent_packets_1_ = 0;
  304. CommandOptions& options = CommandOptions::instance();
  305. // Ip version is not set ONLY in case the command options
  306. // were not parsed. This surely means that parse() function
  307. // was not called prior to starting the test. This is fatal
  308. // error.
  309. if (options.getIpVersion() == 0) {
  310. isc_throw(InvalidOperation,
  311. "command options must be parsed before running a test");
  312. }
  313. registerOptionFactories();
  314. TestControlSocket socket(openSocket());
  315. uint64_t packets_sent = 0;
  316. for (;;) {
  317. updateSendDue();
  318. if (checkExitConditions()) {
  319. break;
  320. }
  321. uint64_t packets_due = getNextExchangesNum();
  322. receivePackets();
  323. for (uint64_t i = packets_due; i > 0; --i) {
  324. sendDiscover4(socket);
  325. ++packets_sent;
  326. cout << "Packets sent " << packets_sent << endl;
  327. }
  328. }
  329. }
  330. void
  331. TestControl::sendDiscover4(const TestControlSocket& socket) {
  332. ++sent_packets_0_;
  333. last_sent_ = microsec_clock::universal_time();
  334. // Generate the MAC address to be passed in the packet.
  335. std::vector<uint8_t> mac_address = generateMacAddress();
  336. // Generate trasnaction id to be set for the new exchange.
  337. const uint32_t transid = static_cast<uint32_t>(random());
  338. boost::shared_ptr<Pkt4> pkt4(new Pkt4(DHCPDISCOVER, transid));
  339. if (!pkt4) {
  340. isc_throw(Unexpected, "failed to create DISCOVER packet");
  341. }
  342. // Set options: DHCP_MESSAGE_TYPE and DHCP_PARAMETER_REQUEST_LIST
  343. OptionBuffer buf_msg_type;
  344. buf_msg_type.push_back(DHCPDISCOVER);
  345. pkt4->addOption(Option::factory(Option::V4, DHO_DHCP_MESSAGE_TYPE,
  346. buf_msg_type));
  347. pkt4->addOption(Option::factory(Option::V4,
  348. DHO_DHCP_PARAMETER_REQUEST_LIST));
  349. // Set client's and server's ports as well as server's address,
  350. // and local (relay) address.
  351. setDefaults4(socket, pkt4);
  352. pkt4->pack();
  353. IfaceMgr::instance().send(pkt4);
  354. }
  355. void
  356. TestControl::setDefaults4(const TestControlSocket &socket,
  357. const boost::shared_ptr<Pkt4>& pkt) {
  358. CommandOptions& options = CommandOptions::instance();
  359. // Interface name.
  360. pkt->setIface(socket.getIface());
  361. // Local client's port (68)
  362. pkt->setLocalPort(DHCP4_CLIENT_PORT);
  363. // Server's port (67)
  364. pkt->setRemotePort(DHCP4_SERVER_PORT);
  365. // The remote server's name or IP.
  366. pkt->setRemoteAddr(IOAddress(options.getServerName()));
  367. // Set relay (GIADDR) address to local address.
  368. pkt->setGiaddr(IOAddress(socket.getAddress()));
  369. // Pretend that we have one relay (which is us).
  370. pkt->setHops(1);
  371. }
  372. void
  373. TestControl::updateSendDue() {
  374. // If default constructor was called, this should not happen but
  375. // if somebody has changed default constructor it is better to
  376. // keep this check.
  377. if (last_sent_.is_not_a_date_time()) {
  378. isc_throw(Unexpected, "time of last sent packet not initialized");
  379. }
  380. // Get the expected exchange rate.
  381. CommandOptions& options = CommandOptions::instance();
  382. int rate = options.getRate();
  383. // If rate was not specified we will wait just one clock tick to
  384. // send next packet. This simulates best effort conditions.
  385. long duration = 1;
  386. if (rate != 0) {
  387. // We use number of ticks instead of nanoseconds because
  388. // nanosecond resolution may not be available on some
  389. // machines. Number of ticks guarantees the highest possible
  390. // timer resolution.
  391. duration = time_duration::ticks_per_second() / rate;
  392. }
  393. // Calculate due time to initate next chunk of exchanges.
  394. send_due_ = last_sent_ + time_duration(0, 0, 0, duration);
  395. }
  396. } // namespace perfdhcp
  397. } // namespace isc