test_control.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. std::vector<uint8_t> mac_addr(options.getMacPrefix());
  119. if (mac_addr.size() != HW_ETHER_LEN) {
  120. isc_throw(BadValue, "invalid MAC address prefix specified");
  121. }
  122. uint32_t r = random();
  123. r %= clients_num;
  124. for (std::vector<uint8_t>::iterator it = mac_addr.end() - 1;
  125. it >= mac_addr.begin();
  126. --it) {
  127. (*it) += r;
  128. if (r < 256) {
  129. break;
  130. }
  131. r >>= 8;
  132. }
  133. return mac_addr;
  134. }
  135. uint64_t
  136. TestControl::getNextExchangesNum() const {
  137. CommandOptions& options = CommandOptions::instance();
  138. // Reset number of exchanges.
  139. uint64_t due_exchanges = 0;
  140. // Get current time.
  141. ptime now(microsec_clock::universal_time());
  142. // The due time indicates when we should start sending next chunk
  143. // of packets. If it is already due time, we should calculate
  144. // how many packets to send.
  145. if (now >= send_due_) {
  146. // If rate is specified from the command line we have to
  147. // synchornize with it.
  148. if (options.getRate() != 0) {
  149. time_period period(send_due_, now);
  150. // Null condition should not occur because we
  151. // have checked it in the first if statement but
  152. // let's keep this check just in case.
  153. if (period.is_null()) {
  154. return (0);
  155. }
  156. time_duration duration = period.length();
  157. // due_factor indicates the number of seconds that
  158. // sending next chunk of packets will take.
  159. double due_factor = duration.fractional_seconds() /
  160. time_duration::ticks_per_second();
  161. due_factor += duration.total_seconds();
  162. // Multiplying due_factor by expected rate gives the number
  163. // of exchanges to be initiated.
  164. due_exchanges = static_cast<uint64_t>(due_factor * options.getRate());
  165. // We want to make sure that at least one packet goes out.
  166. due_exchanges += 1;
  167. // We should not exceed aggressivity as it could have been
  168. // restricted from command line.
  169. if (due_exchanges > options.getAggressivity()) {
  170. due_exchanges = options.getAggressivity();
  171. }
  172. } else {
  173. // Rate is not specified so we rely on aggressivity
  174. // which is the number of packets to be sent in
  175. // one chunk.
  176. due_exchanges = options.getAggressivity();
  177. }
  178. return (due_exchanges);
  179. }
  180. return (0);
  181. }
  182. int
  183. TestControl::openSocket() const {
  184. CommandOptions& options = CommandOptions::instance();
  185. std::string localname = options.getLocalName();
  186. std::string servername = options.getServerName();
  187. uint8_t family = AF_INET;
  188. uint16_t port = 67;
  189. int sock = 0;
  190. if (options.getIpVersion() == 6) {
  191. family = AF_INET6;
  192. port = 547;
  193. }
  194. // Local name is specified along with '-l' option.
  195. // It may point to interface name or local address.
  196. if (!localname.empty()) {
  197. // CommandOptions should be already aware wether local name
  198. // is interface name or address because it uses IfaceMgr to
  199. // scan interfaces and get's their names.
  200. if (options.isInterface()) {
  201. sock = IfaceMgr::instance().openSocketFromIface(localname,
  202. port,
  203. family);
  204. } else {
  205. IOAddress localaddr(localname);
  206. sock = IfaceMgr::instance().openSocketFromAddress(localaddr,
  207. port);
  208. }
  209. } else if (!servername.empty()) {
  210. // If only server name is given we will need to try to resolve
  211. // the local address to bind socket to based on remote address.
  212. IOAddress remoteaddr(servername);
  213. sock = IfaceMgr::instance().openSocketFromRemoteAddress(remoteaddr,
  214. port);
  215. }
  216. if (sock <= 0) {
  217. isc_throw(BadValue, "unable to open socket to communicate with "
  218. "DHCP server");
  219. }
  220. // IfaceMgr does not set broadcast option on the socket. We rely
  221. // on CommandOptions object to find out if socket has to have
  222. // broadcast enabled.
  223. if ((options.getIpVersion() == 4) && options.isBroadcast()) {
  224. int broadcast_enable = 1;
  225. int ret = setsockopt(sock, SOL_SOCKET, SO_BROADCAST,
  226. &broadcast_enable, sizeof(broadcast_enable));
  227. if (ret < 0) {
  228. isc_throw(InvalidOperation,
  229. "unable to set broadcast option on the socket");
  230. }
  231. }
  232. return(sock);
  233. }
  234. void
  235. TestControl::receivePackets() {
  236. int timeout = 0;
  237. bool receiving = true;
  238. while (receiving) {
  239. Pkt4Ptr pkt4 = IfaceMgr::instance().receive4(timeout);
  240. if (!pkt4) {
  241. receiving = false;
  242. } else {
  243. std::cout << "Received packet" << std::endl;
  244. }
  245. }
  246. }
  247. void
  248. TestControl::registerOptionFactories4() const {
  249. static bool factories_registered = false;
  250. if (!factories_registered) {
  251. LibDHCP::OptionFactoryRegister(Option::V4,
  252. DHO_DHCP_MESSAGE_TYPE,
  253. &TestControl::factoryGeneric4);
  254. LibDHCP::OptionFactoryRegister(Option::V4,
  255. DHO_DHCP_PARAMETER_REQUEST_LIST,
  256. &TestControl::factoryRequestList4);
  257. }
  258. factories_registered = true;
  259. }
  260. void
  261. TestControl::registerOptionFactories6() const {
  262. static bool factories_registered = false;
  263. if (!factories_registered) {
  264. }
  265. factories_registered = true;
  266. }
  267. void
  268. TestControl::registerOptionFactories() const {
  269. CommandOptions& options = CommandOptions::instance();
  270. switch(options.getIpVersion()) {
  271. case 4:
  272. registerOptionFactories4();
  273. break;
  274. case 6:
  275. registerOptionFactories6();
  276. break;
  277. default:
  278. isc_throw(InvalidOperation, "command line options have to be parsed "
  279. "before DHCP option factories can be registered");
  280. }
  281. }
  282. void
  283. TestControl::run() {
  284. sent_packets_0_ = 0;
  285. sent_packets_1_ = 0;
  286. CommandOptions& options = CommandOptions::instance();
  287. // Ip version is not set ONLY in case the command options
  288. // were not parsed. This surely means that parse() function
  289. // was not called prior to starting the test. This is fatal
  290. // error.
  291. if (options.getIpVersion() == 0) {
  292. isc_throw(InvalidOperation,
  293. "command options must be parsed before running a test");
  294. }
  295. registerOptionFactories();
  296. TestControlSocket socket(openSocket());
  297. uint64_t packets_sent = 0;
  298. for (;;) {
  299. updateSendDue();
  300. if (checkExitConditions()) {
  301. break;
  302. }
  303. uint64_t packets_due = getNextExchangesNum();
  304. receivePackets();
  305. for (uint64_t i = packets_due; i > 0; --i) {
  306. sendDiscover4(socket);
  307. ++packets_sent;
  308. cout << "Packets sent " << packets_sent << endl;
  309. }
  310. }
  311. }
  312. void
  313. TestControl::sendDiscover4(const TestControlSocket& socket) {
  314. ++sent_packets_0_;
  315. last_sent_ = microsec_clock::universal_time();
  316. std::vector<uint8_t> mac_address = generateMacAddress();
  317. const uint32_t transid = static_cast<uint32_t>(random());
  318. boost::shared_ptr<Pkt4> pkt4(new Pkt4(DHCPDISCOVER, transid));
  319. if (!pkt4) {
  320. isc_throw(Unexpected, "failed to create DISCOVER packet");
  321. }
  322. OptionBuffer buf_msg_type;
  323. buf_msg_type.push_back(DHCPDISCOVER);
  324. pkt4->addOption(Option::factory(Option::V4, DHO_DHCP_MESSAGE_TYPE,
  325. buf_msg_type));
  326. pkt4->addOption(Option::factory(Option::V4,
  327. DHO_DHCP_PARAMETER_REQUEST_LIST));
  328. setDefaults4(socket, pkt4);
  329. pkt4->pack();
  330. IfaceMgr::instance().send(pkt4);
  331. }
  332. void
  333. TestControl::setDefaults4(const TestControlSocket &socket,
  334. const boost::shared_ptr<Pkt4>& pkt) {
  335. CommandOptions& options = CommandOptions::instance();
  336. pkt->setIface(socket.getIface());
  337. pkt->setLocalPort(DHCP4_CLIENT_PORT);
  338. pkt->setRemotePort(DHCP4_SERVER_PORT);
  339. pkt->setRemoteAddr(IOAddress(options.getServerName()));
  340. pkt->setGiaddr(IOAddress(socket.getAddress()));
  341. pkt->setHops(1);
  342. }
  343. void
  344. TestControl::updateSendDue() {
  345. // If default constructor was called, this should not happen but
  346. // if somebody has changed default constructor it is better to
  347. // keep this check.
  348. if (last_sent_.is_not_a_date_time()) {
  349. isc_throw(Unexpected, "time of last sent packet not initialized");
  350. }
  351. // Get the expected exchange rate.
  352. CommandOptions& options = CommandOptions::instance();
  353. int rate = options.getRate();
  354. // If rate was not specified we will wait just one clock tick to
  355. // send next packet. This simulates best effort conditions.
  356. long duration = 1;
  357. if (rate != 0) {
  358. // We use number of ticks instead of nanoseconds because
  359. // nanosecond resolution may not be available on some
  360. // machines. Number of ticks guarantees the highest possible
  361. // timer resolution.
  362. duration = time_duration::ticks_per_second() / rate;
  363. }
  364. // Calculate due time to initate next chunk of exchanges.
  365. send_due_ = last_sent_ + time_duration(0, 0, 0, duration);
  366. }
  367. } // namespace perfdhcp
  368. } // namespace isc