Kea  2.3.9
mysql_host_data_source.cc
Go to the documentation of this file.
1 // Copyright (C) 2015-2023 Internet Systems Consortium, Inc. ("ISC")
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 
7 #include <config.h>
8 
9 #include <asiolink/io_service.h>
10 #include <database/db_exceptions.h>
11 #include <dhcp/libdhcp++.h>
12 #include <dhcp/option.h>
13 #include <dhcp/option_definition.h>
14 #include <dhcp/option_space.h>
15 #include <dhcpsrv/cfg_db_access.h>
16 #include <dhcpsrv/cfg_option.h>
17 #include <dhcpsrv/cfgmgr.h>
18 #include <dhcpsrv/dhcpsrv_log.h>
19 #include <dhcpsrv/host_mgr.h>
21 #include <dhcpsrv/timer_mgr.h>
22 #include <util/buffer.h>
24 #include <util/optional.h>
25 
26 #include <boost/algorithm/string/split.hpp>
27 #include <boost/algorithm/string/classification.hpp>
28 #include <boost/array.hpp>
29 #include <boost/pointer_cast.hpp>
30 #include <boost/static_assert.hpp>
31 
32 #include <mysql.h>
33 #include <mysqld_error.h>
34 #include <stdint.h>
35 
36 #include <mutex>
37 #include <string>
38 
39 using namespace isc;
40 using namespace isc::asiolink;
41 using namespace isc::db;
42 using namespace isc::dhcp;
43 using namespace isc::util;
44 using namespace isc::data;
45 using namespace std;
46 
47 namespace {
48 
53 const uint8_t MAX_IDENTIFIER_TYPE = static_cast<uint8_t>(Host::LAST_IDENTIFIER_TYPE);
54 
83 class MySqlHostExchange {
84 private:
89 
90  static const size_t HOST_ID_COL = 0;
91  static const size_t DHCP_IDENTIFIER_COL = 1;
92  static const size_t DHCP_IDENTIFIER_TYPE_COL = 2;
93  static const size_t DHCP4_SUBNET_ID_COL = 3;
94  static const size_t DHCP6_SUBNET_ID_COL = 4;
95  static const size_t IPV4_ADDRESS_COL = 5;
96  static const size_t HOSTNAME_COL = 6;
97  static const size_t DHCP4_CLIENT_CLASSES_COL = 7;
98  static const size_t DHCP6_CLIENT_CLASSES_COL = 8;
99  static const size_t USER_CONTEXT_COL = 9;
100  static const size_t DHCP4_NEXT_SERVER_COL = 10;
101  static const size_t DHCP4_SERVER_HOSTNAME_COL = 11;
102  static const size_t DHCP4_BOOT_FILE_NAME_COL = 12;
103  static const size_t AUTH_KEY_COL = 13;
105  static const size_t HOST_COLUMNS = 14;
107 
108 public:
109 
116  MySqlHostExchange(const size_t additional_columns_num = 0)
117  : columns_num_(HOST_COLUMNS + additional_columns_num),
118  bind_(columns_num_), columns_(columns_num_),
119  error_(columns_num_, MLM_FALSE), host_id_(0),
120  dhcp_identifier_length_(0), dhcp_identifier_type_(0),
121  dhcp4_subnet_id_(SUBNET_ID_UNUSED),
122  dhcp6_subnet_id_(SUBNET_ID_UNUSED), ipv4_address_(0),
123  hostname_length_(0), dhcp4_client_classes_length_(0),
124  dhcp6_client_classes_length_(0),
125  user_context_length_(0),
126  dhcp4_next_server_(0),
127  dhcp4_server_hostname_length_(0),
128  dhcp4_boot_file_name_length_(0),
129  auth_key_length_(0),
130  dhcp4_subnet_id_null_(MLM_FALSE),
131  dhcp6_subnet_id_null_(MLM_FALSE),
132  ipv4_address_null_(MLM_FALSE), hostname_null_(MLM_FALSE),
133  dhcp4_client_classes_null_(MLM_FALSE),
134  dhcp6_client_classes_null_(MLM_FALSE),
135  user_context_null_(MLM_FALSE),
136  dhcp4_next_server_null_(MLM_FALSE),
137  dhcp4_server_hostname_null_(MLM_FALSE),
138  dhcp4_boot_file_name_null_(MLM_FALSE),
139  auth_key_null_(MLM_FALSE) {
140 
141  // Fill arrays with 0 so as they don't include any garbage.
142  memset(dhcp_identifier_buffer_, 0, sizeof(dhcp_identifier_buffer_));
143  memset(hostname_, 0, sizeof(hostname_));
144  memset(dhcp4_client_classes_, 0, sizeof(dhcp4_client_classes_));
145  memset(dhcp6_client_classes_, 0, sizeof(dhcp6_client_classes_));
146  memset(user_context_, 0, sizeof(user_context_));
147  memset(dhcp4_server_hostname_, 0, sizeof(dhcp4_server_hostname_));
148  memset(dhcp4_boot_file_name_, 0, sizeof(dhcp4_boot_file_name_));
149  memset(auth_key_, 0, sizeof(auth_key_));
150 
151  // Set the column names for use by this class. This only comprises
152  // names used by the MySqlHostExchange class. Derived classes will
153  // need to set names for the columns they use.
154  columns_[HOST_ID_COL] = "host_id";
155  columns_[DHCP_IDENTIFIER_COL] = "dhcp_identifier";
156  columns_[DHCP_IDENTIFIER_TYPE_COL] = "dhcp_identifier_type";
157  columns_[DHCP4_SUBNET_ID_COL] = "dhcp4_subnet_id";
158  columns_[DHCP6_SUBNET_ID_COL] = "dhcp6_subnet_id";
159  columns_[IPV4_ADDRESS_COL] = "ipv4_address";
160  columns_[HOSTNAME_COL] = "hostname";
161  columns_[DHCP4_CLIENT_CLASSES_COL] = "dhcp4_client_classes";
162  columns_[DHCP6_CLIENT_CLASSES_COL] = "dhcp6_client_classes";
163  columns_[USER_CONTEXT_COL] = "user_context";
164  columns_[DHCP4_NEXT_SERVER_COL] = "dhcp4_next_server";
165  columns_[DHCP4_SERVER_HOSTNAME_COL] = "dhcp4_server_hostname";
166  columns_[DHCP4_BOOT_FILE_NAME_COL] = "dhcp4_boot_file_name";
167  columns_[AUTH_KEY_COL] = "auth_key";
168 
169  BOOST_STATIC_ASSERT(13 < HOST_COLUMNS);
170  };
171 
173  virtual ~MySqlHostExchange() {
174  }
175 
190  size_t findAvailColumn() const {
191  std::vector<std::string>::const_iterator empty_column =
192  std::find(columns_.begin(), columns_.end(), std::string());
193  return (std::distance(columns_.begin(), empty_column));
194  }
195 
199  uint64_t getHostId() const {
200  return (host_id_);
201  };
202 
213  static void setErrorIndicators(std::vector<MYSQL_BIND>& bind,
214  std::vector<my_bools>& error) {
215  for (size_t i = 0; i < error.size(); ++i) {
216  error[i] = MLM_FALSE;
217  bind[i].error = reinterpret_cast<my_bool*>(&error[i]);
218  }
219  };
220 
234  static std::string getColumnsInError(std::vector<my_bools>& error,
235  const std::vector<std::string>& names) {
236  std::string result = "";
237 
238  // Accumulate list of column names
239  for (size_t i = 0; i < names.size(); ++i) {
240  if (error[i] == MLM_TRUE) {
241  if (!result.empty()) {
242  result += ", ";
243  }
244  result += names[i];
245  }
246  }
247 
248  if (result.empty()) {
249  result = "(None)";
250  }
251 
252  return (result);
253  };
254 
267  std::vector<MYSQL_BIND> createBindForSend(const HostPtr& host, const bool unique_ip) {
268  // Store host object to ensure it remains valid.
269  host_ = host;
270 
271  // Initialize prior to constructing the array of MYSQL_BIND structures.
272  // It sets all fields, including is_null, to zero, so we need to set
273  // is_null only if it should be true. This gives up minor performance
274  // benefit while being safe approach.
275  memset(&bind_[0], 0, sizeof(MYSQL_BIND) * bind_.size());
276 
277  // Set up the structures for the various components of the host structure.
278 
279  try {
280  // host_id : INT UNSIGNED NOT NULL
281  // The host_id is auto_incremented by MySQL database,
282  // so we need to pass the NULL value
283  host_id_ = 0;
284  bind_[0].buffer_type = MYSQL_TYPE_LONG;
285  bind_[0].buffer = reinterpret_cast<char*>(&host_id_);
286  bind_[0].is_unsigned = MLM_TRUE;
287 
288  // dhcp_identifier : VARBINARY(255) NOT NULL
289  dhcp_identifier_length_ = host->getIdentifier().size();
290  memcpy(static_cast<void*>(dhcp_identifier_buffer_),
291  &(host->getIdentifier())[0],
292  host->getIdentifier().size());
293 
294  bind_[1].buffer_type = MYSQL_TYPE_BLOB;
295  bind_[1].buffer = dhcp_identifier_buffer_;
296  bind_[1].buffer_length = dhcp_identifier_length_;
297  bind_[1].length = &dhcp_identifier_length_;
298 
299  // dhcp_identifier_type : TINYINT NOT NULL
300  dhcp_identifier_type_ = static_cast<uint8_t>(host->getIdentifierType());
301  bind_[2].buffer_type = MYSQL_TYPE_TINY;
302  bind_[2].buffer = reinterpret_cast<char*>(&dhcp_identifier_type_);
303  bind_[2].is_unsigned = MLM_TRUE;
304 
305  // dhcp4_subnet_id : INT UNSIGNED NULL
306  // Can't take an address of intermediate object, so let's store it
307  // in dhcp4_subnet_id_
308  dhcp4_subnet_id_ = host->getIPv4SubnetID();
309  dhcp4_subnet_id_null_ = host->getIPv4SubnetID() == SUBNET_ID_UNUSED ? MLM_TRUE : MLM_FALSE;
310  bind_[3].buffer_type = MYSQL_TYPE_LONG;
311  bind_[3].buffer = reinterpret_cast<char*>(&dhcp4_subnet_id_);
312  bind_[3].is_unsigned = MLM_TRUE;
313  bind_[3].is_null = &dhcp4_subnet_id_null_;
314 
315  // dhcp6_subnet_id : INT UNSIGNED NULL
316  // Can't take an address of intermediate object, so let's store it
317  // in dhcp6_subnet_id_
318  dhcp6_subnet_id_ = host->getIPv6SubnetID();
319  dhcp6_subnet_id_null_ = host->getIPv6SubnetID() == SUBNET_ID_UNUSED ? MLM_TRUE : MLM_FALSE;
320  bind_[4].buffer_type = MYSQL_TYPE_LONG;
321  bind_[4].buffer = reinterpret_cast<char*>(&dhcp6_subnet_id_);
322  bind_[4].is_unsigned = MLM_TRUE;
323  bind_[4].is_null = &dhcp6_subnet_id_null_;
324 
325  // ipv4_address : INT UNSIGNED NULL
326  // The address in the Host structure is an IOAddress object. Convert
327  // this to an integer for storage.
328  ipv4_address_ = host->getIPv4Reservation().toUint32();
329  ipv4_address_null_ = ipv4_address_ == 0 ? MLM_TRUE : MLM_FALSE;
330  bind_[5].buffer_type = MYSQL_TYPE_LONG;
331  bind_[5].buffer = reinterpret_cast<char*>(&ipv4_address_);
332  bind_[5].is_unsigned = MLM_TRUE;
333  bind_[5].is_null = &ipv4_address_null_;
334 
335  // hostname : VARCHAR(255) NULL
336  strncpy(hostname_, host->getHostname().c_str(), HOSTNAME_MAX_LEN - 1);
337  hostname_length_ = host->getHostname().length();
338  bind_[6].buffer_type = MYSQL_TYPE_STRING;
339  bind_[6].buffer = reinterpret_cast<char*>(hostname_);
340  bind_[6].buffer_length = hostname_length_;
341 
342  // dhcp4_client_classes : VARCHAR(255) NULL
343  bind_[7].buffer_type = MYSQL_TYPE_STRING;
344  // Override default separator to not include space after comma.
345  string classes4_txt = host->getClientClasses4().toText(",");
346  strncpy(dhcp4_client_classes_, classes4_txt.c_str(), CLIENT_CLASSES_MAX_LEN - 1);
347  bind_[7].buffer = dhcp4_client_classes_;
348  bind_[7].buffer_length = classes4_txt.length();
349 
350  // dhcp6_client_classes : VARCHAR(255) NULL
351  bind_[8].buffer_type = MYSQL_TYPE_STRING;
352  // Override default separator to not include space after comma.
353  string classes6_txt = host->getClientClasses6().toText(",");
354  strncpy(dhcp6_client_classes_, classes6_txt.c_str(), CLIENT_CLASSES_MAX_LEN - 1);
355  bind_[8].buffer = dhcp6_client_classes_;
356  bind_[8].buffer_length = classes6_txt.length();
357 
358  // user_context : TEXT NULL
359  ConstElementPtr ctx = host->getContext();
360  if (ctx) {
361  bind_[9].buffer_type = MYSQL_TYPE_STRING;
362  string ctx_txt = ctx->str();
363  strncpy(user_context_, ctx_txt.c_str(), USER_CONTEXT_MAX_LEN - 1);
364  bind_[9].buffer = user_context_;
365  bind_[9].buffer_length = ctx_txt.length();
366  } else {
367  bind_[9].buffer_type = MYSQL_TYPE_NULL;
368  }
369 
370  // ipv4_address : INT UNSIGNED NULL
371  // The address in the Host structure is an IOAddress object. Convert
372  // this to an integer for storage.
373  dhcp4_next_server_ = host->getNextServer().toUint32();
374  bind_[10].buffer_type = MYSQL_TYPE_LONG;
375  bind_[10].buffer = reinterpret_cast<char*>(&dhcp4_next_server_);
376  bind_[10].is_unsigned = MLM_TRUE;
377  // bind_[10].is_null = &MLM_FALSE; // commented out for performance
378  // reasons, see memset() above
379 
380  // dhcp4_server_hostname
381  bind_[11].buffer_type = MYSQL_TYPE_STRING;
382  std::string server_hostname = host->getServerHostname();
383  strncpy(dhcp4_server_hostname_, server_hostname.c_str(),
385  bind_[11].buffer = dhcp4_server_hostname_;
386  bind_[11].buffer_length = server_hostname.length();
387 
388  // dhcp4_boot_file_name
389  bind_[12].buffer_type = MYSQL_TYPE_STRING;
390  std::string boot_file_name = host->getBootFileName();
391  strncpy(dhcp4_boot_file_name_, boot_file_name.c_str(),
393  bind_[12].buffer = dhcp4_boot_file_name_;
394  bind_[12].buffer_length = boot_file_name.length();
395 
396  // auth key
397  bind_[13].buffer_type = MYSQL_TYPE_STRING;
398  std::string auth_key = host->getKey().toText();
399  std::strncpy(auth_key_, auth_key.c_str(), TEXT_AUTH_KEY_LEN - 1);
400  auth_key_null_ = auth_key.empty() ? MLM_TRUE : MLM_FALSE;
401  bind_[13].buffer = auth_key_;
402  bind_[13].buffer_length = auth_key.length();
403 
404  } catch (const std::exception& ex) {
406  "Could not create bind array from Host: "
407  << host->getHostname() << ", reason: " << ex.what());
408  }
409 
410  // Add the data to the vector.
411  std::vector<MYSQL_BIND> vec(bind_.begin(), bind_.begin() + HOST_COLUMNS);
412 
413  // When checking whether the IP is unique we need to bind the IPv4 address
414  // at the end of the query as it has additional binding for the IPv4
415  // address.
416  if (unique_ip) {
417  vec.push_back(bind_[5]); // ipv4_address
418  vec.push_back(bind_[3]); // subnet_id
419  }
420  return (vec);
421  };
422 
430  virtual std::vector<MYSQL_BIND> createBindForReceive() {
431  // Initialize MYSQL_BIND array.
432  // It sets all fields, including is_null, to zero, so we need to set
433  // is_null only if it should be true. This gives up minor performance
434  // benefit while being safe approach. For improved readability, the
435  // code that explicitly sets is_null is there, but is commented out.
436  // This also takes care of setting bind_[X].is_null to MLM_FALSE.
437  memset(&bind_[0], 0, sizeof(MYSQL_BIND) * bind_.size());
438 
439  // host_id : INT UNSIGNED NOT NULL
440  bind_[0].buffer_type = MYSQL_TYPE_LONG;
441  bind_[0].buffer = reinterpret_cast<char*>(&host_id_);
442  bind_[0].is_unsigned = MLM_TRUE;
443 
444  // dhcp_identifier : VARBINARY(255) NOT NULL
445  dhcp_identifier_length_ = sizeof(dhcp_identifier_buffer_);
446  bind_[1].buffer_type = MYSQL_TYPE_BLOB;
447  bind_[1].buffer = reinterpret_cast<char*>(dhcp_identifier_buffer_);
448  bind_[1].buffer_length = dhcp_identifier_length_;
449  bind_[1].length = &dhcp_identifier_length_;
450 
451  // dhcp_identifier_type : TINYINT NOT NULL
452  bind_[2].buffer_type = MYSQL_TYPE_TINY;
453  bind_[2].buffer = reinterpret_cast<char*>(&dhcp_identifier_type_);
454  bind_[2].is_unsigned = MLM_TRUE;
455 
456  // dhcp4_subnet_id : INT UNSIGNED NULL
457  dhcp4_subnet_id_null_ = MLM_FALSE;
458  bind_[3].buffer_type = MYSQL_TYPE_LONG;
459  bind_[3].buffer = reinterpret_cast<char*>(&dhcp4_subnet_id_);
460  bind_[3].is_unsigned = MLM_TRUE;
461  bind_[3].is_null = &dhcp4_subnet_id_null_;
462 
463  // dhcp6_subnet_id : INT UNSIGNED NULL
464  dhcp6_subnet_id_null_ = MLM_FALSE;
465  bind_[4].buffer_type = MYSQL_TYPE_LONG;
466  bind_[4].buffer = reinterpret_cast<char*>(&dhcp6_subnet_id_);
467  bind_[4].is_unsigned = MLM_TRUE;
468  bind_[4].is_null = &dhcp6_subnet_id_null_;
469 
470  // ipv4_address : INT UNSIGNED NULL
471  ipv4_address_null_ = MLM_FALSE;
472  bind_[5].buffer_type = MYSQL_TYPE_LONG;
473  bind_[5].buffer = reinterpret_cast<char*>(&ipv4_address_);
474  bind_[5].is_unsigned = MLM_TRUE;
475  bind_[5].is_null = &ipv4_address_null_;
476 
477  // hostname : VARCHAR(255) NULL
478  hostname_null_ = MLM_FALSE;
479  hostname_length_ = sizeof(hostname_);
480  bind_[6].buffer_type = MYSQL_TYPE_STRING;
481  bind_[6].buffer = reinterpret_cast<char*>(hostname_);
482  bind_[6].buffer_length = hostname_length_;
483  bind_[6].length = &hostname_length_;
484  bind_[6].is_null = &hostname_null_;
485 
486  // dhcp4_client_classes : VARCHAR(255) NULL
487  dhcp4_client_classes_null_ = MLM_FALSE;
488  dhcp4_client_classes_length_ = sizeof(dhcp4_client_classes_);
489  bind_[7].buffer_type = MYSQL_TYPE_STRING;
490  bind_[7].buffer = reinterpret_cast<char*>(dhcp4_client_classes_);
491  bind_[7].buffer_length = dhcp4_client_classes_length_;
492  bind_[7].length = &dhcp4_client_classes_length_;
493  bind_[7].is_null = &dhcp4_client_classes_null_;
494 
495  // dhcp6_client_classes : VARCHAR(255) NULL
496  dhcp6_client_classes_null_ = MLM_FALSE;
497  dhcp6_client_classes_length_ = sizeof(dhcp6_client_classes_);
498  bind_[8].buffer_type = MYSQL_TYPE_STRING;
499  bind_[8].buffer = reinterpret_cast<char*>(dhcp6_client_classes_);
500  bind_[8].buffer_length = dhcp6_client_classes_length_;
501  bind_[8].length = &dhcp6_client_classes_length_;
502  bind_[8].is_null = &dhcp6_client_classes_null_;
503 
504  // user_context : TEXT NULL
505  user_context_null_ = MLM_FALSE;
506  user_context_length_ = sizeof(user_context_);
507  bind_[9].buffer_type = MYSQL_TYPE_STRING;
508  bind_[9].buffer = reinterpret_cast<char*>(user_context_);
509  bind_[9].buffer_length = user_context_length_;
510  bind_[9].length = &user_context_length_;
511  bind_[9].is_null = &user_context_null_;
512 
513  // dhcp4_next_server
514  dhcp4_next_server_null_ = MLM_FALSE;
515  bind_[10].buffer_type = MYSQL_TYPE_LONG;
516  bind_[10].buffer = reinterpret_cast<char*>(&dhcp4_next_server_);
517  bind_[10].is_unsigned = MLM_TRUE;
518  bind_[10].is_null = &dhcp4_next_server_null_;
519 
520  // dhcp4_server_hostname
521  dhcp4_server_hostname_null_ = MLM_FALSE;
522  dhcp4_server_hostname_length_ = sizeof(dhcp4_server_hostname_);
523  bind_[11].buffer_type = MYSQL_TYPE_STRING;
524  bind_[11].buffer = reinterpret_cast<char*>(dhcp4_server_hostname_);
525  bind_[11].buffer_length = dhcp4_server_hostname_length_;
526  bind_[11].length = &dhcp4_server_hostname_length_;
527  bind_[11].is_null = &dhcp4_server_hostname_null_;
528 
529  // dhcp4_boot_file_name
530  dhcp4_boot_file_name_null_ = MLM_FALSE;
531  dhcp4_boot_file_name_length_ = sizeof(dhcp4_boot_file_name_);
532  bind_[12].buffer_type = MYSQL_TYPE_STRING;
533  bind_[12].buffer = reinterpret_cast<char*>(dhcp4_boot_file_name_);
534  bind_[12].buffer_length = dhcp4_boot_file_name_length_;
535  bind_[12].length = &dhcp4_boot_file_name_length_;
536  bind_[12].is_null = &dhcp4_boot_file_name_null_;
537 
538  // auth_key_
539  auth_key_null_ = MLM_FALSE;
540  auth_key_length_ = sizeof(auth_key_);
541  bind_[13].buffer_type = MYSQL_TYPE_STRING;
542  bind_[13].buffer = reinterpret_cast<char*>(auth_key_);
543  bind_[13].buffer_length = auth_key_length_;
544  bind_[13].length = &auth_key_length_;
545  bind_[13].is_null = &auth_key_null_;
546 
547  // Add the error flags
548  setErrorIndicators(bind_, error_);
549 
550  // Add the data to the vector. Note the end element is one after the
551  // end of the array.
552  return (bind_);
553  };
554 
563  HostPtr retrieveHost() {
564  // Check if the identifier stored in the database is correct.
565  if (dhcp_identifier_type_ > MAX_IDENTIFIER_TYPE) {
566  isc_throw(BadValue, "invalid dhcp identifier type returned: "
567  << static_cast<int>(dhcp_identifier_type_));
568  }
569  // Set the dhcp identifier type in a variable of the appropriate
570  // data type.
571  Host::IdentifierType type =
572  static_cast<Host::IdentifierType>(dhcp_identifier_type_);
573 
574  // Set DHCPv4 subnet ID to the value returned. If NULL returned,
575  // set to 0.
576  SubnetID ipv4_subnet_id(SUBNET_ID_UNUSED);
577  if (dhcp4_subnet_id_null_ == MLM_FALSE) {
578  ipv4_subnet_id = static_cast<SubnetID>(dhcp4_subnet_id_);
579  }
580 
581  // Set DHCPv6 subnet ID to the value returned. If NULL returned,
582  // set to 0.
583  SubnetID ipv6_subnet_id(SUBNET_ID_UNUSED);
584  if (dhcp6_subnet_id_null_ == MLM_FALSE) {
585  ipv6_subnet_id = static_cast<SubnetID>(dhcp6_subnet_id_);
586  }
587 
588  // Set IPv4 address reservation if it was given, if not, set IPv4 zero
589  // address
590  asiolink::IOAddress ipv4_reservation = asiolink::IOAddress::IPV4_ZERO_ADDRESS();
591  if (ipv4_address_null_ == MLM_FALSE) {
592  ipv4_reservation = asiolink::IOAddress(ipv4_address_);
593  }
594 
595  // Set hostname if non NULL value returned. Otherwise, leave an
596  // empty string.
597  std::string hostname;
598  if (hostname_null_ == MLM_FALSE) {
599  hostname = std::string(hostname_, hostname_length_);
600  }
601 
602  // Set DHCPv4 client classes if non NULL value returned.
603  std::string dhcp4_client_classes;
604  if (dhcp4_client_classes_null_ == MLM_FALSE) {
605  dhcp4_client_classes = std::string(dhcp4_client_classes_,
606  dhcp4_client_classes_length_);
607  }
608 
609  // Set DHCPv6 client classes if non NULL value returned.
610  std::string dhcp6_client_classes;
611  if (dhcp6_client_classes_null_ == MLM_FALSE) {
612  dhcp6_client_classes = std::string(dhcp6_client_classes_,
613  dhcp6_client_classes_length_);
614  }
615 
616  // Convert user_context to string as well.
617  std::string user_context;
618  if (user_context_null_ == MLM_FALSE) {
619  user_context_[user_context_length_] = '\0';
620  user_context.assign(user_context_);
621  }
622 
623  // Set next server value (siaddr) if non NULL value returned.
624  asiolink::IOAddress next_server = asiolink::IOAddress::IPV4_ZERO_ADDRESS();
625  if (dhcp4_next_server_null_ == MLM_FALSE) {
626  next_server = asiolink::IOAddress(dhcp4_next_server_);
627  }
628 
629  // Set server hostname (sname) if non NULL value returned.
630  std::string dhcp4_server_hostname;
631  if (dhcp4_server_hostname_null_ == MLM_FALSE) {
632  dhcp4_server_hostname = std::string(dhcp4_server_hostname_,
633  dhcp4_server_hostname_length_);
634  }
635 
636  // Set boot file name (file) if non NULL value returned.
637  std::string dhcp4_boot_file_name;
638  if (dhcp4_boot_file_name_null_ == MLM_FALSE) {
639  dhcp4_boot_file_name = std::string(dhcp4_boot_file_name_,
640  dhcp4_boot_file_name_length_);
641  }
642 
643  // Set the auth key if a non empty array is retrieved
644  std::string auth_key;
645  if (auth_key_null_ == MLM_FALSE) {
646  auth_key = std::string(auth_key_, auth_key_length_);
647  }
648 
649  // Create and return Host object from the data gathered.
650  HostPtr h(new Host(dhcp_identifier_buffer_, dhcp_identifier_length_,
651  type, ipv4_subnet_id, ipv6_subnet_id, ipv4_reservation,
652  hostname, dhcp4_client_classes, dhcp6_client_classes,
653  next_server, dhcp4_server_hostname,
654  dhcp4_boot_file_name, AuthKey(auth_key)));
655  h->setHostId(host_id_);
656 
657  // Set the user context if there is one.
658  if (!user_context.empty()) {
659  try {
660  ConstElementPtr ctx = Element::fromJSON(user_context);
661  if (!ctx || (ctx->getType() != Element::map)) {
662  isc_throw(BadValue, "user context '" << user_context
663  << "' is not a JSON map");
664  }
665  h->setContext(ctx);
666  } catch (const isc::data::JSONError& ex) {
667  isc_throw(BadValue, "user context '" << user_context
668  << "' is invalid JSON: " << ex.what());
669  }
670  }
671 
672  return (h);
673  };
674 
688  virtual void processFetchedData(ConstHostCollection& hosts) {
689  HostPtr host;
690  // Add new host only if there are no hosts yet or the host id of the
691  // most recently added host is different than the host id of the
692  // currently processed host.
693  if (hosts.empty() || (hosts.back()->getHostId() != getHostId())) {
694  // Create Host object from the fetched data and append it to the
695  // collection.
696  host = retrieveHost();
697  hosts.push_back(host);
698  }
699  }
700 
711  std::string getErrorColumns() {
712  return (getColumnsInError(error_, columns_));
713  };
714 
715 protected:
716 
718  size_t columns_num_;
719 
721  std::vector<MYSQL_BIND> bind_;
722 
724  std::vector<std::string> columns_;
725 
727  std::vector<my_bools> error_;
728 
731  HostPtr host_;
732 
733 private:
734 
736  uint64_t host_id_;
737 
740  uint8_t dhcp_identifier_buffer_[ClientId::MAX_CLIENT_ID_LEN];
741 
743  unsigned long dhcp_identifier_length_;
744 
747  uint8_t dhcp_identifier_type_;
748 
750  uint32_t dhcp4_subnet_id_;
751 
753  uint32_t dhcp6_subnet_id_;
754 
756  uint32_t ipv4_address_;
757 
759  char hostname_[HOSTNAME_MAX_LEN];
760 
762  unsigned long hostname_length_;
763 
765  char dhcp4_client_classes_[CLIENT_CLASSES_MAX_LEN];
766 
769  unsigned long dhcp4_client_classes_length_;
770 
772  char dhcp6_client_classes_[CLIENT_CLASSES_MAX_LEN];
773 
776  unsigned long dhcp6_client_classes_length_;
777 
779  char user_context_[USER_CONTEXT_MAX_LEN];
780 
782  unsigned long user_context_length_;
783 
785  uint32_t dhcp4_next_server_;
786 
788  char dhcp4_server_hostname_[SERVER_HOSTNAME_MAX_LEN];
789 
791  unsigned long dhcp4_server_hostname_length_;
792 
794  char dhcp4_boot_file_name_[BOOT_FILE_NAME_MAX_LEN];
795 
797  unsigned long dhcp4_boot_file_name_length_;
798 
800  char auth_key_[TEXT_AUTH_KEY_LEN];
801 
803  unsigned long auth_key_length_;
804 
807 
808  my_bool dhcp4_subnet_id_null_;
810 
812  my_bool dhcp6_subnet_id_null_;
813 
815  my_bool ipv4_address_null_;
816 
818  my_bool hostname_null_;
819 
822  my_bool dhcp4_client_classes_null_;
823 
826  my_bool dhcp6_client_classes_null_;
827 
829  my_bool user_context_null_;
830 
832  my_bool dhcp4_next_server_null_;
833 
835  my_bool dhcp4_server_hostname_null_;
836 
838  my_bool dhcp4_boot_file_name_null_;
839 
841  my_bool auth_key_null_;
842 
844 };
845 
855 class MySqlHostWithOptionsExchange : public MySqlHostExchange {
856 private:
857 
859  static const size_t OPTION_COLUMNS = 8;
860 
875  class OptionProcessor {
876  public:
877 
884  OptionProcessor(const Option::Universe& universe,
885  const size_t start_column)
886  : universe_(universe), start_column_(start_column), option_id_(0),
887  code_(0), value_length_(0), formatted_value_length_(0),
888  space_length_(0), persistent_(false), cancelled_(false),
889  user_context_length_(0),
890  option_id_null_(MLM_FALSE), code_null_(MLM_FALSE),
891  value_null_(MLM_FALSE), formatted_value_null_(MLM_FALSE),
892  space_null_(MLM_FALSE), user_context_null_(MLM_FALSE),
893  option_id_index_(start_column), code_index_(start_column_ + 1),
894  value_index_(start_column_ + 2),
895  formatted_value_index_(start_column_ + 3),
896  space_index_(start_column_ + 4),
897  persistent_index_(start_column_ + 5),
898  cancelled_index_(start_column_ + 6),
899  user_context_index_(start_column_ + 7),
900  most_recent_option_id_(0) {
901 
902  memset(value_, 0, sizeof(value_));
903  memset(formatted_value_, 0, sizeof(formatted_value_));
904  memset(space_, 0, sizeof(space_));
905  memset(user_context_, 0, sizeof(user_context_));
906  }
907 
909  uint64_t getOptionId() const {
910  if (option_id_null_ == MLM_FALSE) {
911  return (option_id_);
912  }
913  return (0);
914  }
915 
928  void retrieveOption(const CfgOptionPtr& cfg) {
929  // option_id may be NULL if dhcp4_options or dhcp6_options table
930  // doesn't contain any options for the particular host. Also, the
931  // current option id must be greater than id if the most recent
932  // option because options are ordered by option id. Otherwise
933  // we assume that this is already processed option.
934  if ((option_id_null_ == MLM_TRUE) ||
935  (most_recent_option_id_ >= option_id_)) {
936  return;
937  }
938 
939  // Remember current option id as the most recent processed one. We
940  // will be comparing it with option ids in subsequent rows.
941  most_recent_option_id_ = option_id_;
942 
943  // Convert it to string object for easier comparison.
944  std::string space;
945  if (space_null_ == MLM_FALSE) {
946  // Typically, the string values returned by the database are not
947  // NULL terminated.
948  space_[space_length_] = '\0';
949  space.assign(space_);
950  }
951 
952  // If empty or null space provided, use a default top level space.
953  if (space.empty()) {
954  space = (universe_ == Option::V4 ?
956  }
957 
958  // Convert formatted_value to string as well.
959  std::string formatted_value;
960  if (formatted_value_null_ == MLM_FALSE) {
961  formatted_value_[formatted_value_length_] = '\0';
962  formatted_value.assign(formatted_value_);
963  }
964 
965  // Convert user_context to string as well.
966  std::string user_context;
967  if (user_context_null_ == MLM_FALSE) {
968  user_context_[user_context_length_] = '\0';
969  user_context.assign(user_context_);
970  }
971 
972  // Options are held in a binary or textual format in the database.
973  // This is similar to having an option specified in a server
974  // configuration file. Such option is converted to appropriate C++
975  // class, using option definition. Thus, we need to find the
976  // option definition for this option code and option space.
977 
978  // Check if this is a standard option.
979  OptionDefinitionPtr def = LibDHCP::getOptionDef(space, code_);
980 
981  // Otherwise, we may check if this an option encapsulated within the
982  // vendor space.
983  if (!def && (space != DHCP4_OPTION_SPACE) &&
984  (space != DHCP6_OPTION_SPACE)) {
985  uint32_t vendor_id = LibDHCP::optionSpaceToVendorId(space);
986  if (vendor_id > 0) {
987  def = LibDHCP::getVendorOptionDef(universe_, vendor_id, code_);
988  }
989  }
990 
991  // In all other cases, we use runtime option definitions, which
992  // should be also registered within the libdhcp++.
993  if (!def) {
994  def = LibDHCP::getRuntimeOptionDef(space, code_);
995  }
996 
997  OptionPtr option;
998 
999  if (!def) {
1000  // If no definition found, we use generic option type.
1001  OptionBuffer buf(value_, value_ + value_length_);
1002  option.reset(new Option(universe_, code_, buf.begin(),
1003  buf.end()));
1004  } else {
1005  // The option value may be specified in textual or binary format
1006  // in the database. If formatted_value is empty, the binary
1007  // format is used. Depending on the format we use a different
1008  // variant of the optionFactory function.
1009  if (formatted_value.empty()) {
1010  OptionBuffer buf(value_, value_ + value_length_);
1011  option = def->optionFactory(universe_, code_, buf.begin(),
1012  buf.end());
1013  } else {
1014  // Spit the value specified in comma separated values
1015  // format.
1016  std::vector<std::string> split_vec;
1017  boost::split(split_vec, formatted_value, boost::is_any_of(","));
1018  option = def->optionFactory(universe_, code_, split_vec);
1019  }
1020  }
1021 
1022  OptionDescriptor desc(option, persistent_, cancelled_,
1023  formatted_value);
1024 
1025  // Set the user context if there is one into the option descriptor.
1026  if (!user_context.empty()) {
1027  try {
1028  ConstElementPtr ctx = Element::fromJSON(user_context);
1029  if (!ctx || (ctx->getType() != Element::map)) {
1030  isc_throw(BadValue, "user context '" << user_context
1031  << "' is no a JSON map");
1032  }
1033  desc.setContext(ctx);
1034  } catch (const isc::data::JSONError& ex) {
1035  isc_throw(BadValue, "user context '" << user_context
1036  << "' is invalid JSON: " << ex.what());
1037  }
1038  }
1039 
1040  cfg->add(desc, space);
1041  }
1042 
1047  void setColumnNames(std::vector<std::string>& columns) {
1048  columns[option_id_index_] = "option_id";
1049  columns[code_index_] = "code";
1050  columns[value_index_] = "value";
1051  columns[formatted_value_index_] = "formatted_value";
1052  columns[space_index_] = "space";
1053  columns[persistent_index_] = "persistent";
1054  columns[cancelled_index_] = "cancelled";
1055  columns[user_context_index_] = "user_context";
1056  }
1057 
1064  void setBindFields(std::vector<MYSQL_BIND>& bind) {
1065  // This method is called just before making a new query, so we
1066  // reset the most_recent_option_id_ and other exchange members to
1067  // start over with options processing.
1068  most_recent_option_id_ = 0;
1069 
1070  option_id_ = 0;
1071  code_ = 0;
1072  persistent_ = false;
1073  cancelled_ = false;
1074  option_id_null_ = MLM_FALSE;
1075  code_null_ = MLM_FALSE;
1076  value_null_ = MLM_FALSE;
1077  formatted_value_null_ = MLM_FALSE;
1078  space_null_ = MLM_FALSE;
1079  user_context_null_ = MLM_FALSE;
1080 
1081  memset(value_, 0, sizeof(value_));
1082  memset(formatted_value_, 0, sizeof(formatted_value_));
1083  memset(space_, 0, sizeof(space_));
1084  memset(user_context_, 0, sizeof(user_context_));
1085 
1086  // option_id : INT UNSIGNED NOT NULL AUTO_INCREMENT,
1087  bind[option_id_index_].buffer_type = MYSQL_TYPE_LONG;
1088  bind[option_id_index_].buffer = reinterpret_cast<char*>(&option_id_);
1089  bind[option_id_index_].is_unsigned = MLM_TRUE;
1090  bind[option_id_index_].is_null = &option_id_null_;
1091 
1092  // code : TINYINT OR SHORT UNSIGNED NOT NULL
1093  bind[code_index_].buffer_type = MYSQL_TYPE_SHORT;
1094  bind[code_index_].buffer = reinterpret_cast<char*>(&code_);
1095  bind[code_index_].is_unsigned = MLM_TRUE;
1096  bind[code_index_].is_null = &code_null_;
1097 
1098  // value : BLOB NULL
1099  value_length_ = sizeof(value_);
1100  bind[value_index_].buffer_type = MYSQL_TYPE_BLOB;
1101  bind[value_index_].buffer = reinterpret_cast<char*>(value_);
1102  bind[value_index_].buffer_length = value_length_;
1103  bind[value_index_].length = &value_length_;
1104  bind[value_index_].is_null = &value_null_;
1105 
1106  // formatted_value : TEXT NULL
1107  formatted_value_length_ = sizeof(formatted_value_);
1108  bind[formatted_value_index_].buffer_type = MYSQL_TYPE_STRING;
1109  bind[formatted_value_index_].buffer = reinterpret_cast<char*>(formatted_value_);
1110  bind[formatted_value_index_].buffer_length = formatted_value_length_;
1111  bind[formatted_value_index_].length = &formatted_value_length_;
1112  bind[formatted_value_index_].is_null = &formatted_value_null_;
1113 
1114  // space : VARCHAR(128) NULL
1115  space_length_ = sizeof(space_);
1116  bind[space_index_].buffer_type = MYSQL_TYPE_STRING;
1117  bind[space_index_].buffer = reinterpret_cast<char*>(space_);
1118  bind[space_index_].buffer_length = space_length_;
1119  bind[space_index_].length = &space_length_;
1120  bind[space_index_].is_null = &space_null_;
1121 
1122  // persistent : TINYINT(1) NOT NULL DEFAULT 0
1123  bind[persistent_index_].buffer_type = MYSQL_TYPE_TINY;
1124  bind[persistent_index_].buffer = reinterpret_cast<char*>(&persistent_);
1125  bind[persistent_index_].is_unsigned = MLM_TRUE;
1126 
1127  // cancelled : TINYINT(1) NOT NULL DEFAULT 0
1128  bind[cancelled_index_].buffer_type = MYSQL_TYPE_TINY;
1129  bind[cancelled_index_].buffer = reinterpret_cast<char*>(&cancelled_);
1130  bind[cancelled_index_].is_unsigned = MLM_TRUE;
1131 
1132  // user_context : TEXT NULL
1133  user_context_length_ = sizeof(user_context_);
1134  bind[user_context_index_].buffer_type = MYSQL_TYPE_STRING;
1135  bind[user_context_index_].buffer = reinterpret_cast<char*>(user_context_);
1136  bind[user_context_index_].buffer_length = user_context_length_;
1137  bind[user_context_index_].length = &user_context_length_;
1138  bind[user_context_index_].is_null = &user_context_null_;
1139  }
1140 
1141  private:
1142 
1144  Option::Universe universe_;
1145 
1147  size_t start_column_;
1148 
1150  uint32_t option_id_;
1151 
1153  uint16_t code_;
1154 
1156  uint8_t value_[OPTION_VALUE_MAX_LEN];
1157 
1159  unsigned long value_length_;
1160 
1162  char formatted_value_[OPTION_FORMATTED_VALUE_MAX_LEN];
1163 
1165  unsigned long formatted_value_length_;
1166 
1168  char space_[OPTION_SPACE_MAX_LEN];
1169 
1171  unsigned long space_length_;
1172 
1175  bool persistent_;
1176 
1178  bool cancelled_;
1179 
1181  char user_context_[USER_CONTEXT_MAX_LEN];
1182 
1184  unsigned long user_context_length_;
1185 
1188 
1189  my_bool option_id_null_;
1191 
1193  my_bool code_null_;
1194 
1196  my_bool value_null_;
1197 
1200  my_bool formatted_value_null_;
1201 
1203  my_bool space_null_;
1204 
1206  my_bool user_context_null_;
1208 
1210 
1211  size_t option_id_index_;
1213 
1215  size_t code_index_;
1216 
1218  size_t value_index_;
1219 
1221  size_t formatted_value_index_;
1222 
1224  size_t space_index_;
1225 
1227  size_t persistent_index_;
1228 
1230  size_t cancelled_index_;
1232 
1234  size_t user_context_index_;
1235 
1237  uint32_t most_recent_option_id_;
1238  };
1239 
1241  typedef boost::shared_ptr<OptionProcessor> OptionProcessorPtr;
1242 
1243 public:
1244 
1251  enum FetchedOptions {
1252  DHCP4_ONLY,
1253  DHCP6_ONLY,
1254  DHCP4_AND_DHCP6
1255  };
1256 
1265  MySqlHostWithOptionsExchange(const FetchedOptions& fetched_options,
1266  const size_t additional_columns_num = 0)
1267  : MySqlHostExchange(getRequiredColumnsNum(fetched_options)
1268  + additional_columns_num),
1269  opt_proc4_(), opt_proc6_() {
1270 
1271  // Create option processor for DHCPv4 options, if required.
1272  if ((fetched_options == DHCP4_ONLY) ||
1273  (fetched_options == DHCP4_AND_DHCP6)) {
1274  opt_proc4_.reset(new OptionProcessor(Option::V4,
1275  findAvailColumn()));
1276  opt_proc4_->setColumnNames(columns_);
1277  }
1278 
1279  // Create option processor for DHCPv6 options, if required.
1280  if ((fetched_options == DHCP6_ONLY) ||
1281  (fetched_options == DHCP4_AND_DHCP6)) {
1282  opt_proc6_.reset(new OptionProcessor(Option::V6,
1283  findAvailColumn()));
1284  opt_proc6_->setColumnNames(columns_);
1285  }
1286  }
1287 
1296  virtual void processFetchedData(ConstHostCollection& hosts) {
1297  // Holds pointer to the previously parsed host.
1298  HostPtr most_recent_host;
1299  if (!hosts.empty()) {
1300  // Const cast is not very elegant way to deal with it, but
1301  // there is a good reason to use it here. This method is called
1302  // to build a collection of const hosts to be returned to the
1303  // caller. If we wanted to use non-const collection we'd need
1304  // to copy the whole collection before returning it, which has
1305  // performance implications. Alternatively, we could store the
1306  // most recently added host in a class member but this would
1307  // make the code less readable.
1308  most_recent_host = boost::const_pointer_cast<Host>(hosts.back());
1309  }
1310 
1311  // If no host has been parsed yet or we're at the row holding next
1312  // host, we create a new host object and put it at the end of the
1313  // list.
1314  if (!most_recent_host || (most_recent_host->getHostId() < getHostId())) {
1315  HostPtr host = retrieveHost();
1316  hosts.push_back(host);
1317  most_recent_host = host;
1318  }
1319 
1320  // Parse DHCPv4 options if required to do so.
1321  if (opt_proc4_) {
1322  CfgOptionPtr cfg = most_recent_host->getCfgOption4();
1323  opt_proc4_->retrieveOption(cfg);
1324  }
1325 
1326  // Parse DHCPv6 options if required to do so.
1327  if (opt_proc6_) {
1328  CfgOptionPtr cfg = most_recent_host->getCfgOption6();
1329  opt_proc6_->retrieveOption(cfg);
1330  }
1331  }
1332 
1336  virtual std::vector<MYSQL_BIND> createBindForReceive() {
1337  // The following call sets bind_ values between 0 and 8.
1338  static_cast<void>(MySqlHostExchange::createBindForReceive());
1339 
1340  // Bind variables for DHCPv4 options.
1341  if (opt_proc4_) {
1342  opt_proc4_->setBindFields(bind_);
1343  }
1344 
1345  // Bind variables for DHCPv6 options.
1346  if (opt_proc6_) {
1347  opt_proc6_->setBindFields(bind_);
1348  }
1349 
1350  // Add the error flags
1351  setErrorIndicators(bind_, error_);
1352 
1353  return (bind_);
1354  };
1355 
1356 private:
1357 
1369  static size_t getRequiredColumnsNum(const FetchedOptions& fetched_options) {
1370  return (fetched_options == DHCP4_AND_DHCP6 ? 2 * OPTION_COLUMNS :
1371  OPTION_COLUMNS);
1372  }
1373 
1377  OptionProcessorPtr opt_proc4_;
1378 
1382  OptionProcessorPtr opt_proc6_;
1383 };
1384 
1397 class MySqlHostIPv6Exchange : public MySqlHostWithOptionsExchange {
1398 private:
1399 
1401  static const size_t RESERVATION_COLUMNS = 5;
1402 
1403 public:
1404 
1409  MySqlHostIPv6Exchange(const FetchedOptions& fetched_options)
1410  : MySqlHostWithOptionsExchange(fetched_options, RESERVATION_COLUMNS),
1411  reservation_id_(0),
1412  reserv_type_(0), reserv_type_null_(MLM_FALSE),
1413  ipv6_address_buffer_len_(0), prefix_len_(0), iaid_(0),
1414  reservation_id_index_(findAvailColumn()),
1415  address_index_(reservation_id_index_ + 1),
1416  prefix_len_index_(reservation_id_index_ + 2),
1417  type_index_(reservation_id_index_ + 3),
1418  iaid_index_(reservation_id_index_ + 4),
1419  most_recent_reservation_id_(0) {
1420 
1421  memset(ipv6_address_buffer_, 0, sizeof(ipv6_address_buffer_));
1422 
1423  // Provide names of additional columns returned by the queries.
1424  columns_[reservation_id_index_] = "reservation_id";
1425  columns_[address_index_] = "address";
1426  columns_[prefix_len_index_] = "prefix_len";
1427  columns_[type_index_] = "type";
1428  columns_[iaid_index_] = "dhcp6_iaid";
1429  }
1430 
1434  uint32_t getReservationId() const {
1435  if (reserv_type_null_ == MLM_FALSE) {
1436  return (reservation_id_);
1437  }
1438  return (0);
1439  };
1440 
1447  IPv6Resrv retrieveReservation() {
1448  // Set the IPv6 Reservation type (0 = IA_NA, 2 = IA_PD)
1449  IPv6Resrv::Type type = IPv6Resrv::TYPE_NA;
1450 
1451  switch (reserv_type_) {
1452  case 0:
1453  type = IPv6Resrv::TYPE_NA;
1454  break;
1455 
1456  case 2:
1457  type = IPv6Resrv::TYPE_PD;
1458  break;
1459 
1460  default:
1462  "invalid IPv6 reservation type returned: "
1463  << static_cast<int>(reserv_type_)
1464  << ". Only 0 or 2 are allowed.");
1465  }
1466 
1467  ipv6_address_buffer_[ipv6_address_buffer_len_] = '\0';
1468  std::string address = ipv6_address_buffer_;
1469  IPv6Resrv r(type, IOAddress(address), prefix_len_);
1470  return (r);
1471  };
1472 
1492  virtual void processFetchedData(ConstHostCollection& hosts) {
1493 
1494  // Call parent class to fetch host information and options.
1495  MySqlHostWithOptionsExchange::processFetchedData(hosts);
1496 
1497  if (getReservationId() == 0) {
1498  return;
1499  }
1500 
1501  if (hosts.empty()) {
1502  isc_throw(Unexpected, "no host information while retrieving"
1503  " IPv6 reservation");
1504  }
1505  HostPtr host = boost::const_pointer_cast<Host>(hosts.back());
1506 
1507  // If we're dealing with a new reservation, let's add it to the
1508  // host.
1509  if (getReservationId() > most_recent_reservation_id_) {
1510  most_recent_reservation_id_ = getReservationId();
1511 
1512  if (most_recent_reservation_id_ > 0) {
1513  host->addReservation(retrieveReservation());
1514  }
1515  }
1516  }
1517 
1526  virtual std::vector<MYSQL_BIND> createBindForReceive() {
1527  // Reset most recent reservation id value because we're now making
1528  // a new SELECT query.
1529  most_recent_reservation_id_ = 0;
1530 
1531  // Bind values supported by parent classes.
1532  static_cast<void>(MySqlHostWithOptionsExchange::createBindForReceive());
1533 
1534  // reservation_id : INT UNSIGNED NOT NULL AUTO_INCREMENT
1535  bind_[reservation_id_index_].buffer_type = MYSQL_TYPE_LONG;
1536  bind_[reservation_id_index_].buffer = reinterpret_cast<char*>(&reservation_id_);
1537  bind_[reservation_id_index_].is_unsigned = MLM_TRUE;
1538 
1539  // IPv6 address/prefix VARCHAR(39)
1540  ipv6_address_buffer_len_ = sizeof(ipv6_address_buffer_) - 1;
1541  bind_[address_index_].buffer_type = MYSQL_TYPE_STRING;
1542  bind_[address_index_].buffer = ipv6_address_buffer_;
1543  bind_[address_index_].buffer_length = ipv6_address_buffer_len_;
1544  bind_[address_index_].length = &ipv6_address_buffer_len_;
1545 
1546  // prefix_len : TINYINT
1547  bind_[prefix_len_index_].buffer_type = MYSQL_TYPE_TINY;
1548  bind_[prefix_len_index_].buffer = reinterpret_cast<char*>(&prefix_len_);
1549  bind_[prefix_len_index_].is_unsigned = MLM_TRUE;
1550 
1551  // (reservation) type : TINYINT
1552  reserv_type_null_ = MLM_FALSE;
1553  bind_[type_index_].buffer_type = MYSQL_TYPE_TINY;
1554  bind_[type_index_].buffer = reinterpret_cast<char*>(&reserv_type_);
1555  bind_[type_index_].is_unsigned = MLM_TRUE;
1556  bind_[type_index_].is_null = &reserv_type_null_;
1557 
1558  // dhcp6_iaid INT UNSIGNED
1559  bind_[iaid_index_].buffer_type = MYSQL_TYPE_LONG;
1560  bind_[iaid_index_].buffer = reinterpret_cast<char*>(&iaid_);
1561  bind_[iaid_index_].is_unsigned = MLM_TRUE;
1562 
1563  // Add the error flags
1564  setErrorIndicators(bind_, error_);
1565 
1566  return (bind_);
1567  };
1568 
1569 private:
1570 
1572  uint32_t reservation_id_;
1573 
1575  uint8_t reserv_type_;
1576 
1581  my_bool reserv_type_null_;
1582 
1584  char ipv6_address_buffer_[ADDRESS6_TEXT_MAX_LEN + 1];
1585 
1587  unsigned long ipv6_address_buffer_len_;
1588 
1590  uint8_t prefix_len_;
1591 
1593  uint32_t iaid_;
1594 
1596 
1597  size_t reservation_id_index_;
1599 
1601  size_t address_index_;
1602 
1604  size_t prefix_len_index_;
1605 
1607  size_t type_index_;
1608 
1610  size_t iaid_index_;
1611 
1613 
1615  uint32_t most_recent_reservation_id_;
1616 };
1617 
1628 class MySqlIPv6ReservationExchange {
1629 private:
1630 
1632  static const size_t RESRV_COLUMNS = 6;
1633 
1634 public:
1635 
1639  MySqlIPv6ReservationExchange()
1640  : host_id_(0), address_("::"), address_len_(0), prefix_len_(0), type_(0),
1641  iaid_(0), resv_(IPv6Resrv::TYPE_NA, asiolink::IOAddress("::"), 128) {
1642 
1643  // Reset error table.
1644  std::fill(&error_[0], &error_[RESRV_COLUMNS], MLM_FALSE);
1645 
1646  // Set the column names (for error messages)
1647  columns_[0] = "host_id";
1648  columns_[1] = "address";
1649  columns_[2] = "prefix_len";
1650  columns_[3] = "type";
1651  columns_[4] = "dhcp6_iaid";
1652 
1653  BOOST_STATIC_ASSERT(4 < RESRV_COLUMNS);
1654  }
1655 
1670  std::vector<MYSQL_BIND> createBindForSend(const IPv6Resrv& resv,
1671  const HostID& id,
1672  const bool unique_ip) {
1673 
1674  // Store the values to ensure they remain valid.
1675  resv_ = resv;
1676  host_id_ = id;
1677 
1678  // Initialize prior to constructing the array of MYSQL_BIND structures.
1679  // It sets all fields, including is_null, to zero, so we need to set
1680  // is_null only if it should be true. This gives up minor performance
1681  // benefit while being safe approach. For improved readability, the
1682  // code that explicitly sets is_null is there, but is commented out.
1683  memset(bind_, 0, sizeof(bind_));
1684 
1685  // Set up the structures for the various components of the host structure.
1686 
1687  try {
1688  // address VARCHAR(39)
1689  address_ = resv.getPrefix().toText();
1690  address_len_ = address_.length();
1691  bind_[0].buffer_type = MYSQL_TYPE_BLOB;
1692  bind_[0].buffer = reinterpret_cast<char*>
1693  (const_cast<char*>(address_.c_str()));
1694  bind_[0].buffer_length = address_len_;
1695  bind_[0].length = &address_len_;
1696 
1697  // prefix_len tinyint
1698  prefix_len_ = resv.getPrefixLen();
1699  bind_[1].buffer_type = MYSQL_TYPE_TINY;
1700  bind_[1].buffer = reinterpret_cast<char*>(&prefix_len_);
1701  bind_[1].is_unsigned = MLM_TRUE;
1702 
1703  // type tinyint
1704  // See lease6_types for values (0 = IA_NA, 1 = IA_TA, 2 = IA_PD)
1705  type_ = resv.getType() == IPv6Resrv::TYPE_NA ? 0 : 2;
1706  bind_[2].buffer_type = MYSQL_TYPE_TINY;
1707  bind_[2].buffer = reinterpret_cast<char*>(&type_);
1708  bind_[2].is_unsigned = MLM_TRUE;
1709 
1710  // dhcp6_iaid INT UNSIGNED
1712  iaid_ = 0;
1713  bind_[3].buffer_type = MYSQL_TYPE_LONG;
1714  bind_[3].buffer = reinterpret_cast<char*>(&iaid_);
1715  bind_[3].is_unsigned = MLM_TRUE;
1716 
1717  // host_id INT UNSIGNED NOT NULL
1718  bind_[4].buffer_type = MYSQL_TYPE_LONG;
1719  bind_[4].buffer = reinterpret_cast<char*>(&host_id_);
1720  bind_[4].is_unsigned = MLM_TRUE;
1721 
1722  } catch (const std::exception& ex) {
1724  "Could not create bind array from IPv6 Reservation: "
1725  << resv_.toText() << ", reason: " << ex.what());
1726  }
1727 
1728  // Add the data to the vector. Note the end element is one after the
1729  // end of the array.
1730  // RESRV_COLUMNS -1 as we do not set reservation_id.
1731  std::vector<MYSQL_BIND> vec(&bind_[0], &bind_[RESRV_COLUMNS-1]);
1732 
1733  // When checking whether the IP is unique we need to bind the IPv6 address
1734  // and prefix length at the end of the query as it has additional binding
1735  // for the IPv6 address and prefix length.
1736  if (unique_ip) {
1737  vec.push_back(bind_[0]); // address
1738  vec.push_back(bind_[1]); // prefix_len
1739  }
1740 
1741  return (vec);
1742  }
1743 
1744 private:
1745 
1747  uint64_t host_id_;
1748 
1750  std::string address_;
1751 
1753  unsigned long address_len_;
1754 
1756  uint8_t prefix_len_;
1757 
1759  uint8_t type_;
1760 
1762  uint8_t iaid_;
1763 
1765  IPv6Resrv resv_;
1766 
1768  MYSQL_BIND bind_[RESRV_COLUMNS];
1769 
1771  std::string columns_[RESRV_COLUMNS];
1772 
1775  my_bool error_[RESRV_COLUMNS];
1776 };
1777 
1781 class MySqlOptionExchange {
1782 private:
1783 
1784  static const size_t OPTION_ID_COL = 0;
1785  static const size_t CODE_COL = 1;
1786  static const size_t VALUE_COL = 2;
1787  static const size_t FORMATTED_VALUE_COL = 3;
1788  static const size_t SPACE_COL = 4;
1789  static const size_t PERSISTENT_COL = 5;
1790  static const size_t CANCELLED_COL = 6;
1791  static const size_t USER_CONTEXT_COL = 7;
1792  static const size_t DHCP_SUBNET_ID_COL = 8;
1793  static const size_t HOST_ID_COL = 9;
1795  static const size_t OPTION_COLUMNS = 10;
1796 
1797 public:
1798 
1800  MySqlOptionExchange()
1801  : type_(0), value_len_(0), formatted_value_len_(0), space_(),
1802  space_len_(0), persistent_(false), cancelled_(false),
1803  user_context_(), user_context_len_(0), subnet_id_(SUBNET_ID_UNUSED),
1804  host_id_(0), option_() {
1805 
1806  BOOST_STATIC_ASSERT(10 <= OPTION_COLUMNS);
1807  }
1808 
1812  std::vector<MYSQL_BIND> createBindForSend(const OptionDescriptor& opt_desc,
1813  const std::string& opt_space,
1814  const Optional<SubnetID>& subnet_id,
1815  const HostID& host_id) {
1816 
1817  // Hold pointer to the option to make sure it remains valid until
1818  // we complete a query.
1819  option_ = opt_desc.option_;
1820 
1821  memset(bind_, 0, sizeof(bind_));
1822 
1823  try {
1824  // option_id: INT UNSIGNED NOT NULL
1825  // The option_id is auto_incremented, so we need to pass the NULL
1826  // value.
1827  bind_[0].buffer_type = MYSQL_TYPE_NULL;
1828 
1829  // code: SMALLINT UNSIGNED NOT NULL
1830  type_ = option_->getType();
1831  bind_[1].buffer_type = MYSQL_TYPE_SHORT;
1832  bind_[1].buffer = reinterpret_cast<char*>(&type_);
1833  bind_[1].is_unsigned = MLM_TRUE;
1834 
1835  // value: BLOB NULL
1836  if (opt_desc.formatted_value_.empty() &&
1837  (opt_desc.option_->len() > opt_desc.option_->getHeaderLen())) {
1838  // The formatted_value is empty and the option value is
1839  // non-empty so we need to prepare on-wire format for the
1840  // option and store it in the database as a blob.
1841  OutputBuffer buf(opt_desc.option_->len());
1842  opt_desc.option_->pack(buf);
1843  const char* buf_ptr = static_cast<const char*>(buf.getData());
1844  value_.assign(buf_ptr + opt_desc.option_->getHeaderLen(),
1845  buf_ptr + buf.getLength());
1846  value_len_ = value_.size();
1847  bind_[2].buffer_type = MYSQL_TYPE_BLOB;
1848  bind_[2].buffer = &value_[0];
1849  bind_[2].buffer_length = value_len_;
1850  bind_[2].length = &value_len_;
1851 
1852  } else {
1853  // No value or formatted_value specified. In this case, the
1854  // value blob is NULL.
1855  value_.clear();
1856  bind_[2].buffer_type = MYSQL_TYPE_NULL;
1857  }
1858 
1859  // formatted_value: TEXT NULL,
1860  if (!opt_desc.formatted_value_.empty()) {
1861  formatted_value_len_ = opt_desc.formatted_value_.size();
1862  bind_[3].buffer_type = MYSQL_TYPE_STRING;
1863  bind_[3].buffer = const_cast<char*>(opt_desc.formatted_value_.c_str());
1864  bind_[3].buffer_length = formatted_value_len_;
1865  bind_[3].length = &formatted_value_len_;
1866 
1867  } else {
1868  bind_[3].buffer_type = MYSQL_TYPE_NULL;
1869  }
1870 
1871  // space: VARCHAR(128) NULL
1872  space_ = opt_space;
1873  space_len_ = space_.size();
1874  bind_[4].buffer_type = MYSQL_TYPE_STRING;
1875  bind_[4].buffer = const_cast<char*>(space_.c_str());
1876  bind_[4].buffer_length = space_len_;
1877  bind_[4].length = &space_len_;
1878 
1879  // persistent: TINYINT(1) NOT NULL DEFAULT 0
1880  persistent_ = opt_desc.persistent_;
1881  bind_[5].buffer_type = MYSQL_TYPE_TINY;
1882  bind_[5].buffer = reinterpret_cast<char*>(&persistent_);
1883  bind_[5].is_unsigned = MLM_TRUE;
1884 
1885  // cancelled: TINYINT(1) NOT NULL DEFAULT 0
1886  cancelled_ = opt_desc.cancelled_;
1887  bind_[6].buffer_type = MYSQL_TYPE_TINY;
1888  bind_[6].buffer = reinterpret_cast<char*>(&cancelled_);
1889  bind_[6].is_unsigned = MLM_TRUE;
1890 
1891  // user_context: TEST NULL,
1892  ConstElementPtr ctx = opt_desc.getContext();
1893  if (ctx) {
1894  user_context_ = ctx->str();
1895  user_context_len_ = user_context_.size();
1896  bind_[7].buffer_type = MYSQL_TYPE_STRING;
1897  bind_[7].buffer = const_cast<char*>(user_context_.c_str());
1898  bind_[7].buffer_length = user_context_len_;
1899  bind_[7].length = &user_context_len_;
1900  } else {
1901  bind_[7].buffer_type = MYSQL_TYPE_NULL;
1902  }
1903 
1904  // dhcp4_subnet_id: INT UNSIGNED NULL
1905  if (!subnet_id.unspecified()) {
1906  subnet_id_ = subnet_id;
1907  bind_[8].buffer_type = MYSQL_TYPE_LONG;
1908  bind_[8].buffer = reinterpret_cast<char*>(subnet_id_);
1909  bind_[8].is_unsigned = MLM_TRUE;
1910 
1911  } else {
1912  bind_[8].buffer_type = MYSQL_TYPE_NULL;
1913  }
1914 
1915  // host_id: INT UNSIGNED NOT NULL
1916  host_id_ = host_id;
1917  bind_[9].buffer_type = MYSQL_TYPE_LONG;
1918  bind_[9].buffer = reinterpret_cast<char*>(&host_id_);
1919  bind_[9].is_unsigned = MLM_TRUE;
1920 
1921  } catch (const std::exception& ex) {
1923  "Could not create bind array for inserting DHCP "
1924  "option: " << option_->toText() << ", reason: "
1925  << ex.what());
1926  }
1927 
1928  return (std::vector<MYSQL_BIND>(&bind_[0], &bind_[OPTION_COLUMNS]));
1929  }
1930 
1931 private:
1932 
1934  uint16_t type_;
1935 
1937  std::vector<uint8_t> value_;
1938 
1940  unsigned long value_len_;
1941 
1943  unsigned long formatted_value_len_;
1944 
1946  std::string space_;
1947 
1949  unsigned long space_len_;
1950 
1953  bool persistent_;
1954 
1957  bool cancelled_;
1958 
1960  std::string user_context_;
1961 
1963  unsigned long user_context_len_;
1964 
1966  uint32_t subnet_id_;
1967 
1969  uint32_t host_id_;
1970 
1972  OptionPtr option_;
1973 
1975  MYSQL_BIND bind_[OPTION_COLUMNS];
1976 };
1977 
1978 } // namespace
1979 
1980 namespace isc {
1981 namespace dhcp {
1982 
1993 public:
1994 
2001  IOServiceAccessorPtr io_service_accessor,
2002  db::DbCallback db_reconnect_callback);
2003 
2008 
2011  boost::shared_ptr<MySqlHostWithOptionsExchange> host_ipv4_exchange_;
2012 
2015  boost::shared_ptr<MySqlHostIPv6Exchange> host_ipv6_exchange_;
2016 
2020  boost::shared_ptr<MySqlHostIPv6Exchange> host_ipv46_exchange_;
2021 
2024  boost::shared_ptr<MySqlIPv6ReservationExchange> host_ipv6_reservation_exchange_;
2025 
2029  boost::shared_ptr<MySqlOptionExchange> host_option_exchange_;
2030 
2033 
2036 };
2037 
2045 public:
2046 
2048  std::vector<MySqlHostContextPtr> pool_;
2049 
2051  std::mutex mutex_;
2052 };
2053 
2055 typedef boost::shared_ptr<MySqlHostContextPool> MySqlHostContextPoolPtr;
2056 
2059 public:
2060 
2070  GET_HOST_DHCPID, // Gets hosts by host identifier
2071  GET_HOST_ADDR, // Gets hosts by IPv4 address
2072  GET_HOST_SUBID4_DHCPID, // Gets host by IPv4 SubnetID, HW address/DUID
2073  GET_HOST_SUBID6_DHCPID, // Gets host by IPv6 SubnetID, HW address/DUID
2074  GET_HOST_SUBID_ADDR, // Gets host by IPv4 SubnetID and IPv4 address
2075  GET_HOST_PREFIX, // Gets host by IPv6 prefix
2076  GET_HOST_SUBID6_ADDR, // Gets host by IPv6 SubnetID and IPv6 prefix
2077  GET_HOST_SUBID4, // Gets hosts by IPv4 SubnetID
2078  GET_HOST_SUBID6, // Gets hosts by IPv6 SubnetID
2079  GET_HOST_HOSTNAME, // Gets hosts by hostname
2080  GET_HOST_HOSTNAME_SUBID4, // Gets hosts by hostname and IPv4 SubnetID
2081  GET_HOST_HOSTNAME_SUBID6, // Gets hosts by hostname and IPv6 SubnetID
2082  GET_HOST_SUBID4_PAGE, // Gets hosts by IPv4 SubnetID beginning by HID
2083  GET_HOST_SUBID6_PAGE, // Gets hosts by IPv6 SubnetID beginning by HID
2084  GET_HOST_PAGE4, // Gets v4 hosts beginning by HID
2085  GET_HOST_PAGE6, // Gets v6 hosts beginning by HID
2086  INSERT_HOST_NON_UNIQUE_IP, // Insert new host to collection with allowing IP duplicates
2087  INSERT_HOST_UNIQUE_IP, // Insert new host to collection with checking for IP duplicates
2088  INSERT_V6_RESRV_NON_UNIQUE,// Insert v6 reservation without checking that it is unique
2089  INSERT_V6_RESRV_UNIQUE, // Insert v6 reservation with checking that it is unique
2090  INSERT_V4_HOST_OPTION, // Insert DHCPv4 option
2091  INSERT_V6_HOST_OPTION, // Insert DHCPv6 option
2092  DEL_HOST_ADDR4, // Delete v4 host (subnet-id, addr4)
2093  DEL_HOST_ADDR6, // Delete v6 host (subnet-id, addr6)
2094  DEL_HOST_SUBID4_ID, // Delete v4 host (subnet-id, ident.type, identifier)
2095  DEL_HOST_SUBID6_ID, // Delete v6 host (subnet-id, ident.type, identifier)
2096  NUM_STATEMENTS // Number of statements
2097  };
2098 
2104  static const StatementIndex WRITE_STMTS_BEGIN = INSERT_HOST_NON_UNIQUE_IP;
2105 
2111 
2114 
2137  static bool dbReconnect(ReconnectCtlPtr db_reconnect_ctl);
2138 
2148  MySqlHostContextPtr createContext() const;
2149 
2161  std::pair<uint32_t, uint32_t> getVersion() const;
2162 
2171  void addStatement(MySqlHostContextPtr& ctx,
2173  std::vector<MYSQL_BIND>& bind);
2174 
2183  bool delStatement(MySqlHostContextPtr& ctx,
2184  StatementIndex stindex,
2185  MYSQL_BIND* bind);
2186 
2192  void addResv(MySqlHostContextPtr& ctx,
2193  const IPv6Resrv& resv,
2194  const HostID& id);
2195 
2205  void addOption(MySqlHostContextPtr& ctx,
2207  const OptionDescriptor& opt_desc,
2208  const std::string& opt_space,
2209  const Optional<SubnetID>& subnet_id,
2210  const HostID& host_id);
2211 
2219  void addOptions(MySqlHostContextPtr& ctx,
2220  const StatementIndex& stindex,
2221  const ConstCfgOptionPtr& options_cfg,
2222  const uint64_t host_id);
2223 
2235  void checkError(MySqlHostContextPtr& ctx,
2236  const int status,
2237  const StatementIndex index,
2238  const char* what) const;
2239 
2258  void getHostCollection(MySqlHostContextPtr& ctx,
2259  StatementIndex stindex,
2260  MYSQL_BIND* bind,
2261  boost::shared_ptr<MySqlHostExchange> exchange,
2262  ConstHostCollection& result,
2263  bool single) const;
2264 
2282  ConstHostPtr getHost(MySqlHostContextPtr& ctx,
2283  const SubnetID& subnet_id,
2284  const Host::IdentifierType& identifier_type,
2285  const uint8_t* identifier_begin,
2286  const size_t identifier_len,
2287  StatementIndex stindex,
2288  boost::shared_ptr<MySqlHostExchange> exchange) const;
2289 
2299  void checkReadOnly(MySqlHostContextPtr& ctx) const;
2300 
2303 
2307 
2310 
2314 
2316  std::string timer_name_;
2317 };
2318 
2319 namespace {
2320 
2322 typedef boost::array<TaggedStatement, MySqlHostDataSourceImpl::NUM_STATEMENTS>
2323 TaggedStatementArray;
2324 
2327 TaggedStatementArray tagged_statements = { {
2328  // Retrieves host information, IPv6 reservations and both DHCPv4 and
2329  // DHCPv6 options associated with the host. The LEFT JOIN clause is used
2330  // to retrieve information from 4 different tables using a single query.
2331  // Hence, this query returns multiple rows for a single host.
2332  {MySqlHostDataSourceImpl::GET_HOST_DHCPID,
2333  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2334  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, "
2335  "h.hostname, h.dhcp4_client_classes, h.dhcp6_client_classes, "
2336  "h.user_context, "
2337  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2338  "h.dhcp4_boot_file_name, h.auth_key, "
2339  "o4.option_id, o4.code, o4.value, o4.formatted_value, o4.space, "
2340  "o4.persistent, o4.cancelled, o4.user_context, "
2341  "o6.option_id, o6.code, o6.value, o6.formatted_value, o6.space, "
2342  "o6.persistent, o6.cancelled, o6.user_context, "
2343  "r.reservation_id, r.address, r.prefix_len, r.type, "
2344  "r.dhcp6_iaid "
2345  "FROM hosts AS h "
2346  "LEFT JOIN dhcp4_options AS o4 "
2347  "ON h.host_id = o4.host_id "
2348  "LEFT JOIN dhcp6_options AS o6 "
2349  "ON h.host_id = o6.host_id "
2350  "LEFT JOIN ipv6_reservations AS r "
2351  "ON h.host_id = r.host_id "
2352  "WHERE dhcp_identifier = ? AND dhcp_identifier_type = ? "
2353  "ORDER BY h.host_id, o4.option_id, o6.option_id, r.reservation_id"},
2354 
2355  // Retrieves host information along with the DHCPv4 options associated with
2356  // it. Left joining the dhcp4_options table results in multiple rows being
2357  // returned for the same host. The host is retrieved by IPv4 address.
2358  {MySqlHostDataSourceImpl::GET_HOST_ADDR,
2359  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2360  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2361  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2362  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2363  "h.dhcp4_boot_file_name, h.auth_key, "
2364  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2365  "o.persistent, o.cancelled, o.user_context "
2366  "FROM hosts AS h "
2367  "LEFT JOIN dhcp4_options AS o "
2368  "ON h.host_id = o.host_id "
2369  "WHERE ipv4_address = ? "
2370  "ORDER BY h.host_id, o.option_id"},
2371 
2372  // Retrieves host information and DHCPv4 options using subnet identifier
2373  // and client's identifier. Left joining the dhcp4_options table results in
2374  // multiple rows being returned for the same host.
2375  {MySqlHostDataSourceImpl::GET_HOST_SUBID4_DHCPID,
2376  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2377  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2378  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2379  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2380  "h.dhcp4_boot_file_name, h.auth_key, "
2381  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2382  "o.persistent, o.cancelled, o.user_context "
2383  "FROM hosts AS h "
2384  "LEFT JOIN dhcp4_options AS o "
2385  "ON h.host_id = o.host_id "
2386  "WHERE h.dhcp4_subnet_id = ? AND h.dhcp_identifier_type = ? "
2387  "AND h.dhcp_identifier = ? "
2388  "ORDER BY h.host_id, o.option_id"},
2389 
2390  // Retrieves host information, IPv6 reservations and DHCPv6 options
2391  // associated with a host. The number of rows returned is a multiplication
2392  // of number of IPv6 reservations and DHCPv6 options.
2393  {MySqlHostDataSourceImpl::GET_HOST_SUBID6_DHCPID,
2394  "SELECT h.host_id, h.dhcp_identifier, "
2395  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2396  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2397  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2398  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2399  "h.dhcp4_boot_file_name, h.auth_key, "
2400  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2401  "o.persistent, o.cancelled, o.user_context, "
2402  "r.reservation_id, r.address, r.prefix_len, r.type, "
2403  "r.dhcp6_iaid "
2404  "FROM hosts AS h "
2405  "LEFT JOIN dhcp6_options AS o "
2406  "ON h.host_id = o.host_id "
2407  "LEFT JOIN ipv6_reservations AS r "
2408  "ON h.host_id = r.host_id "
2409  "WHERE h.dhcp6_subnet_id = ? AND h.dhcp_identifier_type = ? "
2410  "AND h.dhcp_identifier = ? "
2411  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2412 
2413  // Retrieves host information and DHCPv4 options for the host using subnet
2414  // identifier and IPv4 reservation. Left joining the dhcp4_options table
2415  // results in multiple rows being returned for the host. The number of
2416  // rows depends on the number of options defined for the host.
2417  {MySqlHostDataSourceImpl::GET_HOST_SUBID_ADDR,
2418  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2419  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2420  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2421  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2422  "h.dhcp4_boot_file_name, h.auth_key, "
2423  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2424  "o.persistent, o.cancelled, o.user_context "
2425  "FROM hosts AS h "
2426  "LEFT JOIN dhcp4_options AS o "
2427  "ON h.host_id = o.host_id "
2428  "WHERE h.dhcp4_subnet_id = ? AND h.ipv4_address = ? "
2429  "ORDER BY h.host_id, o.option_id"},
2430 
2431  // Retrieves host information, IPv6 reservations and DHCPv6 options
2432  // associated with a host using prefix and prefix length. This query
2433  // returns host information for a single host. However, multiple rows
2434  // are returned due to left joining IPv6 reservations and DHCPv6 options.
2435  // The number of rows returned is multiplication of number of existing
2436  // IPv6 reservations and DHCPv6 options.
2437  {MySqlHostDataSourceImpl::GET_HOST_PREFIX,
2438  "SELECT h.host_id, h.dhcp_identifier, "
2439  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2440  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2441  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2442  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2443  "h.dhcp4_boot_file_name, h.auth_key, "
2444  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2445  "o.persistent, o.cancelled, o.user_context,"
2446  "r.reservation_id, r.address, r.prefix_len, r.type, "
2447  "r.dhcp6_iaid "
2448  "FROM hosts AS h "
2449  "LEFT JOIN dhcp6_options AS o "
2450  "ON h.host_id = o.host_id "
2451  "LEFT JOIN ipv6_reservations AS r "
2452  "ON h.host_id = r.host_id "
2453  "WHERE h.host_id = "
2454  "( SELECT host_id FROM ipv6_reservations "
2455  "WHERE address = ? AND prefix_len = ? ) "
2456  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2457 
2458  // Retrieves host information, IPv6 reservations and DHCPv6 options
2459  // associated with a host using IPv6 subnet id and prefix. This query
2460  // returns host information for a single host. However, multiple rows
2461  // are returned due to left joining IPv6 reservations and DHCPv6 options.
2462  // The number of rows returned is multiplication of number of existing
2463  // IPv6 reservations and DHCPv6 options.
2464  {MySqlHostDataSourceImpl::GET_HOST_SUBID6_ADDR,
2465  "SELECT h.host_id, h.dhcp_identifier, "
2466  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2467  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2468  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2469  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2470  "h.dhcp4_boot_file_name, h.auth_key, "
2471  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2472  "o.persistent, o.cancelled, o.user_context, "
2473  "r.reservation_id, r.address, r.prefix_len, r.type, "
2474  "r.dhcp6_iaid "
2475  "FROM hosts AS h "
2476  "LEFT JOIN dhcp6_options AS o "
2477  "ON h.host_id = o.host_id "
2478  "LEFT JOIN ipv6_reservations AS r "
2479  "ON h.host_id = r.host_id "
2480  "WHERE h.dhcp6_subnet_id = ? AND r.address = ? "
2481  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2482 
2483  // Retrieves host information along with the DHCPv4 options associated with
2484  // it. Left joining the dhcp4_options table results in multiple rows being
2485  // returned for the same host. Hosts are retrieved by IPv4 subnet id.
2486  {MySqlHostDataSourceImpl::GET_HOST_SUBID4,
2487  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2488  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2489  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2490  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2491  "h.dhcp4_boot_file_name, h.auth_key, "
2492  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2493  "o.persistent, o.cancelled, o.user_context "
2494  "FROM hosts AS h "
2495  "LEFT JOIN dhcp4_options AS o "
2496  "ON h.host_id = o.host_id "
2497  "WHERE h.dhcp4_subnet_id = ? "
2498  "ORDER BY h.host_id, o.option_id"},
2499 
2500  // Retrieves host information, IPv6 reservations and DHCPv6 options
2501  // associated with a host. The number of rows returned is a multiplication
2502  // of number of IPv6 reservations and DHCPv6 options. Hosts are retrieved
2503  // by IPv6 subnet id.
2504  {MySqlHostDataSourceImpl::GET_HOST_SUBID6,
2505  "SELECT h.host_id, h.dhcp_identifier, "
2506  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2507  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2508  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2509  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2510  "h.dhcp4_boot_file_name, h.auth_key, "
2511  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2512  "o.persistent, o.cancelled, o.user_context, "
2513  "r.reservation_id, r.address, r.prefix_len, r.type, "
2514  "r.dhcp6_iaid "
2515  "FROM hosts AS h "
2516  "LEFT JOIN dhcp6_options AS o "
2517  "ON h.host_id = o.host_id "
2518  "LEFT JOIN ipv6_reservations AS r "
2519  "ON h.host_id = r.host_id "
2520  "WHERE h.dhcp6_subnet_id = ? "
2521  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2522 
2523  // Retrieves host information, IPv6 reservations and both DHCPv4 and
2524  // DHCPv6 options associated with the host. The LEFT JOIN clause is used
2525  // to retrieve information from 4 different tables using a single query.
2526  // Hence, this query returns multiple rows for a single host.
2527  {MySqlHostDataSourceImpl::GET_HOST_HOSTNAME,
2528  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2529  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, "
2530  "h.hostname, h.dhcp4_client_classes, h.dhcp6_client_classes, "
2531  "h.user_context, "
2532  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2533  "h.dhcp4_boot_file_name, h.auth_key, "
2534  "o4.option_id, o4.code, o4.value, o4.formatted_value, o4.space, "
2535  "o4.persistent, o4.cancelled, o4.user_context, "
2536  "o6.option_id, o6.code, o6.value, o6.formatted_value, o6.space, "
2537  "o6.persistent, o6.cancelled, o6.user_context, "
2538  "r.reservation_id, r.address, r.prefix_len, r.type, "
2539  "r.dhcp6_iaid "
2540  "FROM hosts AS h "
2541  "LEFT JOIN dhcp4_options AS o4 "
2542  "ON h.host_id = o4.host_id "
2543  "LEFT JOIN dhcp6_options AS o6 "
2544  "ON h.host_id = o6.host_id "
2545  "LEFT JOIN ipv6_reservations AS r "
2546  "ON h.host_id = r.host_id "
2547  "WHERE h.hostname = ? "
2548  "ORDER BY h.host_id, o4.option_id, o6.option_id, r.reservation_id"},
2549 
2550  // Retrieves host information and DHCPv4 options using hostname and
2551  // subnet identifier. Left joining the dhcp4_options table results in
2552  // multiple rows being returned for the same host.
2553  {MySqlHostDataSourceImpl::GET_HOST_HOSTNAME_SUBID4,
2554  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2555  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2556  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2557  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2558  "h.dhcp4_boot_file_name, h.auth_key, "
2559  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2560  "o.persistent, o.cancelled, o.user_context "
2561  "FROM hosts AS h "
2562  "LEFT JOIN dhcp4_options AS o "
2563  "ON h.host_id = o.host_id "
2564  "WHERE h.hostname = ? AND h.dhcp4_subnet_id = ? "
2565  "ORDER BY h.host_id, o.option_id"},
2566 
2567  // Retrieves host information, IPv6 reservations and DHCPv6 options
2568  // using hostname and subnet identifier. The number of rows returned
2569  // is a multiplication of number of IPv6 reservations and DHCPv6 options.
2570  {MySqlHostDataSourceImpl::GET_HOST_HOSTNAME_SUBID6,
2571  "SELECT h.host_id, h.dhcp_identifier, "
2572  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2573  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2574  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2575  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2576  "h.dhcp4_boot_file_name, h.auth_key, "
2577  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2578  "o.persistent, o.cancelled, o.user_context, "
2579  "r.reservation_id, r.address, r.prefix_len, r.type, "
2580  "r.dhcp6_iaid "
2581  "FROM hosts AS h "
2582  "LEFT JOIN dhcp6_options AS o "
2583  "ON h.host_id = o.host_id "
2584  "LEFT JOIN ipv6_reservations AS r "
2585  "ON h.host_id = r.host_id "
2586  "WHERE h.hostname = ? AND h.dhcp6_subnet_id = ? "
2587  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2588 
2589  // Retrieves host information along with the DHCPv4 options associated with
2590  // it. Left joining the dhcp4_options table results in multiple rows being
2591  // returned for the same host. Hosts are retrieved by IPv4 subnet id
2592  // and with a host id greater than the start one.
2593  // The number of hosts returned is lower or equal to the limit.
2594  {MySqlHostDataSourceImpl::GET_HOST_SUBID4_PAGE,
2595  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2596  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2597  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2598  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2599  "h.dhcp4_boot_file_name, h.auth_key, "
2600  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2601  "o.persistent, o.cancelled, o.user_context "
2602  "FROM ( SELECT * FROM hosts AS h "
2603  "WHERE h.dhcp4_subnet_id = ? AND h.host_id > ? "
2604  "ORDER BY h.host_id "
2605  "LIMIT ? ) AS h "
2606  "LEFT JOIN dhcp4_options AS o "
2607  "ON h.host_id = o.host_id "
2608  "ORDER BY h.host_id, o.option_id"},
2609 
2610  // Retrieves host information, IPv6 reservations and DHCPv6 options
2611  // associated with a host. The number of rows returned is a multiplication
2612  // of number of IPv6 reservations and DHCPv6 options. Hosts are retrieved
2613  // by IPv6 subnet id and with a host id greater than the start one.
2614  // The number of hosts returned is lower or equal to the limit.
2615  {MySqlHostDataSourceImpl::GET_HOST_SUBID6_PAGE,
2616  "SELECT h.host_id, h.dhcp_identifier, "
2617  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2618  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2619  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2620  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2621  "h.dhcp4_boot_file_name, h.auth_key, "
2622  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2623  "o.persistent, o.cancelled, o.user_context, "
2624  "r.reservation_id, r.address, r.prefix_len, r.type, "
2625  "r.dhcp6_iaid "
2626  "FROM ( SELECT * FROM hosts AS h "
2627  "WHERE h.dhcp6_subnet_id = ? AND h.host_id > ? "
2628  "ORDER BY h.host_id "
2629  "LIMIT ? ) AS h "
2630  "LEFT JOIN dhcp6_options AS o "
2631  "ON h.host_id = o.host_id "
2632  "LEFT JOIN ipv6_reservations AS r "
2633  "ON h.host_id = r.host_id "
2634  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2635 
2636  // Retrieves host information along with the DHCPv4 options associated with
2637  // it. Left joining the dhcp4_options table results in multiple rows being
2638  // returned for the same host. Hosts are retrieved with a host id greater
2639  // than the start one.
2640  // The number of hosts returned is lower or equal to the limit.
2641  {MySqlHostDataSourceImpl::GET_HOST_PAGE4,
2642  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2643  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2644  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2645  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2646  "h.dhcp4_boot_file_name, h.auth_key, "
2647  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2648  "o.persistent, o.cancelled, o.user_context "
2649  "FROM ( SELECT * FROM hosts AS h "
2650  "WHERE h.host_id > ? "
2651  "ORDER BY h.host_id "
2652  "LIMIT ? ) AS h "
2653  "LEFT JOIN dhcp4_options AS o "
2654  "ON h.host_id = o.host_id "
2655  "ORDER BY h.host_id, o.option_id"},
2656 
2657  // Retrieves host information, IPv6 reservations and DHCPv6 options
2658  // associated with a host. The number of rows returned is a multiplication
2659  // of number of IPv6 reservations and DHCPv6 options. Hosts are retrieved
2660  // with a host id greater than the start one.
2661  // The number of hosts returned is lower or equal to the limit.
2662  {MySqlHostDataSourceImpl::GET_HOST_PAGE6,
2663  "SELECT h.host_id, h.dhcp_identifier, "
2664  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2665  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2666  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2667  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2668  "h.dhcp4_boot_file_name, h.auth_key, "
2669  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2670  "o.persistent, o.cancelled, o.user_context, "
2671  "r.reservation_id, r.address, r.prefix_len, r.type, "
2672  "r.dhcp6_iaid "
2673  "FROM ( SELECT * FROM hosts AS h "
2674  "WHERE h.host_id > ? "
2675  "ORDER BY h.host_id "
2676  "LIMIT ? ) AS h "
2677  "LEFT JOIN dhcp6_options AS o "
2678  "ON h.host_id = o.host_id "
2679  "LEFT JOIN ipv6_reservations AS r "
2680  "ON h.host_id = r.host_id "
2681  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2682 
2683  // Inserts a host into the 'hosts' table without checking that there is
2684  // a reservation for the IP address.
2685  {MySqlHostDataSourceImpl::INSERT_HOST_NON_UNIQUE_IP,
2686  "INSERT INTO hosts(host_id, dhcp_identifier, dhcp_identifier_type, "
2687  "dhcp4_subnet_id, dhcp6_subnet_id, ipv4_address, hostname, "
2688  "dhcp4_client_classes, dhcp6_client_classes, "
2689  "user_context, dhcp4_next_server, "
2690  "dhcp4_server_hostname, dhcp4_boot_file_name, auth_key) "
2691  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"},
2692 
2693  // Inserts a host into the 'hosts' table with checking that reserved IP
2694  // address is unique. The innermost query checks if there is at least
2695  // one host for the given IP/subnet combination. For checking whether
2696  // hosts exists or not it doesn't matter if we select actual columns,
2697  // thus SELECT 1 was used as an optimization to avoid selecting data
2698  // that will be ignored anyway. If the host does not exist the new
2699  // host is inserted. DUAL is a special MySQL table from which we can
2700  // select the values to be inserted. If the host with the given IP
2701  // address already exists the new host won't be inserted. The caller
2702  // can check the number of affected rows to detect that there was
2703  // a duplicate host in the database.
2704  {MySqlHostDataSourceImpl::INSERT_HOST_UNIQUE_IP,
2705  "INSERT INTO hosts(host_id, dhcp_identifier, dhcp_identifier_type, "
2706  "dhcp4_subnet_id, dhcp6_subnet_id, ipv4_address, hostname, "
2707  "dhcp4_client_classes, dhcp6_client_classes, "
2708  "user_context, dhcp4_next_server, "
2709  "dhcp4_server_hostname, dhcp4_boot_file_name, auth_key) "
2710  "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? FROM DUAL "
2711  "WHERE NOT EXISTS ("
2712  "SELECT 1 FROM hosts "
2713  "WHERE ipv4_address = ? AND dhcp4_subnet_id = ? "
2714  "LIMIT 1"
2715  ")"},
2716 
2717  // Inserts a single IPv6 reservation into 'reservations' table without
2718  // checking that the inserted reservation is unique.
2719  {MySqlHostDataSourceImpl::INSERT_V6_RESRV_NON_UNIQUE,
2720  "INSERT INTO ipv6_reservations(address, prefix_len, type, "
2721  "dhcp6_iaid, host_id) "
2722  "VALUES (?, ?, ?, ?, ?)"},
2723 
2724  // Inserts a single IPv6 reservation into 'reservations' table with
2725  // checking that the inserted reservation is unique.
2726  {MySqlHostDataSourceImpl::INSERT_V6_RESRV_UNIQUE,
2727  "INSERT INTO ipv6_reservations(address, prefix_len, type, "
2728  "dhcp6_iaid, host_id) "
2729  "SELECT ?, ?, ?, ?, ? FROM DUAL "
2730  "WHERE NOT EXISTS ("
2731  "SELECT 1 FROM ipv6_reservations "
2732  "WHERE address = ? AND prefix_len = ? "
2733  "LIMIT 1"
2734  ")"},
2735 
2736  // Inserts a single DHCPv4 option into 'dhcp4_options' table.
2737  // Using fixed scope_id = 3, which associates an option with host.
2738  {MySqlHostDataSourceImpl::INSERT_V4_HOST_OPTION,
2739  "INSERT INTO dhcp4_options(option_id, code, value, formatted_value, space, "
2740  "persistent, cancelled, user_context, dhcp4_subnet_id, host_id, scope_id) "
2741  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 3)"},
2742 
2743  // Inserts a single DHCPv6 option into 'dhcp6_options' table.
2744  // Using fixed scope_id = 3, which associates an option with host.
2745  {MySqlHostDataSourceImpl::INSERT_V6_HOST_OPTION,
2746  "INSERT INTO dhcp6_options(option_id, code, value, formatted_value, space, "
2747  "persistent, cancelled, user_context, dhcp6_subnet_id, host_id, scope_id) "
2748  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 3)"},
2749 
2750  // Delete IPv4 reservations by subnet id and reserved address.
2751  {MySqlHostDataSourceImpl::DEL_HOST_ADDR4,
2752  "DELETE FROM hosts WHERE dhcp4_subnet_id = ? AND ipv4_address = ?"},
2753 
2754  // Delete IPv6 reservations by subnet id and reserved address/prefix.
2755  {MySqlHostDataSourceImpl::DEL_HOST_ADDR6,
2756  "DELETE h FROM hosts AS h "
2757  "INNER JOIN ipv6_reservations AS r "
2758  "ON h.host_id = r.host_id "
2759  "WHERE h.dhcp6_subnet_id = ? AND r.address = ?"},
2760 
2761  // Delete a single IPv4 reservation by subnet id and identifier.
2762  {MySqlHostDataSourceImpl::DEL_HOST_SUBID4_ID,
2763  "DELETE FROM hosts WHERE dhcp4_subnet_id = ? AND dhcp_identifier_type=? "
2764  "AND dhcp_identifier = ?"},
2765 
2766  // Delete a single IPv6 reservation by subnet id and identifier.
2767  {MySqlHostDataSourceImpl::DEL_HOST_SUBID6_ID,
2768  "DELETE FROM hosts WHERE dhcp6_subnet_id = ? AND dhcp_identifier_type=? "
2769  "AND dhcp_identifier = ?"}
2770  }
2771 };
2772 
2773 } // namespace
2774 
2775 // MySqlHostContext Constructor
2776 
2777 MySqlHostContext::MySqlHostContext(const DatabaseConnection::ParameterMap& parameters,
2778  IOServiceAccessorPtr io_service_accessor,
2779  db::DbCallback db_reconnect_callback)
2780  : conn_(parameters, io_service_accessor, db_reconnect_callback),
2781  is_readonly_(true) {
2782 }
2783 
2784 // MySqlHostContextAlloc Constructor and Destructor
2785 
2787  MySqlHostDataSourceImpl& mgr) : ctx_(), mgr_(mgr) {
2788 
2789  if (MultiThreadingMgr::instance().getMode()) {
2790  // multi-threaded
2791  {
2792  // we need to protect the whole pool_ operation, hence extra scope {}
2793  lock_guard<mutex> lock(mgr_.pool_->mutex_);
2794  if (!mgr_.pool_->pool_.empty()) {
2795  ctx_ = mgr_.pool_->pool_.back();
2796  mgr_.pool_->pool_.pop_back();
2797  }
2798  }
2799  if (!ctx_) {
2800  ctx_ = mgr_.createContext();
2801  }
2802  } else {
2803  // single-threaded
2804  if (mgr_.pool_->pool_.empty()) {
2805  isc_throw(Unexpected, "No available MySQL host context?!");
2806  }
2807  ctx_ = mgr_.pool_->pool_.back();
2808  }
2809 }
2810 
2812  if (MultiThreadingMgr::instance().getMode()) {
2813  // multi-threaded
2814  lock_guard<mutex> lock(mgr_.pool_->mutex_);
2815  mgr_.pool_->pool_.push_back(ctx_);
2816  if (ctx_->conn_.isUnusable()) {
2817  mgr_.unusable_ = true;
2818  }
2819  } else if (ctx_->conn_.isUnusable()) {
2820  mgr_.unusable_ = true;
2821  }
2822 }
2823 
2825  : parameters_(parameters), ip_reservations_unique_(true), unusable_(false),
2826  timer_name_("") {
2827 
2828  // Create unique timer name per instance.
2829  timer_name_ = "MySqlHostMgr[";
2830  timer_name_ += boost::lexical_cast<std::string>(reinterpret_cast<uint64_t>(this));
2831  timer_name_ += "]DbReconnectTimer";
2832 
2833  // Validate the schema version first.
2834  std::pair<uint32_t, uint32_t> code_version(MYSQL_SCHEMA_VERSION_MAJOR,
2836  std::pair<uint32_t, uint32_t> db_version = getVersion();
2837  if (code_version != db_version) {
2839  "MySQL schema version mismatch: need version: "
2840  << code_version.first << "." << code_version.second
2841  << " found version: " << db_version.first << "."
2842  << db_version.second);
2843  }
2844 
2845  // Create an initial context.
2846  pool_.reset(new MySqlHostContextPool());
2847  pool_->pool_.push_back(createContext());
2848 }
2849 
2850 // Create context.
2851 
2857 
2858  // Open the database.
2859  ctx->conn_.openDatabase();
2860 
2861  // Check if we have TLS when we required it.
2862  if (ctx->conn_.getTls()) {
2863  std::string cipher = ctx->conn_.getTlsCipher();
2864  if (cipher.empty()) {
2866  } else {
2869  .arg(cipher);
2870  }
2871  }
2872 
2873  // Prepare query statements. Those are will be only used to retrieve
2874  // information from the database, so they can be used even if the
2875  // database is read only for the current user.
2876  ctx->conn_.prepareStatements(tagged_statements.begin(),
2877  tagged_statements.begin() + WRITE_STMTS_BEGIN);
2878 
2879  // Check if the backend is explicitly configured to operate with
2880  // read only access to the database.
2881  ctx->is_readonly_ = ctx->conn_.configuredReadOnly();
2882 
2883  // If we are using read-write mode for the database we also prepare
2884  // statements for INSERTS etc.
2885  if (!ctx->is_readonly_) {
2886  // Prepare statements for writing to the database, e.g. INSERT.
2887  ctx->conn_.prepareStatements(tagged_statements.begin() + WRITE_STMTS_BEGIN,
2888  tagged_statements.end());
2889  } else {
2891  }
2892 
2893  // Create the exchange objects for use in exchanging data between the
2894  // program and the database.
2895  ctx->host_ipv4_exchange_.reset(new MySqlHostWithOptionsExchange(MySqlHostWithOptionsExchange::DHCP4_ONLY));
2896  ctx->host_ipv6_exchange_.reset(new MySqlHostIPv6Exchange(MySqlHostWithOptionsExchange::DHCP6_ONLY));
2897  ctx->host_ipv46_exchange_.reset(new MySqlHostIPv6Exchange(MySqlHostWithOptionsExchange::DHCP4_AND_DHCP6));
2898  ctx->host_ipv6_reservation_exchange_.reset(new MySqlIPv6ReservationExchange());
2899  ctx->host_option_exchange_.reset(new MySqlOptionExchange());
2900 
2901  // Create ReconnectCtl for this connection.
2902  ctx->conn_.makeReconnectCtl(timer_name_);
2903 
2904  return (ctx);
2905 }
2906 
2908 }
2909 
2910 bool
2913 
2914  // Invoke application layer connection lost callback.
2915  if (!DatabaseConnection::invokeDbLostCallback(db_reconnect_ctl)) {
2916  return (false);
2917  }
2918 
2919  bool reopened = false;
2920 
2921  const std::string timer_name = db_reconnect_ctl->timerName();
2922 
2923  // At least one connection was lost.
2924  try {
2925  CfgDbAccessPtr cfg_db = CfgMgr::instance().getCurrentCfg()->getCfgDbAccess();
2926  std::list<std::string> host_db_access_list = cfg_db->getHostDbAccessStringList();
2927  for (std::string& hds : host_db_access_list) {
2928  auto parameters = DatabaseConnection::parse(hds);
2929  if (HostMgr::delBackend("mysql", hds, true)) {
2930  HostMgr::addBackend(hds);
2931  }
2932  }
2933  reopened = true;
2934  } catch (const std::exception& ex) {
2936  .arg(ex.what());
2937  }
2938 
2939  if (reopened) {
2940  // Cancel the timer.
2941  if (TimerMgr::instance()->isTimerRegistered(timer_name)) {
2942  TimerMgr::instance()->unregisterTimer(timer_name);
2943  }
2944 
2945  // Invoke application layer connection recovered callback.
2946  if (!DatabaseConnection::invokeDbRecoveredCallback(db_reconnect_ctl)) {
2947  return (false);
2948  }
2949  } else {
2950  if (!db_reconnect_ctl->checkRetries()) {
2951  // We're out of retries, log it and initiate shutdown.
2953  .arg(db_reconnect_ctl->maxRetries());
2954 
2955  // Cancel the timer.
2956  if (TimerMgr::instance()->isTimerRegistered(timer_name)) {
2957  TimerMgr::instance()->unregisterTimer(timer_name);
2958  }
2959 
2960  // Invoke application layer connection failed callback.
2962  return (false);
2963  }
2964 
2966  .arg(db_reconnect_ctl->maxRetries() - db_reconnect_ctl->retriesLeft() + 1)
2967  .arg(db_reconnect_ctl->maxRetries())
2968  .arg(db_reconnect_ctl->retryInterval());
2969 
2970  // Start the timer.
2971  if (!TimerMgr::instance()->isTimerRegistered(timer_name)) {
2972  TimerMgr::instance()->registerTimer(timer_name,
2973  std::bind(&MySqlHostDataSourceImpl::dbReconnect, db_reconnect_ctl),
2974  db_reconnect_ctl->retryInterval(),
2976  }
2977  TimerMgr::instance()->setup(timer_name);
2978  }
2979 
2980  return (true);
2981 }
2982 
2983 std::pair<uint32_t, uint32_t>
2987 
2989 }
2990 
2991 void
2993  StatementIndex stindex,
2994  std::vector<MYSQL_BIND>& bind) {
2995  // Bind the parameters to the statement
2996  int status = mysql_stmt_bind_param(ctx->conn_.statements_[stindex], &bind[0]);
2997  checkError(ctx, status, stindex, "unable to bind parameters");
2998 
2999  // Execute the statement
3000  status = MysqlExecuteStatement(ctx->conn_.statements_[stindex]);
3001 
3002  if (status != 0) {
3003  // Failure: check for the special case of duplicate entry.
3004  if (mysql_errno(ctx->conn_.mysql_) == ER_DUP_ENTRY) {
3005  isc_throw(DuplicateEntry, "Database duplicate entry error");
3006  }
3007  checkError(ctx, status, stindex, "unable to execute");
3008  }
3009 
3010  // If the number of rows inserted is 0 it means that the query detected
3011  // an attempt to insert duplicated data for which there is no unique
3012  // index in the database. Unique indexes are not created in the database
3013  // when it may be sometimes allowed to insert duplicated records per
3014  // server's configuration.
3015  my_ulonglong numrows = mysql_stmt_affected_rows(ctx->conn_.statements_[stindex]);
3016  if (numrows == 0) {
3017  isc_throw(DuplicateEntry, "Database duplicate entry error");
3018  }
3019 }
3020 
3021 bool
3023  StatementIndex stindex,
3024  MYSQL_BIND* bind) {
3025  // Bind the parameters to the statement
3026  int status = mysql_stmt_bind_param(ctx->conn_.statements_[stindex], &bind[0]);
3027  checkError(ctx, status, stindex, "unable to bind parameters");
3028 
3029  // Execute the statement
3030  status = MysqlExecuteStatement(ctx->conn_.statements_[stindex]);
3031 
3032  if (status != 0) {
3033  checkError(ctx, status, stindex, "unable to execute");
3034  }
3035 
3036  // Let's check how many hosts were deleted.
3037  my_ulonglong numrows = mysql_stmt_affected_rows(ctx->conn_.statements_[stindex]);
3038 
3039  return (numrows != 0);
3040 }
3041 
3042 void
3044  const IPv6Resrv& resv,
3045  const HostID& id) {
3046  std::vector<MYSQL_BIND> bind = ctx->host_ipv6_reservation_exchange_->
3047  createBindForSend(resv, id, ip_reservations_unique_);
3048 
3050 }
3051 
3052 void
3054  const StatementIndex& stindex,
3055  const OptionDescriptor& opt_desc,
3056  const std::string& opt_space,
3057  const Optional<SubnetID>& subnet_id,
3058  const HostID& id) {
3059  std::vector<MYSQL_BIND> bind = ctx->host_option_exchange_->createBindForSend(opt_desc, opt_space, subnet_id, id);
3060 
3061  addStatement(ctx, stindex, bind);
3062 }
3063 
3064 void
3066  const StatementIndex& stindex,
3067  const ConstCfgOptionPtr& options_cfg,
3068  const uint64_t host_id) {
3069  // Get option space names and vendor space names and combine them within a
3070  // single list.
3071  std::list<std::string> option_spaces = options_cfg->getOptionSpaceNames();
3072  std::list<std::string> vendor_spaces = options_cfg->getVendorIdsSpaceNames();
3073  option_spaces.insert(option_spaces.end(), vendor_spaces.begin(),
3074  vendor_spaces.end());
3075 
3076  // For each option space retrieve all options and insert them into the
3077  // database.
3078  for (auto space = option_spaces.begin(); space != option_spaces.end(); ++space) {
3079  OptionContainerPtr options = options_cfg->getAll(*space);
3080  if (options && !options->empty()) {
3081  for (auto opt = options->begin(); opt != options->end(); ++opt) {
3082  addOption(ctx, stindex, *opt, *space, Optional<SubnetID>(), host_id);
3083  }
3084  }
3085  }
3086 }
3087 
3088 void
3090  const int status,
3091  const StatementIndex index,
3092  const char* what) const {
3093  ctx->conn_.checkError(status, index, what);
3094 }
3095 
3096 void
3098  StatementIndex stindex,
3099  MYSQL_BIND* bind,
3100  boost::shared_ptr<MySqlHostExchange> exchange,
3101  ConstHostCollection& result,
3102  bool single) const {
3103 
3104  // Bind the selection parameters to the statement
3105  int status = mysql_stmt_bind_param(ctx->conn_.statements_[stindex], bind);
3106  checkError(ctx, status, stindex, "unable to bind WHERE clause parameter");
3107 
3108  // Set up the MYSQL_BIND array for the data being returned and bind it to
3109  // the statement.
3110  std::vector<MYSQL_BIND> outbind = exchange->createBindForReceive();
3111  status = mysql_stmt_bind_result(ctx->conn_.statements_[stindex], &outbind[0]);
3112  checkError(ctx, status, stindex, "unable to bind SELECT clause parameters");
3113 
3114  // Execute the statement
3115  status = MysqlExecuteStatement(ctx->conn_.statements_[stindex]);
3116  checkError(ctx, status, stindex, "unable to execute");
3117 
3118  // Ensure that all the lease information is retrieved in one go to avoid
3119  // overhead of going back and forth between client and server.
3120  status = mysql_stmt_store_result(ctx->conn_.statements_[stindex]);
3121  checkError(ctx, status, stindex, "unable to set up for storing all results");
3122 
3123  // Set up the fetch "release" object to release resources associated
3124  // with the call to mysql_stmt_fetch when this method exits, then
3125  // retrieve the data. mysql_stmt_fetch return value equal to 0 represents
3126  // successful data fetch.
3127  MySqlFreeResult fetch_release(ctx->conn_.statements_[stindex]);
3128  while ((status = mysql_stmt_fetch(ctx->conn_.statements_[stindex])) ==
3130  try {
3131  exchange->processFetchedData(result);
3132 
3133  } catch (const isc::BadValue& ex) {
3134  // Rethrow the exception with a bit more data.
3135  isc_throw(BadValue, ex.what() << ". Statement is <" <<
3136  ctx->conn_.text_statements_[stindex] << ">");
3137  }
3138 
3139  if (single && (result.size() > 1)) {
3140  isc_throw(MultipleRecords, "multiple records were found in the "
3141  "database where only one was expected for query "
3142  << ctx->conn_.text_statements_[stindex]);
3143  }
3144  }
3145 
3146  // How did the fetch end?
3147  // If mysql_stmt_fetch return value is equal to 1 an error occurred.
3148  if (status == MLM_MYSQL_FETCH_FAILURE) {
3149  // Error - unable to fetch results
3150  checkError(ctx, status, stindex, "unable to fetch results");
3151 
3152  } else if (status == MYSQL_DATA_TRUNCATED) {
3153  // Data truncated - throw an exception indicating what was at fault
3154  isc_throw(DataTruncated, ctx->conn_.text_statements_[stindex]
3155  << " returned truncated data: columns affected are "
3156  << exchange->getErrorColumns());
3157  }
3158 }
3159 
3162  const SubnetID& subnet_id,
3163  const Host::IdentifierType& identifier_type,
3164  const uint8_t* identifier_begin,
3165  const size_t identifier_len,
3166  StatementIndex stindex,
3167  boost::shared_ptr<MySqlHostExchange> exchange) const {
3168 
3169  // Set up the WHERE clause value
3170  MYSQL_BIND inbind[3];
3171  memset(inbind, 0, sizeof(inbind));
3172 
3173  uint32_t subnet_buffer = static_cast<uint32_t>(subnet_id);
3174  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3175  inbind[0].buffer = reinterpret_cast<char*>(&subnet_buffer);
3176  inbind[0].is_unsigned = MLM_TRUE;
3177 
3178  // Identifier value.
3179  std::vector<char> identifier_vec(identifier_begin,
3180  identifier_begin + identifier_len);
3181  unsigned long length = identifier_vec.size();
3182  inbind[2].buffer_type = MYSQL_TYPE_BLOB;
3183  inbind[2].buffer = &identifier_vec[0];
3184  inbind[2].buffer_length = length;
3185  inbind[2].length = &length;
3186 
3187  // Identifier type.
3188  char identifier_type_copy = static_cast<char>(identifier_type);
3189  inbind[1].buffer_type = MYSQL_TYPE_TINY;
3190  inbind[1].buffer = reinterpret_cast<char*>(&identifier_type_copy);
3191  inbind[1].is_unsigned = MLM_TRUE;
3192 
3193  ConstHostCollection collection;
3194  getHostCollection(ctx, stindex, inbind, exchange, collection, true);
3195 
3196  // Return single record if present, else clear the host.
3197  ConstHostPtr result;
3198  if (!collection.empty()) {
3199  result = *collection.begin();
3200  }
3201 
3202  return (result);
3203 }
3204 
3205 void
3207  if (ctx->is_readonly_) {
3208  isc_throw(ReadOnlyDb, "MySQL host database backend is configured to"
3209  " operate in read only mode");
3210  }
3211 }
3212 
3214  : impl_(new MySqlHostDataSourceImpl(parameters)) {
3215 }
3216 
3218 }
3219 
3222  return (impl_->parameters_);
3223 }
3224 
3225 void
3227  // Get a context
3228  MySqlHostContextAlloc get_context(*impl_);
3229  MySqlHostContextPtr ctx = get_context.ctx_;
3230 
3231  // If operating in read-only mode, throw exception.
3232  impl_->checkReadOnly(ctx);
3233 
3234  // Initiate MySQL transaction as we will have to make multiple queries
3235  // to insert host information into multiple tables. If that fails on
3236  // any stage, the transaction will be rolled back by the destructor of
3237  // the MySqlTransaction class.
3238  MySqlTransaction transaction(ctx->conn_);
3239 
3240  // If we're configured to check that an IP reservation within a given subnet
3241  // is unique, the IP reservation exists and the subnet is actually set
3242  // we will be using a special query that checks for uniqueness. Otherwise,
3243  // we will use a regular insert statement.
3244  bool unique_ip = impl_->ip_reservations_unique_ && !host->getIPv4Reservation().isV4Zero()
3245  && host->getIPv4SubnetID() != SUBNET_ID_UNUSED;
3246 
3247  // Create the MYSQL_BIND array for the host
3248  std::vector<MYSQL_BIND> bind = ctx->host_ipv4_exchange_->createBindForSend(host, unique_ip);
3249 
3250  // ... and insert the host.
3251  impl_->addStatement(ctx, unique_ip ? MySqlHostDataSourceImpl::INSERT_HOST_UNIQUE_IP :
3253 
3254  // Gets the last inserted hosts id
3255  uint64_t host_id = mysql_insert_id(ctx->conn_.mysql_);
3256 
3257  // Insert DHCPv4 options.
3258  ConstCfgOptionPtr cfg_option4 = host->getCfgOption4();
3259  if (cfg_option4) {
3260  impl_->addOptions(ctx, MySqlHostDataSourceImpl::INSERT_V4_HOST_OPTION,
3261  cfg_option4, host_id);
3262  }
3263 
3264  // Insert DHCPv6 options.
3265  ConstCfgOptionPtr cfg_option6 = host->getCfgOption6();
3266  if (cfg_option6) {
3267  impl_->addOptions(ctx, MySqlHostDataSourceImpl::INSERT_V6_HOST_OPTION,
3268  cfg_option6, host_id);
3269  }
3270 
3271  // Insert IPv6 reservations.
3272  IPv6ResrvRange v6resv = host->getIPv6Reservations();
3273  if (std::distance(v6resv.first, v6resv.second) > 0) {
3274  for (IPv6ResrvIterator resv = v6resv.first; resv != v6resv.second;
3275  ++resv) {
3276  impl_->addResv(ctx, resv->second, host_id);
3277  }
3278  }
3279 
3280  // Everything went fine, so explicitly commit the transaction.
3281  transaction.commit();
3282 }
3283 
3284 bool
3286  const asiolink::IOAddress& addr) {
3287  // Get a context
3288  MySqlHostContextAlloc get_context(*impl_);
3289  MySqlHostContextPtr ctx = get_context.ctx_;
3290 
3291  // If operating in read-only mode, throw exception.
3292  impl_->checkReadOnly(ctx);
3293 
3294  // Set up the WHERE clause value
3295  MYSQL_BIND inbind[2];
3296 
3297  uint32_t subnet = subnet_id;
3298  memset(inbind, 0, sizeof(inbind));
3299  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3300  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3301  inbind[0].is_unsigned = MLM_TRUE;
3302 
3303  // v4
3304  if (addr.isV4()) {
3305  uint32_t addr4 = addr.toUint32();
3306  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3307  inbind[1].buffer = reinterpret_cast<char*>(&addr4);
3308  inbind[1].is_unsigned = MLM_TRUE;
3309 
3310  return (impl_->delStatement(ctx, MySqlHostDataSourceImpl::DEL_HOST_ADDR4, inbind));
3311  }
3312 
3313  // v6
3314  std::string addr_str = addr.toText();
3315  unsigned long addr_len = addr_str.size();
3316  inbind[1].buffer_type = MYSQL_TYPE_BLOB;
3317  inbind[1].buffer = reinterpret_cast<char*>
3318  (const_cast<char*>(addr_str.c_str()));
3319  inbind[1].length = &addr_len;
3320  inbind[1].buffer_length = addr_len;
3321 
3322  return (impl_->delStatement(ctx, MySqlHostDataSourceImpl::DEL_HOST_ADDR6, inbind));
3323 }
3324 
3325 bool
3327  const Host::IdentifierType& identifier_type,
3328  const uint8_t* identifier_begin,
3329  const size_t identifier_len) {
3330  // Get a context
3331  MySqlHostContextAlloc get_context(*impl_);
3332  MySqlHostContextPtr ctx = get_context.ctx_;
3333 
3334  // If operating in read-only mode, throw exception.
3335  impl_->checkReadOnly(ctx);
3336 
3337  // Set up the WHERE clause value
3338  MYSQL_BIND inbind[3];
3339 
3340  // subnet-id
3341  memset(inbind, 0, sizeof(inbind));
3342  uint32_t subnet = static_cast<uint32_t>(subnet_id);
3343  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3344  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3345  inbind[0].is_unsigned = MLM_TRUE;
3346 
3347  // identifier type
3348  char identifier_type_copy = static_cast<char>(identifier_type);
3349  inbind[1].buffer_type = MYSQL_TYPE_TINY;
3350  inbind[1].buffer = reinterpret_cast<char*>(&identifier_type_copy);
3351  inbind[1].is_unsigned = MLM_TRUE;
3352 
3353  // identifier value
3354  std::vector<char> identifier_vec(identifier_begin,
3355  identifier_begin + identifier_len);
3356  unsigned long length = identifier_vec.size();
3357  inbind[2].buffer_type = MYSQL_TYPE_BLOB;
3358  inbind[2].buffer = &identifier_vec[0];
3359  inbind[2].buffer_length = length;
3360  inbind[2].length = &length;
3361 
3362  ConstHostCollection collection;
3363  return (impl_->delStatement(ctx, MySqlHostDataSourceImpl::DEL_HOST_SUBID4_ID, inbind));
3364 }
3365 
3366 bool
3368  const Host::IdentifierType& identifier_type,
3369  const uint8_t* identifier_begin,
3370  const size_t identifier_len) {
3371  // Get a context
3372  MySqlHostContextAlloc get_context(*impl_);
3373  MySqlHostContextPtr ctx = get_context.ctx_;
3374 
3375  // If operating in read-only mode, throw exception.
3376  impl_->checkReadOnly(ctx);
3377 
3378  // Set up the WHERE clause value
3379  MYSQL_BIND inbind[3];
3380 
3381  // subnet-id
3382  memset(inbind, 0, sizeof(inbind));
3383  uint32_t subnet = static_cast<uint32_t>(subnet_id);
3384  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3385  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3386  inbind[0].is_unsigned = MLM_TRUE;
3387 
3388  // identifier type
3389  char identifier_type_copy = static_cast<char>(identifier_type);
3390  inbind[1].buffer_type = MYSQL_TYPE_TINY;
3391  inbind[1].buffer = reinterpret_cast<char*>(&identifier_type_copy);
3392  inbind[1].is_unsigned = MLM_TRUE;
3393 
3394  // identifier value
3395  std::vector<char> identifier_vec(identifier_begin,
3396  identifier_begin + identifier_len);
3397  unsigned long length = identifier_vec.size();
3398  inbind[2].buffer_type = MYSQL_TYPE_BLOB;
3399  inbind[2].buffer = &identifier_vec[0];
3400  inbind[2].buffer_length = length;
3401  inbind[2].length = &length;
3402 
3403  ConstHostCollection collection;
3404  return (impl_->delStatement(ctx, MySqlHostDataSourceImpl::DEL_HOST_SUBID6_ID, inbind));
3405 }
3406 
3409  const uint8_t* identifier_begin,
3410  const size_t identifier_len) const {
3411  // Get a context
3412  MySqlHostContextAlloc get_context(*impl_);
3413  MySqlHostContextPtr ctx = get_context.ctx_;
3414 
3415  // Set up the WHERE clause value
3416  MYSQL_BIND inbind[2];
3417  memset(inbind, 0, sizeof(inbind));
3418 
3419  // Identifier type.
3420  char identifier_type_copy = static_cast<char>(identifier_type);
3421  inbind[1].buffer = &identifier_type_copy;
3422  inbind[1].buffer_type = MYSQL_TYPE_TINY;
3423  inbind[1].is_unsigned = MLM_TRUE;
3424 
3425  // Identifier value.
3426  std::vector<char> identifier_vec(identifier_begin,
3427  identifier_begin + identifier_len);
3428  unsigned long int length = identifier_vec.size();
3429  inbind[0].buffer_type = MYSQL_TYPE_BLOB;
3430  inbind[0].buffer = &identifier_vec[0];
3431  inbind[0].buffer_length = length;
3432  inbind[0].length = &length;
3433 
3434  ConstHostCollection result;
3435  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_DHCPID, inbind,
3436  ctx->host_ipv46_exchange_, result, false);
3437 
3438  return (result);
3439 }
3440 
3442 MySqlHostDataSource::getAll4(const SubnetID& subnet_id) const {
3443  // Get a context
3444  MySqlHostContextAlloc get_context(*impl_);
3445  MySqlHostContextPtr ctx = get_context.ctx_;
3446 
3447  // Set up the WHERE clause value
3448  MYSQL_BIND inbind[1];
3449  memset(inbind, 0, sizeof(inbind));
3450  uint32_t subnet = subnet_id;
3451  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3452  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3453  inbind[0].is_unsigned = MLM_TRUE;
3454 
3455  ConstHostCollection result;
3456  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID4, inbind,
3457  ctx->host_ipv4_exchange_, result, false);
3458 
3459  return (result);
3460 }
3461 
3463 MySqlHostDataSource::getAll6(const SubnetID& subnet_id) const {
3464  // Get a context
3465  MySqlHostContextAlloc get_context(*impl_);
3466  MySqlHostContextPtr ctx = get_context.ctx_;
3467 
3468  // Set up the WHERE clause value
3469  MYSQL_BIND inbind[1];
3470  memset(inbind, 0, sizeof(inbind));
3471  uint32_t subnet = subnet_id;
3472  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3473  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3474  inbind[0].is_unsigned = MLM_TRUE;
3475 
3476  ConstHostCollection result;
3477  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID6, inbind,
3478  ctx->host_ipv6_exchange_, result, false);
3479 
3480  return (result);
3481 }
3482 
3484 MySqlHostDataSource::getAllbyHostname(const std::string& hostname) const {
3485  // Get a context
3486  MySqlHostContextAlloc get_context(*impl_);
3487  MySqlHostContextPtr ctx = get_context.ctx_;
3488 
3489  // Set up the WHERE clause value
3490  MYSQL_BIND inbind[1];
3491  memset(inbind, 0, sizeof(inbind));
3492 
3493  // Hostname
3494  char hostname_[HOSTNAME_MAX_LEN];
3495  strncpy(hostname_, hostname.c_str(), HOSTNAME_MAX_LEN - 1);
3496  unsigned long length = hostname.length();
3497  inbind[0].buffer_type = MYSQL_TYPE_STRING;
3498  inbind[0].buffer = reinterpret_cast<char*>(hostname_);
3499  inbind[0].buffer_length = length;
3500  inbind[0].length = &length;
3501 
3502  ConstHostCollection result;
3503  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_HOSTNAME, inbind,
3504  ctx->host_ipv46_exchange_, result, false);
3505 
3506  return (result);
3507 }
3508 
3510 MySqlHostDataSource::getAllbyHostname4(const std::string& hostname,
3511  const SubnetID& subnet_id) const {
3512  // Get a context
3513  MySqlHostContextAlloc get_context(*impl_);
3514  MySqlHostContextPtr ctx = get_context.ctx_;
3515 
3516  // Set up the WHERE clause value
3517  MYSQL_BIND inbind[2];
3518  memset(inbind, 0, sizeof(inbind));
3519 
3520  // Hostname
3521  char hostname_[HOSTNAME_MAX_LEN];
3522  strncpy(hostname_, hostname.c_str(), HOSTNAME_MAX_LEN - 1);
3523  unsigned long length = hostname.length();
3524  inbind[0].buffer_type = MYSQL_TYPE_STRING;
3525  inbind[0].buffer = reinterpret_cast<char*>(hostname_);
3526  inbind[0].buffer_length = length;
3527  inbind[0].length = &length;
3528 
3529  // Subnet ID
3530  uint32_t subnet = subnet_id;
3531  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3532  inbind[1].buffer = reinterpret_cast<char*>(&subnet);
3533  inbind[1].is_unsigned = MLM_TRUE;
3534 
3535  ConstHostCollection result;
3536  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_HOSTNAME_SUBID4, inbind,
3537  ctx->host_ipv4_exchange_, result, false);
3538 
3539  return (result);
3540 }
3541 
3543 MySqlHostDataSource::getAllbyHostname6(const std::string& hostname,
3544  const SubnetID& subnet_id) const {
3545  // Get a context
3546  MySqlHostContextAlloc get_context(*impl_);
3547  MySqlHostContextPtr ctx = get_context.ctx_;
3548 
3549  // Set up the WHERE clause value
3550  MYSQL_BIND inbind[2];
3551  memset(inbind, 0, sizeof(inbind));
3552 
3553  // Hostname
3554  char hostname_[HOSTNAME_MAX_LEN];
3555  strncpy(hostname_, hostname.c_str(), HOSTNAME_MAX_LEN - 1);
3556  unsigned long length = hostname.length();
3557  inbind[0].buffer_type = MYSQL_TYPE_STRING;
3558  inbind[0].buffer = reinterpret_cast<char*>(hostname_);
3559  inbind[0].buffer_length = length;
3560  inbind[0].length = &length;
3561 
3562  // Subnet ID
3563  uint32_t subnet = subnet_id;
3564  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3565  inbind[1].buffer = reinterpret_cast<char*>(&subnet);
3566  inbind[1].is_unsigned = MLM_TRUE;
3567 
3568  ConstHostCollection result;
3569  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_HOSTNAME_SUBID6, inbind,
3570  ctx->host_ipv6_exchange_, result, false);
3571 
3572  return (result);
3573 }
3574 
3577  size_t& /*source_index*/,
3578  uint64_t lower_host_id,
3579  const HostPageSize& page_size) const {
3580  // Get a context
3581  MySqlHostContextAlloc get_context(*impl_);
3582  MySqlHostContextPtr ctx = get_context.ctx_;
3583 
3584  // Set up the WHERE clause value
3585  MYSQL_BIND inbind[3];
3586  memset(inbind, 0, sizeof(inbind));
3587 
3588  // Bind subnet id
3589  uint32_t subnet = subnet_id;
3590  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3591  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3592  inbind[0].is_unsigned = MLM_TRUE;
3593 
3594  // Bind lower host id
3595  uint32_t host_id = lower_host_id;
3596  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3597  inbind[1].buffer = reinterpret_cast<char*>(&host_id);
3598  inbind[1].is_unsigned = MLM_TRUE;
3599 
3600  // Bind page size value
3601  uint32_t page_size_data = page_size.page_size_;
3602  inbind[2].buffer_type = MYSQL_TYPE_LONG;
3603  inbind[2].buffer = reinterpret_cast<char*>(&page_size_data);
3604  inbind[2].is_unsigned = MLM_TRUE;
3605 
3606  ConstHostCollection result;
3607  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID4_PAGE, inbind,
3608  ctx->host_ipv4_exchange_, result, false);
3609 
3610  return (result);
3611 }
3612 
3615  size_t& /*source_index*/,
3616  uint64_t lower_host_id,
3617  const HostPageSize& page_size) const {
3618  // Get a context
3619  MySqlHostContextAlloc get_context(*impl_);
3620  MySqlHostContextPtr ctx = get_context.ctx_;
3621 
3622  // Set up the WHERE clause value
3623  MYSQL_BIND inbind[3];
3624  memset(inbind, 0, sizeof(inbind));
3625 
3626  // Bind subnet id
3627  uint32_t subnet = subnet_id;
3628  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3629  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3630  inbind[0].is_unsigned = MLM_TRUE;
3631 
3632  // Bind lower host id
3633  uint32_t host_id = lower_host_id;
3634  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3635  inbind[1].buffer = reinterpret_cast<char*>(&host_id);
3636  inbind[1].is_unsigned = MLM_TRUE;
3637 
3638  // Bind page size value
3639  uint32_t page_size_data = page_size.page_size_;
3640  inbind[2].buffer_type = MYSQL_TYPE_LONG;
3641  inbind[2].buffer = reinterpret_cast<char*>(&page_size_data);
3642  inbind[2].is_unsigned = MLM_TRUE;
3643 
3644  ConstHostCollection result;
3645  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID6_PAGE, inbind,
3646  ctx->host_ipv6_exchange_, result, false);
3647 
3648  return (result);
3649 }
3650 
3652 MySqlHostDataSource::getPage4(size_t& /*source_index*/,
3653  uint64_t lower_host_id,
3654  const HostPageSize& page_size) const {
3655  // Get a context
3656  MySqlHostContextAlloc get_context(*impl_);
3657  MySqlHostContextPtr ctx = get_context.ctx_;
3658 
3659  // Set up the WHERE clause value
3660  MYSQL_BIND inbind[2];
3661  memset(inbind, 0, sizeof(inbind));
3662 
3663  // Bind lower host id
3664  uint32_t host_id = lower_host_id;
3665  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3666  inbind[0].buffer = reinterpret_cast<char*>(&host_id);
3667  inbind[0].is_unsigned = MLM_TRUE;
3668 
3669  // Bind page size value
3670  uint32_t page_size_data = page_size.page_size_;
3671  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3672  inbind[1].buffer = reinterpret_cast<char*>(&page_size_data);
3673  inbind[1].is_unsigned = MLM_TRUE;
3674 
3675  ConstHostCollection result;
3676  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_PAGE4, inbind,
3677  ctx->host_ipv4_exchange_, result, false);
3678 
3679  return (result);
3680 }
3681 
3683 MySqlHostDataSource::getPage6(size_t& /*source_index*/,
3684  uint64_t lower_host_id,
3685  const HostPageSize& page_size) const {
3686  // Get a context
3687  MySqlHostContextAlloc get_context(*impl_);
3688  MySqlHostContextPtr ctx = get_context.ctx_;
3689 
3690  // Set up the WHERE clause value
3691  MYSQL_BIND inbind[2];
3692  memset(inbind, 0, sizeof(inbind));
3693 
3694  // Bind lower host id
3695  uint32_t host_id = lower_host_id;
3696  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3697  inbind[0].buffer = reinterpret_cast<char*>(&host_id);
3698  inbind[0].is_unsigned = MLM_TRUE;
3699 
3700  // Bind page size value
3701  uint32_t page_size_data = page_size.page_size_;
3702  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3703  inbind[1].buffer = reinterpret_cast<char*>(&page_size_data);
3704  inbind[1].is_unsigned = MLM_TRUE;
3705 
3706  ConstHostCollection result;
3707  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_PAGE6, inbind,
3708  ctx->host_ipv6_exchange_, result, false);
3709 
3710  return (result);
3711 }
3712 
3715  // Get a context
3716  MySqlHostContextAlloc get_context(*impl_);
3717  MySqlHostContextPtr ctx = get_context.ctx_;
3718 
3719  // Set up the WHERE clause value
3720  MYSQL_BIND inbind[1];
3721  memset(inbind, 0, sizeof(inbind));
3722 
3723  uint32_t addr4 = address.toUint32();
3724  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3725  inbind[0].buffer = reinterpret_cast<char*>(&addr4);
3726  inbind[0].is_unsigned = MLM_TRUE;
3727 
3728  ConstHostCollection result;
3729  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_ADDR, inbind,
3730  ctx->host_ipv4_exchange_, result, false);
3731 
3732  return (result);
3733 }
3734 
3737  const Host::IdentifierType& identifier_type,
3738  const uint8_t* identifier_begin,
3739  const size_t identifier_len) const {
3740  // Get a context
3741  MySqlHostContextAlloc get_context(*impl_);
3742  MySqlHostContextPtr ctx = get_context.ctx_;
3743 
3744  return (impl_->getHost(ctx, subnet_id, identifier_type, identifier_begin, identifier_len,
3746  ctx->host_ipv4_exchange_));
3747 }
3748 
3751  const asiolink::IOAddress& address) const {
3752  if (!address.isV4()) {
3753  isc_throw(BadValue, "MySqlHostDataSource::get4(id, address): "
3754  "wrong address type, address supplied is an IPv6 address");
3755  }
3756 
3757  // Get a context
3758  MySqlHostContextAlloc get_context(*impl_);
3759  MySqlHostContextPtr ctx = get_context.ctx_;
3760 
3761  // Set up the WHERE clause value
3762  MYSQL_BIND inbind[2];
3763  uint32_t subnet = subnet_id;
3764  memset(inbind, 0, sizeof(inbind));
3765  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3766  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3767  inbind[0].is_unsigned = MLM_TRUE;
3768 
3769  uint32_t addr4 = address.toUint32();
3770  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3771  inbind[1].buffer = reinterpret_cast<char*>(&addr4);
3772  inbind[1].is_unsigned = MLM_TRUE;
3773 
3774  ConstHostCollection collection;
3775  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID_ADDR, inbind,
3776  ctx->host_ipv4_exchange_, collection, true);
3777 
3778  // Return single record if present, else clear the host.
3779  ConstHostPtr result;
3780  if (!collection.empty()) {
3781  result = *collection.begin();
3782  }
3783 
3784  return (result);
3785 }
3786 
3789  const asiolink::IOAddress& address) const {
3790  if (!address.isV4()) {
3791  isc_throw(BadValue, "MySqlHostDataSource::getAll4(id, address): "
3792  "wrong address type, address supplied is an IPv6 address");
3793  }
3794 
3795  // Get a context
3796  MySqlHostContextAlloc get_context(*impl_);
3797  MySqlHostContextPtr ctx = get_context.ctx_;
3798 
3799  // Set up the WHERE clause value
3800  MYSQL_BIND inbind[2];
3801  uint32_t subnet = subnet_id;
3802  memset(inbind, 0, sizeof(inbind));
3803  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3804  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3805  inbind[0].is_unsigned = MLM_TRUE;
3806 
3807  uint32_t addr4 = address.toUint32();
3808  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3809  inbind[1].buffer = reinterpret_cast<char*>(&addr4);
3810  inbind[1].is_unsigned = MLM_TRUE;
3811 
3812  ConstHostCollection collection;
3813  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID_ADDR, inbind,
3814  ctx->host_ipv4_exchange_, collection, false);
3815  return (collection);
3816 }
3817 
3820  const Host::IdentifierType& identifier_type,
3821  const uint8_t* identifier_begin,
3822  const size_t identifier_len) const {
3823  // Get a context
3824  MySqlHostContextAlloc get_context(*impl_);
3825  MySqlHostContextPtr ctx = get_context.ctx_;
3826 
3827  return (impl_->getHost(ctx, subnet_id, identifier_type, identifier_begin, identifier_len,
3829  ctx->host_ipv6_exchange_));
3830 }
3831 
3834  const uint8_t prefix_len) const {
3835  if (!prefix.isV6()) {
3836  isc_throw(BadValue, "MySqlHostDataSource::get6(prefix, prefix_len): "
3837  "wrong address type, address supplied is an IPv4 address");
3838  }
3839 
3840  // Get a context
3841  MySqlHostContextAlloc get_context(*impl_);
3842  MySqlHostContextPtr ctx = get_context.ctx_;
3843 
3844  // Set up the WHERE clause value
3845  MYSQL_BIND inbind[2];
3846  memset(inbind, 0, sizeof(inbind));
3847 
3848  std::string addr6 = prefix.toText();
3849  unsigned long addr6_length = addr6.size();
3850 
3851  inbind[0].buffer_type = MYSQL_TYPE_BLOB;
3852  inbind[0].buffer = reinterpret_cast<char*>
3853  (const_cast<char*>(addr6.c_str()));
3854  inbind[0].length = &addr6_length;
3855  inbind[0].buffer_length = addr6_length;
3856 
3857  uint8_t tmp = prefix_len;
3858  inbind[1].buffer_type = MYSQL_TYPE_TINY;
3859  inbind[1].buffer = reinterpret_cast<char*>(&tmp);
3860  inbind[1].is_unsigned = MLM_TRUE;
3861 
3862  ConstHostCollection collection;
3863  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_PREFIX, inbind,
3864  ctx->host_ipv6_exchange_, collection, true);
3865 
3866  // Return single record if present, else clear the host.
3867  ConstHostPtr result;
3868  if (!collection.empty()) {
3869  result = *collection.begin();
3870  }
3871 
3872  return (result);
3873 }
3874 
3877  const asiolink::IOAddress& address) const {
3878  if (!address.isV6()) {
3879  isc_throw(BadValue, "MySqlHostDataSource::get6(id, address): "
3880  "wrong address type, address supplied is an IPv4 address");
3881  }
3882 
3883  // Get a context
3884  MySqlHostContextAlloc get_context(*impl_);
3885  MySqlHostContextPtr ctx = get_context.ctx_;
3886 
3887  // Set up the WHERE clause value
3888  MYSQL_BIND inbind[2];
3889  memset(inbind, 0, sizeof(inbind));
3890 
3891  uint32_t subnet_buffer = static_cast<uint32_t>(subnet_id);
3892  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3893  inbind[0].buffer = reinterpret_cast<char*>(&subnet_buffer);
3894  inbind[0].is_unsigned = MLM_TRUE;
3895 
3896  std::string addr6 = address.toText();
3897  unsigned long addr6_length = addr6.size();
3898 
3899  inbind[1].buffer_type = MYSQL_TYPE_BLOB;
3900  inbind[1].buffer = reinterpret_cast<char*>
3901  (const_cast<char*>(addr6.c_str()));
3902  inbind[1].length = &addr6_length;
3903  inbind[1].buffer_length = addr6_length;
3904 
3905  ConstHostCollection collection;
3906  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID6_ADDR, inbind,
3907  ctx->host_ipv6_exchange_, collection, true);
3908 
3909  // Return single record if present, else clear the host.
3910  ConstHostPtr result;
3911  if (!collection.empty()) {
3912  result = *collection.begin();
3913  }
3914 
3915  return (result);
3916 }
3917 
3920  const asiolink::IOAddress& address) const {
3921  if (!address.isV6()) {
3922  isc_throw(BadValue, "MySqlHostDataSource::getAll6(id, address): "
3923  "wrong address type, address supplied is an IPv4 address");
3924  }
3925 
3926  // Get a context
3927  MySqlHostContextAlloc get_context(*impl_);
3928  MySqlHostContextPtr ctx = get_context.ctx_;
3929 
3930  // Set up the WHERE clause value
3931  MYSQL_BIND inbind[2];
3932  memset(inbind, 0, sizeof(inbind));
3933 
3934  uint32_t subnet_buffer = static_cast<uint32_t>(subnet_id);
3935  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3936  inbind[0].buffer = reinterpret_cast<char*>(&subnet_buffer);
3937  inbind[0].is_unsigned = MLM_TRUE;
3938 
3939  std::string addr6 = address.toText();
3940  unsigned long addr6_length = addr6.size();
3941 
3942  inbind[1].buffer_type = MYSQL_TYPE_BLOB;
3943  inbind[1].buffer = reinterpret_cast<char*>
3944  (const_cast<char*>(addr6.c_str()));
3945  inbind[1].length = &addr6_length;
3946  inbind[1].buffer_length = addr6_length;
3947 
3948  ConstHostCollection collection;
3949  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID6_ADDR, inbind,
3950  ctx->host_ipv6_exchange_, collection, false);
3951  return (collection);
3952 }
3953 
3954 void
3956  // Get a context.
3957  MySqlHostContextAlloc const context(*impl_);
3958  MySqlHostContextPtr ctx(context.ctx_);
3959 
3960  // If operating in read-only mode, throw exception.
3961  impl_->checkReadOnly(ctx);
3962 
3963  // Initiate MySQL transaction as we will have to make multiple queries
3964  // to update host information into multiple tables. If that fails on
3965  // any stage, the transaction will be rolled back by the destructor of
3966  // the MySqlTransaction class.
3967  MySqlTransaction transaction(ctx->conn_);
3968 
3969  // As much as having dedicated prepared statements for updating tables would be consistent with
3970  // the implementation of other commands, it's difficult if not impossible to cover all cases for
3971  // updating the host to exactly as is described in the command, which may involve inserts and
3972  // deletes alongside updates. So let's delete and add. The delete cascades into all tables. The
3973  // add explicitly adds into all tables.
3975 
3976  // Everything went fine, so explicitly commit the transaction.
3977  transaction.commit();
3978 }
3979 
3980 // Miscellaneous database methods.
3981 
3982 std::string
3984  std::string name = "";
3985  // Get a context
3986  MySqlHostContextAlloc get_context(*impl_);
3987  MySqlHostContextPtr ctx = get_context.ctx_;
3988 
3989  try {
3990  name = ctx->conn_.getParameter("name");
3991  } catch (...) {
3992  // Return an empty name
3993  }
3994  return (name);
3995 }
3996 
3997 std::string
3999  return (std::string("Host data source that stores host information"
4000  "in MySQL database"));
4001 }
4002 
4003 std::pair<uint32_t, uint32_t>
4005  return(impl_->getVersion());
4006 }
4007 
4008 void
4010  // Get a context
4011  MySqlHostContextAlloc get_context(*impl_);
4012  MySqlHostContextPtr ctx = get_context.ctx_;
4013 
4014  // If operating in read-only mode, throw exception.
4015  impl_->checkReadOnly(ctx);
4016  if (ctx->conn_.isTransactionStarted()) {
4017  ctx->conn_.commit();
4018  }
4019 }
4020 
4021 void
4023  // Get a context
4024  MySqlHostContextAlloc get_context(*impl_);
4025  MySqlHostContextPtr ctx = get_context.ctx_;
4026 
4027  // If operating in read-only mode, throw exception.
4028  impl_->checkReadOnly(ctx);
4029  if (ctx->conn_.isTransactionStarted()) {
4030  ctx->conn_.rollback();
4031  }
4032 }
4033 
4034 bool
4036  impl_->ip_reservations_unique_ = unique;
4037  return (true);
4038 }
4039 
4040 bool
4042  return (impl_->unusable_);
4043 }
4044 
4045 } // namespace dhcp
4046 } // namespace isc
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
A generic exception that is thrown when an unexpected error condition occurs.
A standard Data module exception that is thrown if a parse error is encountered when constructing an ...
Definition: data.h:49
Data is truncated.
Definition: db_exceptions.h:23
static bool invokeDbLostCallback(const util::ReconnectCtlPtr &db_reconnect_ctl)
Invokes the connection's lost connectivity callback.
static bool invokeDbFailedCallback(const util::ReconnectCtlPtr &db_reconnect_ctl)
Invokes the connection's restore failed connectivity callback.
static ParameterMap parse(const std::string &dbaccess)
Parse database access string.
static bool invokeDbRecoveredCallback(const util::ReconnectCtlPtr &db_reconnect_ctl)
Invokes the connection's restored connectivity callback.
std::map< std::string, std::string > ParameterMap
Database configuration parameter map.
Exception thrown on failure to open database.
Exception thrown on failure to execute a database function.
Database duplicate entry error.
Definition: db_exceptions.h:30
Multiple lease records found where one expected.
Definition: db_exceptions.h:16
Common MySQL Connector Pool.
static std::pair< uint32_t, uint32_t > getVersion(const ParameterMap &parameters)
Get the schema version.
Fetch and Release MySQL Results.
RAII object representing MySQL transaction.
void commit()
Commits transaction.
Attempt to modify data in read-only database.
Definition: db_exceptions.h:44
Authentication keys.
Definition: host.h:75
virtual void update(HostPtr const &host)
Attempts to update an existing host entry.
static CfgMgr & instance()
returns a single instance of Configuration Manager
Definition: cfgmgr.cc:25
SrvConfigPtr getCurrentCfg()
Returns a pointer to the current configuration.
Definition: cfgmgr.cc:161
static bool delBackend(const std::string &db_type)
Delete an alternate host backend (aka host data source).
Definition: host_mgr.cc:64
static void addBackend(const std::string &access)
Add an alternate host backend (aka host data source).
Definition: host_mgr.cc:59
static isc::asiolink::IOServicePtr & getIOService()
Returns pointer to the IO service.
Definition: host_mgr.h:820
Wraps value holding size of the page with host reservations.
const size_t page_size_
Holds page size.
Represents a device with IPv4 and/or IPv6 reservations.
Definition: host.h:297
IdentifierType
Type of the host identifier.
Definition: host.h:307
IPv6 reservation for a host.
Definition: host.h:161
Type getType() const
Returns reservation type.
Definition: host.h:204
const asiolink::IOAddress & getPrefix() const
Returns prefix for the reservation.
Definition: host.h:190
Type
Type of the reservation.
Definition: host.h:167
uint8_t getPrefixLen() const
Returns prefix length.
Definition: host.h:195
std::vector< MySqlHostContextPtr > pool_
The vector of available contexts.
std::mutex mutex_
The mutex to protect pool access.
boost::shared_ptr< MySqlHostIPv6Exchange > host_ipv46_exchange_
Pointer to an object representing an exchange which can be used to retrieve hosts,...
boost::shared_ptr< MySqlHostIPv6Exchange > host_ipv6_exchange_
Pointer to an object representing an exchange which can be used to retrieve hosts,...
boost::shared_ptr< MySqlIPv6ReservationExchange > host_ipv6_reservation_exchange_
Pointer to an object representing an exchange which can be used to insert new IPv6 reservation.
boost::shared_ptr< MySqlHostWithOptionsExchange > host_ipv4_exchange_
The exchange objects are used for transfer of data to/from the database.
boost::shared_ptr< MySqlOptionExchange > host_option_exchange_
Pointer to an object representing an exchange which can be used to insert DHCPv4 or DHCPv6 option int...
MySqlConnection conn_
MySQL connection.
bool is_readonly_
Indicates if the database is opened in read only mode.
Implementation of the MySqlHostDataSource.
void checkReadOnly(MySqlHostContextPtr &ctx) const
Throws exception if database is read only.
void checkError(MySqlHostContextPtr &ctx, const int status, const StatementIndex index, const char *what) const
Check Error and Throw Exception.
std::string timer_name_
Timer name used to register database reconnect timer.
std::pair< uint32_t, uint32_t > getVersion() const
Returns backend version.
DatabaseConnection::ParameterMap parameters_
The parameters.
MySqlHostContextPtr createContext() const
Create a new context.
bool delStatement(MySqlHostContextPtr &ctx, StatementIndex stindex, MYSQL_BIND *bind)
Executes statements that delete records.
MySqlHostDataSourceImpl(const DatabaseConnection::ParameterMap &parameters)
Constructor.
ConstHostPtr getHost(MySqlHostContextPtr &ctx, const SubnetID &subnet_id, const Host::IdentifierType &identifier_type, const uint8_t *identifier_begin, const size_t identifier_len, StatementIndex stindex, boost::shared_ptr< MySqlHostExchange > exchange) const
Retrieves a host by subnet and client's unique identifier.
void addStatement(MySqlHostContextPtr &ctx, MySqlHostDataSourceImpl::StatementIndex stindex, std::vector< MYSQL_BIND > &bind)
Executes statements which inserts a row into one of the tables.
void getHostCollection(MySqlHostContextPtr &ctx, StatementIndex stindex, MYSQL_BIND *bind, boost::shared_ptr< MySqlHostExchange > exchange, ConstHostCollection &result, bool single) const
Creates collection of Host objects with associated information such as IPv6 reservations and/or DHCP ...
bool ip_reservations_unique_
Holds the setting whether the IP reservations must be unique or may be non-unique.
void addOptions(MySqlHostContextPtr &ctx, const StatementIndex &stindex, const ConstCfgOptionPtr &options_cfg, const uint64_t host_id)
Inserts multiple options into the database.
MySqlHostContextPoolPtr pool_
The pool of contexts.
void addOption(MySqlHostContextPtr &ctx, const MySqlHostDataSourceImpl::StatementIndex &stindex, const OptionDescriptor &opt_desc, const std::string &opt_space, const Optional< SubnetID > &subnet_id, const HostID &host_id)
Inserts a single DHCP option into the database.
bool unusable_
Indicates if there is at least one connection that can no longer be used for normal operations.
void addResv(MySqlHostContextPtr &ctx, const IPv6Resrv &resv, const HostID &id)
Inserts IPv6 Reservation into ipv6_reservation table.
static bool dbReconnect(ReconnectCtlPtr db_reconnect_ctl)
Attempts to reconnect the server to the host DB backend manager.
static const StatementIndex WRITE_STMTS_BEGIN
Index of first statement performing write to the database.
MySqlHostContextAlloc(MySqlHostDataSourceImpl &mgr)
Constructor.
virtual ConstHostCollection getAll(const Host::IdentifierType &identifier_type, const uint8_t *identifier_begin, const size_t identifier_len) const
Return all hosts connected to any subnet for which reservations have been made using a specified iden...
virtual ConstHostPtr get6(const SubnetID &subnet_id, const Host::IdentifierType &identifier_type, const uint8_t *identifier_begin, const size_t identifier_len) const
Returns a host connected to the IPv6 subnet.
virtual void commit()
Commit Transactions.
virtual bool del(const SubnetID &subnet_id, const asiolink::IOAddress &addr)
Attempts to delete hosts by (subnet-id, address)
virtual ConstHostCollection getAll4(const SubnetID &subnet_id) const
Return all hosts in a DHCPv4 subnet.
virtual std::pair< uint32_t, uint32_t > getVersion() const
Returns backend version.
virtual ConstHostCollection getAll6(const SubnetID &subnet_id) const
Return all hosts in a DHCPv6 subnet.
virtual std::string getDescription() const
Returns description of the backend.
MySqlHostDataSource(const db::DatabaseConnection::ParameterMap &parameters)
Constructor.
virtual ~MySqlHostDataSource()
Virtual destructor.
virtual ConstHostCollection getAllbyHostname(const std::string &hostname) const
Return all hosts with a hostname.
virtual isc::db::DatabaseConnection::ParameterMap getParameters() const
Return backend parameters.
void update(HostPtr const &host)
Implements BaseHostDataSource::update() for MySQL.
virtual bool del6(const SubnetID &subnet_id, const Host::IdentifierType &identifier_type, const uint8_t *identifier_begin, const size_t identifier_len)
Attempts to delete a host by (subnet6-id, identifier type, identifier)
virtual ConstHostCollection getPage6(const SubnetID &subnet_id, size_t &source_index, uint64_t lower_host_id, const HostPageSize &page_size) const
Returns range of hosts in a DHCPv6 subnet.
virtual ConstHostCollection getAllbyHostname6(const std::string &hostname, const SubnetID &subnet_id) const
Return all hosts with a hostname in a DHCPv6 subnet.
virtual bool del4(const SubnetID &subnet_id, const Host::IdentifierType &identifier_type, const uint8_t *identifier_begin, const size_t identifier_len)
Attempts to delete a host by (subnet4-id, identifier type, identifier)
virtual ConstHostCollection getPage4(const SubnetID &subnet_id, size_t &source_index, uint64_t lower_host_id, const HostPageSize &page_size) const
Returns range of hosts in a DHCPv4 subnet.
virtual bool isUnusable()
Flag which indicates if the host manager has at least one unusable connection.
virtual ConstHostCollection getAllbyHostname4(const std::string &hostname, const SubnetID &subnet_id) const
Return all hosts with a hostname in a DHCPv4 subnet.
virtual void rollback()
Rollback Transactions.
virtual std::string getName() const
Returns backend name.
virtual void add(const HostPtr &host)
Adds a new host to the collection.
virtual ConstHostPtr get4(const SubnetID &subnet_id, const Host::IdentifierType &identifier_type, const uint8_t *identifier_begin, const size_t identifier_len) const
Returns a host connected to the IPv4 subnet.
virtual bool setIPReservationsUnique(const bool unique)
Controls whether IP reservations are unique or non-unique.
Option descriptor.
Definition: cfg_option.h:46
OptionPtr option_
Option instance.
Definition: cfg_option.h:49
bool cancelled_
Cancelled flag.
Definition: cfg_option.h:63
std::string formatted_value_
Option value in textual (CSV) format.
Definition: cfg_option.h:78
bool persistent_
Persistence flag.
Definition: cfg_option.h:55
Universe
defines option universe DHCPv4 or DHCPv6
Definition: option.h:83
static const TimerMgrPtr & instance()
Returns pointer to the sole instance of the TimerMgr.
Definition: timer_mgr.cc:449
RAII class creating a critical section.
A template representing an optional value.
Definition: optional.h:36
void unspecified(bool unspecified)
Modifies the flag that indicates whether the value is specified or unspecified.
Definition: optional.h:136
The OutputBuffer class is a buffer abstraction for manipulating mutable data.
Definition: buffer.h:294
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
#define LOG_ERROR(LOGGER, MESSAGE)
Macro to conveniently test error output and log it.
Definition: macros.h:32
#define LOG_INFO(LOGGER, MESSAGE)
Macro to conveniently test info output and log it.
Definition: macros.h:20
#define LOG_DEBUG(LOGGER, LEVEL, MESSAGE)
Macro to conveniently test debug output and log it.
Definition: macros.h:14
boost::shared_ptr< const Element > ConstElementPtr
Definition: data.h:29
const my_bool MLM_FALSE
MySQL false value.
const uint32_t MYSQL_SCHEMA_VERSION_MAJOR
boost::shared_ptr< IOServiceAccessor > IOServiceAccessorPtr
Pointer to an instance of IOServiceAccessor.
@ error
Definition: db_log.h:116
const uint32_t MYSQL_SCHEMA_VERSION_MINOR
const my_bool MLM_TRUE
MySQL true value.
bool my_bool
my_bool type in MySQL 8.x.
const int MLM_MYSQL_FETCH_FAILURE
MySQL fetch failure code.
const int MLM_MYSQL_FETCH_SUCCESS
check for bool size
std::function< bool(util::ReconnectCtlPtr db_reconnect_ctl)> DbCallback
Defines a callback prototype for propagating events upward.
std::function< isc::asiolink::IOServicePtr()> IOServiceAccessor
Function which returns the IOService that can be used to recover the connection.
int MysqlExecuteStatement(MYSQL_STMT *stmt)
Execute a prepared statement.
isc::log::Logger dhcpsrv_logger("dhcpsrv")
DHCP server library Logger.
Definition: dhcpsrv_log.h:56
IPv6ResrvCollection::const_iterator IPv6ResrvIterator
Definition: host.h:241
const size_t OPTION_FORMATTED_VALUE_MAX_LEN
Maximum length of option value specified in textual format.
Definition: host.h:48
const isc::log::MessageID DHCPSRV_MYSQL_HOST_DB_GET_VERSION
boost::shared_ptr< CfgOption > CfgOptionPtr
Non-const pointer.
Definition: cfg_option.h:780
boost::shared_ptr< Host > HostPtr
Pointer to the Host object.
Definition: host.h:801
std::vector< ConstHostPtr > ConstHostCollection
Collection of the const Host objects.
Definition: host.h:807
const isc::log::MessageID DHCPSRV_MYSQL_NO_TLS
boost::shared_ptr< CfgDbAccess > CfgDbAccessPtr
A pointer to the CfgDbAccess.
const size_t CLIENT_CLASSES_MAX_LEN
Maximum length of classes stored in a dhcp4/6_client_classes columns.
Definition: host.h:36
std::pair< IPv6ResrvIterator, IPv6ResrvIterator > IPv6ResrvRange
Definition: host.h:243
const int DHCPSRV_DBG_TRACE_DETAIL
Additional information.
Definition: dhcpsrv_log.h:38
const size_t TEXT_AUTH_KEY_LEN
Maximum length of authentication keys (coded in hexadecimal).
Definition: host.h:66
const isc::log::MessageID DHCPSRV_MYSQL_HOST_DB_RECONNECT_FAILED
boost::shared_ptr< OptionDefinition > OptionDefinitionPtr
Pointer to option definition object.
uint32_t SubnetID
Defines unique IPv4 or IPv6 subnet identifier.
Definition: subnet_id.h:25
uint64_t HostID
HostID (used only when storing in MySQL or PostgreSQL backends)
Definition: host.h:69
boost::shared_ptr< OptionContainer > OptionContainerPtr
Pointer to the OptionContainer object.
Definition: cfg_option.h:302
const size_t ADDRESS6_TEXT_MAX_LEN
Maximum size of an IPv6 address represented as a text string.
Definition: host.h:32
boost::shared_ptr< const Host > ConstHostPtr
Const pointer to the Host object.
Definition: host.h:804
boost::shared_ptr< MySqlHostContextPool > MySqlHostContextPoolPtr
Type of pointers to context pools.
const size_t HOSTNAME_MAX_LEN
Maximum length of the hostname stored in DNS.
Definition: host.h:42
boost::shared_ptr< MySqlHostContext > MySqlHostContextPtr
Type of pointers to contexts.
const size_t USER_CONTEXT_MAX_LEN
Maximum length of user context.
Definition: host.h:54
const size_t OPTION_VALUE_MAX_LEN
Maximum length of option value.
Definition: host.h:45
std::vector< uint8_t > OptionBuffer
buffer types used in DHCP code.
Definition: option.h:24
const size_t SERVER_HOSTNAME_MAX_LEN
Maximum length of the server hostname.
Definition: host.h:57
const isc::log::MessageID DHCPSRV_MYSQL_HOST_DB_READONLY
const size_t BOOT_FILE_NAME_MAX_LEN
Maximum length of the boot file name.
Definition: host.h:60
const int DHCPSRV_DBG_TRACE
DHCP server library logging levels.
Definition: dhcpsrv_log.h:26
const isc::log::MessageID DHCPSRV_MYSQL_HOST_DB_RECONNECT_ATTEMPT_SCHEDULE
boost::shared_ptr< Option > OptionPtr
Definition: option.h:36
const isc::log::MessageID DHCPSRV_MYSQL_HOST_DB_RECONNECT_ATTEMPT_FAILED
const isc::log::MessageID DHCPSRV_MYSQL_TLS_CIPHER
boost::shared_ptr< const CfgOption > ConstCfgOptionPtr
Const pointer.
Definition: cfg_option.h:783
const size_t OPTION_SPACE_MAX_LEN
Maximum length of option space name.
Definition: host.h:51
Definition: edns.h:19
boost::shared_ptr< ReconnectCtl > ReconnectCtlPtr
Pointer to an instance of ReconnectCtl.
Defines the logger used by the top-level component of kea-lfc.
uint16_t code_
#define DHCP4_OPTION_SPACE
global std option spaces
#define DHCP6_OPTION_SPACE
data::ConstElementPtr getContext() const
Returns const pointer to the user context.
Definition: user_context.h:24