Kea  1.9.9-git
mysql_host_data_source.cc
Go to the documentation of this file.
1 // Copyright (C) 2015-2021 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:
85 
87  static const size_t HOST_COLUMNS = 14;
88 
89 public:
90 
97  MySqlHostExchange(const size_t additional_columns_num = 0)
98  : columns_num_(HOST_COLUMNS + additional_columns_num),
99  bind_(columns_num_), columns_(columns_num_),
100  error_(columns_num_, MLM_FALSE), host_id_(0),
101  dhcp_identifier_length_(0), dhcp_identifier_type_(0),
102  dhcp4_subnet_id_(SUBNET_ID_UNUSED),
103  dhcp6_subnet_id_(SUBNET_ID_UNUSED), ipv4_address_(0),
104  hostname_length_(0), dhcp4_client_classes_length_(0),
105  dhcp6_client_classes_length_(0),
106  user_context_length_(0),
107  dhcp4_next_server_(0),
108  dhcp4_server_hostname_length_(0),
109  dhcp4_boot_file_name_length_(0),
110  auth_key_length_(0),
111  dhcp4_subnet_id_null_(MLM_FALSE),
112  dhcp6_subnet_id_null_(MLM_FALSE),
113  ipv4_address_null_(MLM_FALSE), hostname_null_(MLM_FALSE),
114  dhcp4_client_classes_null_(MLM_FALSE),
115  dhcp6_client_classes_null_(MLM_FALSE),
116  user_context_null_(MLM_FALSE),
117  dhcp4_next_server_null_(MLM_FALSE),
118  dhcp4_server_hostname_null_(MLM_FALSE),
119  dhcp4_boot_file_name_null_(MLM_FALSE),
120  auth_key_null_(MLM_FALSE) {
121 
122  // Fill arrays with 0 so as they don't include any garbage.
123  memset(dhcp_identifier_buffer_, 0, sizeof(dhcp_identifier_buffer_));
124  memset(hostname_, 0, sizeof(hostname_));
125  memset(dhcp4_client_classes_, 0, sizeof(dhcp4_client_classes_));
126  memset(dhcp6_client_classes_, 0, sizeof(dhcp6_client_classes_));
127  memset(user_context_, 0, sizeof(user_context_));
128  memset(dhcp4_server_hostname_, 0, sizeof(dhcp4_server_hostname_));
129  memset(dhcp4_boot_file_name_, 0, sizeof(dhcp4_boot_file_name_));
130  memset(auth_key_, 0, sizeof(auth_key_));
131 
132  // Set the column names for use by this class. This only comprises
133  // names used by the MySqlHostExchange class. Derived classes will
134  // need to set names for the columns they use.
135  columns_[0] = "host_id";
136  columns_[1] = "dhcp_identifier";
137  columns_[2] = "dhcp_identifier_type";
138  columns_[3] = "dhcp4_subnet_id";
139  columns_[4] = "dhcp6_subnet_id";
140  columns_[5] = "ipv4_address";
141  columns_[6] = "hostname";
142  columns_[7] = "dhcp4_client_classes";
143  columns_[8] = "dhcp6_client_classes";
144  columns_[9] = "user_context";
145  columns_[10] = "dhcp4_next_server";
146  columns_[11] = "dhcp4_server_hostname";
147  columns_[12] = "dhcp4_boot_file_name";
148  columns_[13] = "auth_key";
149 
150  BOOST_STATIC_ASSERT(13 < HOST_COLUMNS);
151  };
152 
154  virtual ~MySqlHostExchange() {
155  }
156 
171  size_t findAvailColumn() const {
172  std::vector<std::string>::const_iterator empty_column =
173  std::find(columns_.begin(), columns_.end(), std::string());
174  return (std::distance(columns_.begin(), empty_column));
175  }
176 
180  uint64_t getHostId() const {
181  return (host_id_);
182  };
183 
194  static void setErrorIndicators(std::vector<MYSQL_BIND>& bind,
195  std::vector<my_bools>& error) {
196  for (size_t i = 0; i < error.size(); ++i) {
197  error[i] = MLM_FALSE;
198  bind[i].error = reinterpret_cast<my_bool*>(&error[i]);
199  }
200  };
201 
215  static std::string getColumnsInError(std::vector<my_bools>& error,
216  const std::vector<std::string>& names) {
217  std::string result = "";
218 
219  // Accumulate list of column names
220  for (size_t i = 0; i < names.size(); ++i) {
221  if (error[i] == MLM_TRUE) {
222  if (!result.empty()) {
223  result += ", ";
224  }
225  result += names[i];
226  }
227  }
228 
229  if (result.empty()) {
230  result = "(None)";
231  }
232 
233  return (result);
234  };
235 
248  std::vector<MYSQL_BIND> createBindForSend(const HostPtr& host, const bool unique_ip) {
249  // Store host object to ensure it remains valid.
250  host_ = host;
251 
252  // Initialize prior to constructing the array of MYSQL_BIND structures.
253  // It sets all fields, including is_null, to zero, so we need to set
254  // is_null only if it should be true. This gives up minor performance
255  // benefit while being safe approach.
256  memset(&bind_[0], 0, sizeof(MYSQL_BIND) * bind_.size());
257 
258  // Set up the structures for the various components of the host structure.
259 
260  try {
261  // host_id : INT UNSIGNED NOT NULL
262  // The host_id is auto_incremented by MySQL database,
263  // so we need to pass the NULL value
264  host_id_ = 0;
265  bind_[0].buffer_type = MYSQL_TYPE_LONG;
266  bind_[0].buffer = reinterpret_cast<char*>(&host_id_);
267  bind_[0].is_unsigned = MLM_TRUE;
268 
269  // dhcp_identifier : VARBINARY(128) NOT NULL
270  dhcp_identifier_length_ = host->getIdentifier().size();
271  memcpy(static_cast<void*>(dhcp_identifier_buffer_),
272  &(host->getIdentifier())[0],
273  host->getIdentifier().size());
274 
275  bind_[1].buffer_type = MYSQL_TYPE_BLOB;
276  bind_[1].buffer = dhcp_identifier_buffer_;
277  bind_[1].buffer_length = dhcp_identifier_length_;
278  bind_[1].length = &dhcp_identifier_length_;
279 
280  // dhcp_identifier_type : TINYINT NOT NULL
281  dhcp_identifier_type_ = static_cast<uint8_t>(host->getIdentifierType());
282  bind_[2].buffer_type = MYSQL_TYPE_TINY;
283  bind_[2].buffer = reinterpret_cast<char*>(&dhcp_identifier_type_);
284  bind_[2].is_unsigned = MLM_TRUE;
285 
286  // dhcp4_subnet_id : INT UNSIGNED NULL
287  // Can't take an address of intermediate object, so let's store it
288  // in dhcp4_subnet_id_
289  dhcp4_subnet_id_ = host->getIPv4SubnetID();
290  dhcp4_subnet_id_null_ = host->getIPv4SubnetID() == SUBNET_ID_UNUSED ? MLM_TRUE : MLM_FALSE;
291  bind_[3].buffer_type = MYSQL_TYPE_LONG;
292  bind_[3].buffer = reinterpret_cast<char*>(&dhcp4_subnet_id_);
293  bind_[3].is_unsigned = MLM_TRUE;
294  bind_[3].is_null = &dhcp4_subnet_id_null_;
295 
296  // dhcp6_subnet_id : INT UNSIGNED NULL
297  // Can't take an address of intermediate object, so let's store it
298  // in dhcp6_subnet_id_
299  dhcp6_subnet_id_ = host->getIPv6SubnetID();
300  dhcp6_subnet_id_null_ = host->getIPv6SubnetID() == SUBNET_ID_UNUSED ? MLM_TRUE : MLM_FALSE;
301  bind_[4].buffer_type = MYSQL_TYPE_LONG;
302  bind_[4].buffer = reinterpret_cast<char*>(&dhcp6_subnet_id_);
303  bind_[4].is_unsigned = MLM_TRUE;
304  bind_[4].is_null = &dhcp6_subnet_id_null_;
305 
306  // ipv4_address : INT UNSIGNED NULL
307  // The address in the Host structure is an IOAddress object. Convert
308  // this to an integer for storage.
309  ipv4_address_ = host->getIPv4Reservation().toUint32();
310  ipv4_address_null_ = ipv4_address_ == 0 ? MLM_TRUE : MLM_FALSE;
311  bind_[5].buffer_type = MYSQL_TYPE_LONG;
312  bind_[5].buffer = reinterpret_cast<char*>(&ipv4_address_);
313  bind_[5].is_unsigned = MLM_TRUE;
314  bind_[5].is_null = &ipv4_address_null_;
315 
316  // hostname : VARCHAR(255) NULL
317  strncpy(hostname_, host->getHostname().c_str(), HOSTNAME_MAX_LEN - 1);
318  hostname_length_ = host->getHostname().length();
319  bind_[6].buffer_type = MYSQL_TYPE_STRING;
320  bind_[6].buffer = reinterpret_cast<char*>(hostname_);
321  bind_[6].buffer_length = hostname_length_;
322 
323  // dhcp4_client_classes : VARCHAR(255) NULL
324  bind_[7].buffer_type = MYSQL_TYPE_STRING;
325  // Override default separator to not include space after comma.
326  string classes4_txt = host->getClientClasses4().toText(",");
327  strncpy(dhcp4_client_classes_, classes4_txt.c_str(), CLIENT_CLASSES_MAX_LEN - 1);
328  bind_[7].buffer = dhcp4_client_classes_;
329  bind_[7].buffer_length = classes4_txt.length();
330 
331  // dhcp6_client_classes : VARCHAR(255) NULL
332  bind_[8].buffer_type = MYSQL_TYPE_STRING;
333  // Override default separator to not include space after comma.
334  string classes6_txt = host->getClientClasses6().toText(",");
335  strncpy(dhcp6_client_classes_, classes6_txt.c_str(), CLIENT_CLASSES_MAX_LEN - 1);
336  bind_[8].buffer = dhcp6_client_classes_;
337  bind_[8].buffer_length = classes6_txt.length();
338 
339  // user_context : TEXT NULL
340  ConstElementPtr ctx = host->getContext();
341  if (ctx) {
342  bind_[9].buffer_type = MYSQL_TYPE_STRING;
343  string ctx_txt = ctx->str();
344  strncpy(user_context_, ctx_txt.c_str(), USER_CONTEXT_MAX_LEN - 1);
345  bind_[9].buffer = user_context_;
346  bind_[9].buffer_length = ctx_txt.length();
347  } else {
348  bind_[9].buffer_type = MYSQL_TYPE_NULL;
349  }
350 
351  // ipv4_address : INT UNSIGNED NULL
352  // The address in the Host structure is an IOAddress object. Convert
353  // this to an integer for storage.
354  dhcp4_next_server_ = host->getNextServer().toUint32();
355  bind_[10].buffer_type = MYSQL_TYPE_LONG;
356  bind_[10].buffer = reinterpret_cast<char*>(&dhcp4_next_server_);
357  bind_[10].is_unsigned = MLM_TRUE;
358  // bind_[10].is_null = &MLM_FALSE; // commented out for performance
359  // reasons, see memset() above
360 
361  // dhcp4_server_hostname
362  bind_[11].buffer_type = MYSQL_TYPE_STRING;
363  std::string server_hostname = host->getServerHostname();
364  strncpy(dhcp4_server_hostname_, server_hostname.c_str(),
366  bind_[11].buffer = dhcp4_server_hostname_;
367  bind_[11].buffer_length = server_hostname.length();
368 
369  // dhcp4_boot_file_name
370  bind_[12].buffer_type = MYSQL_TYPE_STRING;
371  std::string boot_file_name = host->getBootFileName();
372  strncpy(dhcp4_boot_file_name_, boot_file_name.c_str(),
374  bind_[12].buffer = dhcp4_boot_file_name_;
375  bind_[12].buffer_length = boot_file_name.length();
376 
377  // auth key
378  bind_[13].buffer_type = MYSQL_TYPE_STRING;
379  std::string auth_key = host->getKey().toText();
380  std::strncpy(auth_key_, auth_key.c_str(), TEXT_AUTH_KEY_LEN - 1);
381  auth_key_null_ = auth_key.empty() ? MLM_TRUE : MLM_FALSE;
382  bind_[13].buffer = auth_key_;
383  bind_[13].buffer_length = auth_key.length();
384 
385  } catch (const std::exception& ex) {
387  "Could not create bind array from Host: "
388  << host->getHostname() << ", reason: " << ex.what());
389  }
390 
391  // Add the data to the vector.
392  std::vector<MYSQL_BIND> vec(bind_.begin(), bind_.begin() + HOST_COLUMNS);
393 
394  // When checking whether the IP is unique we need to bind the IPv4 address
395  // at the end of the query as it has additional binding for the IPv4
396  // address.
397  if (unique_ip) {
398  vec.push_back(bind_[5]); // ipv4_address
399  vec.push_back(bind_[3]); // subnet_id
400  }
401  return (vec);
402  };
403 
411  virtual std::vector<MYSQL_BIND> createBindForReceive() {
412  // Initialize MYSQL_BIND array.
413  // It sets all fields, including is_null, to zero, so we need to set
414  // is_null only if it should be true. This gives up minor performance
415  // benefit while being safe approach. For improved readability, the
416  // code that explicitly sets is_null is there, but is commented out.
417  // This also takes care of setting bind_[X].is_null to MLM_FALSE.
418  memset(&bind_[0], 0, sizeof(MYSQL_BIND) * bind_.size());
419 
420  // host_id : INT UNSIGNED NOT NULL
421  bind_[0].buffer_type = MYSQL_TYPE_LONG;
422  bind_[0].buffer = reinterpret_cast<char*>(&host_id_);
423  bind_[0].is_unsigned = MLM_TRUE;
424 
425  // dhcp_identifier : VARBINARY(128) NOT NULL
426  dhcp_identifier_length_ = sizeof(dhcp_identifier_buffer_);
427  bind_[1].buffer_type = MYSQL_TYPE_BLOB;
428  bind_[1].buffer = reinterpret_cast<char*>(dhcp_identifier_buffer_);
429  bind_[1].buffer_length = dhcp_identifier_length_;
430  bind_[1].length = &dhcp_identifier_length_;
431 
432  // dhcp_identifier_type : TINYINT NOT NULL
433  bind_[2].buffer_type = MYSQL_TYPE_TINY;
434  bind_[2].buffer = reinterpret_cast<char*>(&dhcp_identifier_type_);
435  bind_[2].is_unsigned = MLM_TRUE;
436 
437  // dhcp4_subnet_id : INT UNSIGNED NULL
438  dhcp4_subnet_id_null_ = MLM_FALSE;
439  bind_[3].buffer_type = MYSQL_TYPE_LONG;
440  bind_[3].buffer = reinterpret_cast<char*>(&dhcp4_subnet_id_);
441  bind_[3].is_unsigned = MLM_TRUE;
442  bind_[3].is_null = &dhcp4_subnet_id_null_;
443 
444  // dhcp6_subnet_id : INT UNSIGNED NULL
445  dhcp6_subnet_id_null_ = MLM_FALSE;
446  bind_[4].buffer_type = MYSQL_TYPE_LONG;
447  bind_[4].buffer = reinterpret_cast<char*>(&dhcp6_subnet_id_);
448  bind_[4].is_unsigned = MLM_TRUE;
449  bind_[4].is_null = &dhcp6_subnet_id_null_;
450 
451  // ipv4_address : INT UNSIGNED NULL
452  ipv4_address_null_ = MLM_FALSE;
453  bind_[5].buffer_type = MYSQL_TYPE_LONG;
454  bind_[5].buffer = reinterpret_cast<char*>(&ipv4_address_);
455  bind_[5].is_unsigned = MLM_TRUE;
456  bind_[5].is_null = &ipv4_address_null_;
457 
458  // hostname : VARCHAR(255) NULL
459  hostname_null_ = MLM_FALSE;
460  hostname_length_ = sizeof(hostname_);
461  bind_[6].buffer_type = MYSQL_TYPE_STRING;
462  bind_[6].buffer = reinterpret_cast<char*>(hostname_);
463  bind_[6].buffer_length = hostname_length_;
464  bind_[6].length = &hostname_length_;
465  bind_[6].is_null = &hostname_null_;
466 
467  // dhcp4_client_classes : VARCHAR(255) NULL
468  dhcp4_client_classes_null_ = MLM_FALSE;
469  dhcp4_client_classes_length_ = sizeof(dhcp4_client_classes_);
470  bind_[7].buffer_type = MYSQL_TYPE_STRING;
471  bind_[7].buffer = reinterpret_cast<char*>(dhcp4_client_classes_);
472  bind_[7].buffer_length = dhcp4_client_classes_length_;
473  bind_[7].length = &dhcp4_client_classes_length_;
474  bind_[7].is_null = &dhcp4_client_classes_null_;
475 
476  // dhcp6_client_classes : VARCHAR(255) NULL
477  dhcp6_client_classes_null_ = MLM_FALSE;
478  dhcp6_client_classes_length_ = sizeof(dhcp6_client_classes_);
479  bind_[8].buffer_type = MYSQL_TYPE_STRING;
480  bind_[8].buffer = reinterpret_cast<char*>(dhcp6_client_classes_);
481  bind_[8].buffer_length = dhcp6_client_classes_length_;
482  bind_[8].length = &dhcp6_client_classes_length_;
483  bind_[8].is_null = &dhcp6_client_classes_null_;
484 
485  // user_context : TEXT NULL
486  user_context_null_ = MLM_FALSE;
487  user_context_length_ = sizeof(user_context_);
488  bind_[9].buffer_type = MYSQL_TYPE_STRING;
489  bind_[9].buffer = reinterpret_cast<char*>(user_context_);
490  bind_[9].buffer_length = user_context_length_;
491  bind_[9].length = &user_context_length_;
492  bind_[9].is_null = &user_context_null_;
493 
494  // dhcp4_next_server
495  dhcp4_next_server_null_ = MLM_FALSE;
496  bind_[10].buffer_type = MYSQL_TYPE_LONG;
497  bind_[10].buffer = reinterpret_cast<char*>(&dhcp4_next_server_);
498  bind_[10].is_unsigned = MLM_TRUE;
499  bind_[10].is_null = &dhcp4_next_server_null_;
500 
501  // dhcp4_server_hostname
502  dhcp4_server_hostname_null_ = MLM_FALSE;
503  dhcp4_server_hostname_length_ = sizeof(dhcp4_server_hostname_);
504  bind_[11].buffer_type = MYSQL_TYPE_STRING;
505  bind_[11].buffer = reinterpret_cast<char*>(dhcp4_server_hostname_);
506  bind_[11].buffer_length = dhcp4_server_hostname_length_;
507  bind_[11].length = &dhcp4_server_hostname_length_;
508  bind_[11].is_null = &dhcp4_server_hostname_null_;
509 
510  // dhcp4_boot_file_name
511  dhcp4_boot_file_name_null_ = MLM_FALSE;
512  dhcp4_boot_file_name_length_ = sizeof(dhcp4_boot_file_name_);
513  bind_[12].buffer_type = MYSQL_TYPE_STRING;
514  bind_[12].buffer = reinterpret_cast<char*>(dhcp4_boot_file_name_);
515  bind_[12].buffer_length = dhcp4_boot_file_name_length_;
516  bind_[12].length = &dhcp4_boot_file_name_length_;
517  bind_[12].is_null = &dhcp4_boot_file_name_null_;
518 
519  // auth_key_
520  auth_key_null_ = MLM_FALSE;
521  auth_key_length_ = sizeof(auth_key_);
522  bind_[13].buffer_type = MYSQL_TYPE_STRING;
523  bind_[13].buffer = reinterpret_cast<char*>(auth_key_);
524  bind_[13].buffer_length = auth_key_length_;
525  bind_[13].length = &auth_key_length_;
526  bind_[13].is_null = &auth_key_null_;
527 
528  // Add the error flags
529  setErrorIndicators(bind_, error_);
530 
531  // Add the data to the vector. Note the end element is one after the
532  // end of the array.
533  return (bind_);
534  };
535 
544  HostPtr retrieveHost() {
545  // Check if the identifier stored in the database is correct.
546  if (dhcp_identifier_type_ > MAX_IDENTIFIER_TYPE) {
547  isc_throw(BadValue, "invalid dhcp identifier type returned: "
548  << static_cast<int>(dhcp_identifier_type_));
549  }
550  // Set the dhcp identifier type in a variable of the appropriate
551  // data type.
552  Host::IdentifierType type =
553  static_cast<Host::IdentifierType>(dhcp_identifier_type_);
554 
555  // Set DHCPv4 subnet ID to the value returned. If NULL returned,
556  // set to 0.
557  SubnetID ipv4_subnet_id(SUBNET_ID_UNUSED);
558  if (dhcp4_subnet_id_null_ == MLM_FALSE) {
559  ipv4_subnet_id = static_cast<SubnetID>(dhcp4_subnet_id_);
560  }
561 
562  // Set DHCPv6 subnet ID to the value returned. If NULL returned,
563  // set to 0.
564  SubnetID ipv6_subnet_id(SUBNET_ID_UNUSED);
565  if (dhcp6_subnet_id_null_ == MLM_FALSE) {
566  ipv6_subnet_id = static_cast<SubnetID>(dhcp6_subnet_id_);
567  }
568 
569  // Set IPv4 address reservation if it was given, if not, set IPv4 zero
570  // address
571  asiolink::IOAddress ipv4_reservation = asiolink::IOAddress::IPV4_ZERO_ADDRESS();
572  if (ipv4_address_null_ == MLM_FALSE) {
573  ipv4_reservation = asiolink::IOAddress(ipv4_address_);
574  }
575 
576  // Set hostname if non NULL value returned. Otherwise, leave an
577  // empty string.
578  std::string hostname;
579  if (hostname_null_ == MLM_FALSE) {
580  hostname = std::string(hostname_, hostname_length_);
581  }
582 
583  // Set DHCPv4 client classes if non NULL value returned.
584  std::string dhcp4_client_classes;
585  if (dhcp4_client_classes_null_ == MLM_FALSE) {
586  dhcp4_client_classes = std::string(dhcp4_client_classes_,
587  dhcp4_client_classes_length_);
588  }
589 
590  // Set DHCPv6 client classes if non NULL value returned.
591  std::string dhcp6_client_classes;
592  if (dhcp6_client_classes_null_ == MLM_FALSE) {
593  dhcp6_client_classes = std::string(dhcp6_client_classes_,
594  dhcp6_client_classes_length_);
595  }
596 
597  // Convert user_context to string as well.
598  std::string user_context;
599  if (user_context_null_ == MLM_FALSE) {
600  user_context_[user_context_length_] = '\0';
601  user_context.assign(user_context_);
602  }
603 
604  // Set next server value (siaddr) if non NULL value returned.
605  asiolink::IOAddress next_server = asiolink::IOAddress::IPV4_ZERO_ADDRESS();
606  if (dhcp4_next_server_null_ == MLM_FALSE) {
607  next_server = asiolink::IOAddress(dhcp4_next_server_);
608  }
609 
610  // Set server hostname (sname) if non NULL value returned.
611  std::string dhcp4_server_hostname;
612  if (dhcp4_server_hostname_null_ == MLM_FALSE) {
613  dhcp4_server_hostname = std::string(dhcp4_server_hostname_,
614  dhcp4_server_hostname_length_);
615  }
616 
617  // Set boot file name (file) if non NULL value returned.
618  std::string dhcp4_boot_file_name;
619  if (dhcp4_boot_file_name_null_ == MLM_FALSE) {
620  dhcp4_boot_file_name = std::string(dhcp4_boot_file_name_,
621  dhcp4_boot_file_name_length_);
622  }
623 
624  // Set the auth key if a non empty array is retrieved
625  std::string auth_key;
626  if (auth_key_null_ == MLM_FALSE) {
627  auth_key = std::string(auth_key_, auth_key_length_);
628  }
629 
630  // Create and return Host object from the data gathered.
631  HostPtr h(new Host(dhcp_identifier_buffer_, dhcp_identifier_length_,
632  type, ipv4_subnet_id, ipv6_subnet_id, ipv4_reservation,
633  hostname, dhcp4_client_classes, dhcp6_client_classes,
634  next_server, dhcp4_server_hostname,
635  dhcp4_boot_file_name, AuthKey(auth_key)));
636  h->setHostId(host_id_);
637 
638  // Set the user context if there is one.
639  if (!user_context.empty()) {
640  try {
641  ConstElementPtr ctx = Element::fromJSON(user_context);
642  if (!ctx || (ctx->getType() != Element::map)) {
643  isc_throw(BadValue, "user context '" << user_context
644  << "' is not a JSON map");
645  }
646  h->setContext(ctx);
647  } catch (const isc::data::JSONError& ex) {
648  isc_throw(BadValue, "user context '" << user_context
649  << "' is invalid JSON: " << ex.what());
650  }
651  }
652 
653  return (h);
654  };
655 
669  virtual void processFetchedData(ConstHostCollection& hosts) {
670  HostPtr host;
671  // Add new host only if there are no hosts yet or the host id of the
672  // most recently added host is different than the host id of the
673  // currently processed host.
674  if (hosts.empty() || (hosts.back()->getHostId() != getHostId())) {
675  // Create Host object from the fetched data and append it to the
676  // collection.
677  host = retrieveHost();
678  hosts.push_back(host);
679  }
680  }
681 
692  std::string getErrorColumns() {
693  return (getColumnsInError(error_, columns_));
694  };
695 
696 protected:
697 
699  size_t columns_num_;
700 
702  std::vector<MYSQL_BIND> bind_;
703 
705  std::vector<std::string> columns_;
706 
708  std::vector<my_bools> error_;
709 
712  HostPtr host_;
713 
714 private:
715 
717  uint64_t host_id_;
718 
721  uint8_t dhcp_identifier_buffer_[DUID::MAX_DUID_LEN];
722 
724  unsigned long dhcp_identifier_length_;
725 
728  uint8_t dhcp_identifier_type_;
729 
731  uint32_t dhcp4_subnet_id_;
732 
734  uint32_t dhcp6_subnet_id_;
735 
737  uint32_t ipv4_address_;
738 
740  char hostname_[HOSTNAME_MAX_LEN];
741 
743  unsigned long hostname_length_;
744 
746  char dhcp4_client_classes_[CLIENT_CLASSES_MAX_LEN];
747 
750  unsigned long dhcp4_client_classes_length_;
751 
753  char dhcp6_client_classes_[CLIENT_CLASSES_MAX_LEN];
754 
757  unsigned long dhcp6_client_classes_length_;
758 
760  char user_context_[USER_CONTEXT_MAX_LEN];
761 
763  unsigned long user_context_length_;
764 
766  uint32_t dhcp4_next_server_;
767 
769  char dhcp4_server_hostname_[SERVER_HOSTNAME_MAX_LEN];
770 
772  unsigned long dhcp4_server_hostname_length_;
773 
775  char dhcp4_boot_file_name_[BOOT_FILE_NAME_MAX_LEN];
776 
778  unsigned long dhcp4_boot_file_name_length_;
779 
781  char auth_key_[TEXT_AUTH_KEY_LEN];
782 
784  unsigned long auth_key_length_;
785 
788 
789  my_bool dhcp4_subnet_id_null_;
791 
793  my_bool dhcp6_subnet_id_null_;
794 
796  my_bool ipv4_address_null_;
797 
799  my_bool hostname_null_;
800 
803  my_bool dhcp4_client_classes_null_;
804 
807  my_bool dhcp6_client_classes_null_;
808 
810  my_bool user_context_null_;
811 
813  my_bool dhcp4_next_server_null_;
814 
816  my_bool dhcp4_server_hostname_null_;
817 
819  my_bool dhcp4_boot_file_name_null_;
820 
822  my_bool auth_key_null_;
823 
825 };
826 
836 class MySqlHostWithOptionsExchange : public MySqlHostExchange {
837 private:
838 
840  static const size_t OPTION_COLUMNS = 7;
841 
856  class OptionProcessor {
857  public:
858 
865  OptionProcessor(const Option::Universe& universe,
866  const size_t start_column)
867  : universe_(universe), start_column_(start_column), option_id_(0),
868  code_(0), value_length_(0), formatted_value_length_(0),
869  space_length_(0), persistent_(false), user_context_length_(0),
870  option_id_null_(MLM_FALSE), code_null_(MLM_FALSE),
871  value_null_(MLM_FALSE), formatted_value_null_(MLM_FALSE),
872  space_null_(MLM_FALSE), user_context_null_(MLM_FALSE),
873  option_id_index_(start_column), code_index_(start_column_ + 1),
874  value_index_(start_column_ + 2),
875  formatted_value_index_(start_column_ + 3),
876  space_index_(start_column_ + 4),
877  persistent_index_(start_column_ + 5),
878  user_context_index_(start_column_ + 6),
879  most_recent_option_id_(0) {
880 
881  memset(value_, 0, sizeof(value_));
882  memset(formatted_value_, 0, sizeof(formatted_value_));
883  memset(space_, 0, sizeof(space_));
884  memset(user_context_, 0, sizeof(user_context_));
885  }
886 
888  uint64_t getOptionId() const {
889  if (option_id_null_ == MLM_FALSE) {
890  return (option_id_);
891  }
892  return (0);
893  }
894 
907  void retrieveOption(const CfgOptionPtr& cfg) {
908  // option_id may be NULL if dhcp4_options or dhcp6_options table
909  // doesn't contain any options for the particular host. Also, the
910  // current option id must be greater than id if the most recent
911  // option because options are ordered by option id. Otherwise
912  // we assume that this is already processed option.
913  if ((option_id_null_ == MLM_TRUE) ||
914  (most_recent_option_id_ >= option_id_)) {
915  return;
916  }
917 
918  // Remember current option id as the most recent processed one. We
919  // will be comparing it with option ids in subsequent rows.
920  most_recent_option_id_ = option_id_;
921 
922  // Convert it to string object for easier comparison.
923  std::string space;
924  if (space_null_ == MLM_FALSE) {
925  // Typically, the string values returned by the database are not
926  // NULL terminated.
927  space_[space_length_] = '\0';
928  space.assign(space_);
929  }
930 
931  // If empty or null space provided, use a default top level space.
932  if (space.empty()) {
933  space = (universe_ == Option::V4 ?
935  }
936 
937  // Convert formatted_value to string as well.
938  std::string formatted_value;
939  if (formatted_value_null_ == MLM_FALSE) {
940  formatted_value_[formatted_value_length_] = '\0';
941  formatted_value.assign(formatted_value_);
942  }
943 
944  // Convert user_context to string as well.
945  std::string user_context;
946  if (user_context_null_ == MLM_FALSE) {
947  user_context_[user_context_length_] = '\0';
948  user_context.assign(user_context_);
949  }
950 
951  // Options are held in a binary or textual format in the database.
952  // This is similar to having an option specified in a server
953  // configuration file. Such option is converted to appropriate C++
954  // class, using option definition. Thus, we need to find the
955  // option definition for this option code and option space.
956 
957  // Check if this is a standard option.
958  OptionDefinitionPtr def = LibDHCP::getOptionDef(space, code_);
959 
960  // Otherwise, we may check if this an option encapsulated within the
961  // vendor space.
962  if (!def && (space != DHCP4_OPTION_SPACE) &&
963  (space != DHCP6_OPTION_SPACE)) {
964  uint32_t vendor_id = LibDHCP::optionSpaceToVendorId(space);
965  if (vendor_id > 0) {
966  def = LibDHCP::getVendorOptionDef(universe_, vendor_id, code_);
967  }
968  }
969 
970  // In all other cases, we use runtime option definitions, which
971  // should be also registered within the libdhcp++.
972  if (!def) {
973  def = LibDHCP::getRuntimeOptionDef(space, code_);
974  }
975 
976  OptionPtr option;
977 
978  if (!def) {
979  // If no definition found, we use generic option type.
980  OptionBuffer buf(value_, value_ + value_length_);
981  option.reset(new Option(universe_, code_, buf.begin(),
982  buf.end()));
983  } else {
984  // The option value may be specified in textual or binary format
985  // in the database. If formatted_value is empty, the binary
986  // format is used. Depending on the format we use a different
987  // variant of the optionFactory function.
988  if (formatted_value.empty()) {
989  OptionBuffer buf(value_, value_ + value_length_);
990  option = def->optionFactory(universe_, code_, buf.begin(),
991  buf.end());
992  } else {
993  // Spit the value specified in comma separated values
994  // format.
995  std::vector<std::string> split_vec;
996  boost::split(split_vec, formatted_value, boost::is_any_of(","));
997  option = def->optionFactory(universe_, code_, split_vec);
998  }
999  }
1000 
1001  OptionDescriptor desc(option, persistent_, formatted_value);
1002 
1003  // Set the user context if there is one into the option descriptor.
1004  if (!user_context.empty()) {
1005  try {
1006  ConstElementPtr ctx = Element::fromJSON(user_context);
1007  if (!ctx || (ctx->getType() != Element::map)) {
1008  isc_throw(BadValue, "user context '" << user_context
1009  << "' is no a JSON map");
1010  }
1011  desc.setContext(ctx);
1012  } catch (const isc::data::JSONError& ex) {
1013  isc_throw(BadValue, "user context '" << user_context
1014  << "' is invalid JSON: " << ex.what());
1015  }
1016  }
1017 
1018  cfg->add(desc, space);
1019  }
1020 
1025  void setColumnNames(std::vector<std::string>& columns) {
1026  columns[option_id_index_] = "option_id";
1027  columns[code_index_] = "code";
1028  columns[value_index_] = "value";
1029  columns[formatted_value_index_] = "formatted_value";
1030  columns[space_index_] = "space";
1031  columns[persistent_index_] = "persistent";
1032  columns[user_context_index_] = "user_context";
1033  }
1034 
1041  void setBindFields(std::vector<MYSQL_BIND>& bind) {
1042  // This method is called just before making a new query, so we
1043  // reset the most_recent_option_id_ and other exchange members to
1044  // start over with options processing.
1045  most_recent_option_id_ = 0;
1046 
1047  option_id_ = 0;
1048  code_ = 0;
1049  persistent_ = false;
1050  option_id_null_ = MLM_FALSE;
1051  code_null_ = MLM_FALSE;
1052  value_null_ = MLM_FALSE;
1053  formatted_value_null_ = MLM_FALSE;
1054  space_null_ = MLM_FALSE;
1055  user_context_null_ = MLM_FALSE;
1056 
1057  memset(value_, 0, sizeof(value_));
1058  memset(formatted_value_, 0, sizeof(formatted_value_));
1059  memset(space_, 0, sizeof(space_));
1060  memset(user_context_, 0, sizeof(user_context_));
1061 
1062  // option_id : INT UNSIGNED NOT NULL AUTO_INCREMENT,
1063  bind[option_id_index_].buffer_type = MYSQL_TYPE_LONG;
1064  bind[option_id_index_].buffer = reinterpret_cast<char*>(&option_id_);
1065  bind[option_id_index_].is_unsigned = MLM_TRUE;
1066  bind[option_id_index_].is_null = &option_id_null_;
1067 
1068  // code : TINYINT OR SHORT UNSIGNED NOT NULL
1069  bind[code_index_].buffer_type = MYSQL_TYPE_SHORT;
1070  bind[code_index_].buffer = reinterpret_cast<char*>(&code_);
1071  bind[code_index_].is_unsigned = MLM_TRUE;
1072  bind[code_index_].is_null = &code_null_;
1073 
1074  // value : BLOB NULL
1075  value_length_ = sizeof(value_);
1076  bind[value_index_].buffer_type = MYSQL_TYPE_BLOB;
1077  bind[value_index_].buffer = reinterpret_cast<char*>(value_);
1078  bind[value_index_].buffer_length = value_length_;
1079  bind[value_index_].length = &value_length_;
1080  bind[value_index_].is_null = &value_null_;
1081 
1082  // formatted_value : TEXT NULL
1083  formatted_value_length_ = sizeof(formatted_value_);
1084  bind[formatted_value_index_].buffer_type = MYSQL_TYPE_STRING;
1085  bind[formatted_value_index_].buffer = reinterpret_cast<char*>(formatted_value_);
1086  bind[formatted_value_index_].buffer_length = formatted_value_length_;
1087  bind[formatted_value_index_].length = &formatted_value_length_;
1088  bind[formatted_value_index_].is_null = &formatted_value_null_;
1089 
1090  // space : VARCHAR(128) NULL
1091  space_length_ = sizeof(space_);
1092  bind[space_index_].buffer_type = MYSQL_TYPE_STRING;
1093  bind[space_index_].buffer = reinterpret_cast<char*>(space_);
1094  bind[space_index_].buffer_length = space_length_;
1095  bind[space_index_].length = &space_length_;
1096  bind[space_index_].is_null = &space_null_;
1097 
1098  // persistent : TINYINT(1) NOT NULL DEFAULT 0
1099  bind[persistent_index_].buffer_type = MYSQL_TYPE_TINY;
1100  bind[persistent_index_].buffer = reinterpret_cast<char*>(&persistent_);
1101  bind[persistent_index_].is_unsigned = MLM_TRUE;
1102 
1103  // user_context : TEXT NULL
1104  user_context_length_ = sizeof(user_context_);
1105  bind[user_context_index_].buffer_type = MYSQL_TYPE_STRING;
1106  bind[user_context_index_].buffer = reinterpret_cast<char*>(user_context_);
1107  bind[user_context_index_].buffer_length = user_context_length_;
1108  bind[user_context_index_].length = &user_context_length_;
1109  bind[user_context_index_].is_null = &user_context_null_;
1110  }
1111 
1112  private:
1113 
1115  Option::Universe universe_;
1116 
1118  size_t start_column_;
1119 
1121  uint32_t option_id_;
1122 
1124  uint16_t code_;
1125 
1127  uint8_t value_[OPTION_VALUE_MAX_LEN];
1128 
1130  unsigned long value_length_;
1131 
1133  char formatted_value_[OPTION_FORMATTED_VALUE_MAX_LEN];
1134 
1136  unsigned long formatted_value_length_;
1137 
1139  char space_[OPTION_SPACE_MAX_LEN];
1140 
1142  unsigned long space_length_;
1143 
1146  bool persistent_;
1147 
1149  char user_context_[USER_CONTEXT_MAX_LEN];
1150 
1152  unsigned long user_context_length_;
1153 
1156 
1157  my_bool option_id_null_;
1159 
1161  my_bool code_null_;
1162 
1164  my_bool value_null_;
1165 
1168  my_bool formatted_value_null_;
1169 
1171  my_bool space_null_;
1172 
1174  my_bool user_context_null_;
1176 
1178 
1179  size_t option_id_index_;
1181 
1183  size_t code_index_;
1184 
1186  size_t value_index_;
1187 
1189  size_t formatted_value_index_;
1190 
1192  size_t space_index_;
1193 
1195  size_t persistent_index_;
1197 
1199  size_t user_context_index_;
1200 
1202  uint32_t most_recent_option_id_;
1203  };
1204 
1206  typedef boost::shared_ptr<OptionProcessor> OptionProcessorPtr;
1207 
1208 public:
1209 
1216  enum FetchedOptions {
1217  DHCP4_ONLY,
1218  DHCP6_ONLY,
1219  DHCP4_AND_DHCP6
1220  };
1221 
1230  MySqlHostWithOptionsExchange(const FetchedOptions& fetched_options,
1231  const size_t additional_columns_num = 0)
1232  : MySqlHostExchange(getRequiredColumnsNum(fetched_options)
1233  + additional_columns_num),
1234  opt_proc4_(), opt_proc6_() {
1235 
1236  // Create option processor for DHCPv4 options, if required.
1237  if ((fetched_options == DHCP4_ONLY) ||
1238  (fetched_options == DHCP4_AND_DHCP6)) {
1239  opt_proc4_.reset(new OptionProcessor(Option::V4,
1240  findAvailColumn()));
1241  opt_proc4_->setColumnNames(columns_);
1242  }
1243 
1244  // Create option processor for DHCPv6 options, if required.
1245  if ((fetched_options == DHCP6_ONLY) ||
1246  (fetched_options == DHCP4_AND_DHCP6)) {
1247  opt_proc6_.reset(new OptionProcessor(Option::V6,
1248  findAvailColumn()));
1249  opt_proc6_->setColumnNames(columns_);
1250  }
1251  }
1252 
1261  virtual void processFetchedData(ConstHostCollection& hosts) {
1262  // Holds pointer to the previously parsed host.
1263  HostPtr most_recent_host;
1264  if (!hosts.empty()) {
1265  // Const cast is not very elegant way to deal with it, but
1266  // there is a good reason to use it here. This method is called
1267  // to build a collection of const hosts to be returned to the
1268  // caller. If we wanted to use non-const collection we'd need
1269  // to copy the whole collection before returning it, which has
1270  // performance implications. Alternatively, we could store the
1271  // most recently added host in a class member but this would
1272  // make the code less readable.
1273  most_recent_host = boost::const_pointer_cast<Host>(hosts.back());
1274  }
1275 
1276  // If no host has been parsed yet or we're at the row holding next
1277  // host, we create a new host object and put it at the end of the
1278  // list.
1279  if (!most_recent_host || (most_recent_host->getHostId() < getHostId())) {
1280  HostPtr host = retrieveHost();
1281  hosts.push_back(host);
1282  most_recent_host = host;
1283  }
1284 
1285  // Parse DHCPv4 options if required to do so.
1286  if (opt_proc4_) {
1287  CfgOptionPtr cfg = most_recent_host->getCfgOption4();
1288  opt_proc4_->retrieveOption(cfg);
1289  }
1290 
1291  // Parse DHCPv6 options if required to do so.
1292  if (opt_proc6_) {
1293  CfgOptionPtr cfg = most_recent_host->getCfgOption6();
1294  opt_proc6_->retrieveOption(cfg);
1295  }
1296  }
1297 
1301  virtual std::vector<MYSQL_BIND> createBindForReceive() {
1302  // The following call sets bind_ values between 0 and 8.
1303  static_cast<void>(MySqlHostExchange::createBindForReceive());
1304 
1305  // Bind variables for DHCPv4 options.
1306  if (opt_proc4_) {
1307  opt_proc4_->setBindFields(bind_);
1308  }
1309 
1310  // Bind variables for DHCPv6 options.
1311  if (opt_proc6_) {
1312  opt_proc6_->setBindFields(bind_);
1313  }
1314 
1315  // Add the error flags
1316  setErrorIndicators(bind_, error_);
1317 
1318  return (bind_);
1319  };
1320 
1321 private:
1322 
1334  static size_t getRequiredColumnsNum(const FetchedOptions& fetched_options) {
1335  return (fetched_options == DHCP4_AND_DHCP6 ? 2 * OPTION_COLUMNS :
1336  OPTION_COLUMNS);
1337  }
1338 
1342  OptionProcessorPtr opt_proc4_;
1343 
1347  OptionProcessorPtr opt_proc6_;
1348 };
1349 
1362 class MySqlHostIPv6Exchange : public MySqlHostWithOptionsExchange {
1363 private:
1364 
1366  static const size_t RESERVATION_COLUMNS = 5;
1367 
1368 public:
1369 
1374  MySqlHostIPv6Exchange(const FetchedOptions& fetched_options)
1375  : MySqlHostWithOptionsExchange(fetched_options, RESERVATION_COLUMNS),
1376  reservation_id_(0),
1377  reserv_type_(0), reserv_type_null_(MLM_FALSE),
1378  ipv6_address_buffer_len_(0), prefix_len_(0), iaid_(0),
1379  reservation_id_index_(findAvailColumn()),
1380  address_index_(reservation_id_index_ + 1),
1381  prefix_len_index_(reservation_id_index_ + 2),
1382  type_index_(reservation_id_index_ + 3),
1383  iaid_index_(reservation_id_index_ + 4),
1384  most_recent_reservation_id_(0) {
1385 
1386  memset(ipv6_address_buffer_, 0, sizeof(ipv6_address_buffer_));
1387 
1388  // Provide names of additional columns returned by the queries.
1389  columns_[reservation_id_index_] = "reservation_id";
1390  columns_[address_index_] = "address";
1391  columns_[prefix_len_index_] = "prefix_len";
1392  columns_[type_index_] = "type";
1393  columns_[iaid_index_] = "dhcp6_iaid";
1394  }
1395 
1399  uint32_t getReservationId() const {
1400  if (reserv_type_null_ == MLM_FALSE) {
1401  return (reservation_id_);
1402  }
1403  return (0);
1404  };
1405 
1412  IPv6Resrv retrieveReservation() {
1413  // Set the IPv6 Reservation type (0 = IA_NA, 2 = IA_PD)
1414  IPv6Resrv::Type type = IPv6Resrv::TYPE_NA;
1415 
1416  switch (reserv_type_) {
1417  case 0:
1418  type = IPv6Resrv::TYPE_NA;
1419  break;
1420 
1421  case 2:
1422  type = IPv6Resrv::TYPE_PD;
1423  break;
1424 
1425  default:
1427  "invalid IPv6 reservation type returned: "
1428  << static_cast<int>(reserv_type_)
1429  << ". Only 0 or 2 are allowed.");
1430  }
1431 
1432  ipv6_address_buffer_[ipv6_address_buffer_len_] = '\0';
1433  std::string address = ipv6_address_buffer_;
1434  IPv6Resrv r(type, IOAddress(address), prefix_len_);
1435  return (r);
1436  };
1437 
1457  virtual void processFetchedData(ConstHostCollection& hosts) {
1458 
1459  // Call parent class to fetch host information and options.
1460  MySqlHostWithOptionsExchange::processFetchedData(hosts);
1461 
1462  if (getReservationId() == 0) {
1463  return;
1464  }
1465 
1466  if (hosts.empty()) {
1467  isc_throw(Unexpected, "no host information while retrieving"
1468  " IPv6 reservation");
1469  }
1470  HostPtr host = boost::const_pointer_cast<Host>(hosts.back());
1471 
1472  // If we're dealing with a new reservation, let's add it to the
1473  // host.
1474  if (getReservationId() > most_recent_reservation_id_) {
1475  most_recent_reservation_id_ = getReservationId();
1476 
1477  if (most_recent_reservation_id_ > 0) {
1478  host->addReservation(retrieveReservation());
1479  }
1480  }
1481  }
1482 
1491  virtual std::vector<MYSQL_BIND> createBindForReceive() {
1492  // Reset most recent reservation id value because we're now making
1493  // a new SELECT query.
1494  most_recent_reservation_id_ = 0;
1495 
1496  // Bind values supported by parent classes.
1497  static_cast<void>(MySqlHostWithOptionsExchange::createBindForReceive());
1498 
1499  // reservation_id : INT UNSIGNED NOT NULL AUTO_INCREMENT
1500  bind_[reservation_id_index_].buffer_type = MYSQL_TYPE_LONG;
1501  bind_[reservation_id_index_].buffer = reinterpret_cast<char*>(&reservation_id_);
1502  bind_[reservation_id_index_].is_unsigned = MLM_TRUE;
1503 
1504  // IPv6 address/prefix VARCHAR(39)
1505  ipv6_address_buffer_len_ = sizeof(ipv6_address_buffer_) - 1;
1506  bind_[address_index_].buffer_type = MYSQL_TYPE_STRING;
1507  bind_[address_index_].buffer = ipv6_address_buffer_;
1508  bind_[address_index_].buffer_length = ipv6_address_buffer_len_;
1509  bind_[address_index_].length = &ipv6_address_buffer_len_;
1510 
1511  // prefix_len : TINYINT
1512  bind_[prefix_len_index_].buffer_type = MYSQL_TYPE_TINY;
1513  bind_[prefix_len_index_].buffer = reinterpret_cast<char*>(&prefix_len_);
1514  bind_[prefix_len_index_].is_unsigned = MLM_TRUE;
1515 
1516  // (reservation) type : TINYINT
1517  reserv_type_null_ = MLM_FALSE;
1518  bind_[type_index_].buffer_type = MYSQL_TYPE_TINY;
1519  bind_[type_index_].buffer = reinterpret_cast<char*>(&reserv_type_);
1520  bind_[type_index_].is_unsigned = MLM_TRUE;
1521  bind_[type_index_].is_null = &reserv_type_null_;
1522 
1523  // dhcp6_iaid INT UNSIGNED
1524  bind_[iaid_index_].buffer_type = MYSQL_TYPE_LONG;
1525  bind_[iaid_index_].buffer = reinterpret_cast<char*>(&iaid_);
1526  bind_[iaid_index_].is_unsigned = MLM_TRUE;
1527 
1528  // Add the error flags
1529  setErrorIndicators(bind_, error_);
1530 
1531  return (bind_);
1532  };
1533 
1534 private:
1535 
1537  uint32_t reservation_id_;
1538 
1540  uint8_t reserv_type_;
1541 
1546  my_bool reserv_type_null_;
1547 
1549  char ipv6_address_buffer_[ADDRESS6_TEXT_MAX_LEN + 1];
1550 
1552  unsigned long ipv6_address_buffer_len_;
1553 
1555  uint8_t prefix_len_;
1556 
1558  uint32_t iaid_;
1559 
1561 
1562  size_t reservation_id_index_;
1564 
1566  size_t address_index_;
1567 
1569  size_t prefix_len_index_;
1570 
1572  size_t type_index_;
1573 
1575  size_t iaid_index_;
1576 
1578 
1580  uint32_t most_recent_reservation_id_;
1581 };
1582 
1593 class MySqlIPv6ReservationExchange {
1594 private:
1595 
1597  static const size_t RESRV_COLUMNS = 6;
1598 
1599 public:
1600 
1604  MySqlIPv6ReservationExchange()
1605  : host_id_(0), address_("::"), address_len_(0), prefix_len_(0), type_(0),
1606  iaid_(0), resv_(IPv6Resrv::TYPE_NA, asiolink::IOAddress("::"), 128) {
1607 
1608  // Reset error table.
1609  std::fill(&error_[0], &error_[RESRV_COLUMNS], MLM_FALSE);
1610 
1611  // Set the column names (for error messages)
1612  columns_[0] = "host_id";
1613  columns_[1] = "address";
1614  columns_[2] = "prefix_len";
1615  columns_[3] = "type";
1616  columns_[4] = "dhcp6_iaid";
1617  BOOST_STATIC_ASSERT(4 < RESRV_COLUMNS);
1618  }
1619 
1634  std::vector<MYSQL_BIND> createBindForSend(const IPv6Resrv& resv,
1635  const HostID& id,
1636  const bool unique_ip) {
1637 
1638  // Store the values to ensure they remain valid.
1639  resv_ = resv;
1640  host_id_ = id;
1641 
1642  // Initialize prior to constructing the array of MYSQL_BIND structures.
1643  // It sets all fields, including is_null, to zero, so we need to set
1644  // is_null only if it should be true. This gives up minor performance
1645  // benefit while being safe approach. For improved readability, the
1646  // code that explicitly sets is_null is there, but is commented out.
1647  memset(bind_, 0, sizeof(bind_));
1648 
1649  // Set up the structures for the various components of the host structure.
1650 
1651  try {
1652  // address VARCHAR(39)
1653  address_ = resv.getPrefix().toText();
1654  address_len_ = address_.length();
1655  bind_[0].buffer_type = MYSQL_TYPE_BLOB;
1656  bind_[0].buffer = reinterpret_cast<char*>
1657  (const_cast<char*>(address_.c_str()));
1658  bind_[0].buffer_length = address_len_;
1659  bind_[0].length = &address_len_;
1660 
1661  // prefix_len tinyint
1662  prefix_len_ = resv.getPrefixLen();
1663  bind_[1].buffer_type = MYSQL_TYPE_TINY;
1664  bind_[1].buffer = reinterpret_cast<char*>(&prefix_len_);
1665  bind_[1].is_unsigned = MLM_TRUE;
1666 
1667  // type tinyint
1668  // See lease6_types for values (0 = IA_NA, 1 = IA_TA, 2 = IA_PD)
1669  type_ = resv.getType() == IPv6Resrv::TYPE_NA ? 0 : 2;
1670  bind_[2].buffer_type = MYSQL_TYPE_TINY;
1671  bind_[2].buffer = reinterpret_cast<char*>(&type_);
1672  bind_[2].is_unsigned = MLM_TRUE;
1673 
1674  // dhcp6_iaid INT UNSIGNED
1676  iaid_ = 0;
1677  bind_[3].buffer_type = MYSQL_TYPE_LONG;
1678  bind_[3].buffer = reinterpret_cast<char*>(&iaid_);
1679  bind_[3].is_unsigned = MLM_TRUE;
1680 
1681  // host_id INT UNSIGNED NOT NULL
1682  bind_[4].buffer_type = MYSQL_TYPE_LONG;
1683  bind_[4].buffer = reinterpret_cast<char*>(&host_id_);
1684  bind_[4].is_unsigned = MLM_TRUE;
1685 
1686  } catch (const std::exception& ex) {
1688  "Could not create bind array from IPv6 Reservation: "
1689  << resv_.toText() << ", reason: " << ex.what());
1690  }
1691 
1692  // Add the data to the vector. Note the end element is one after the
1693  // end of the array.
1694  // RESRV_COLUMNS -1 as we do not set reservation_id.
1695  std::vector<MYSQL_BIND> vec(&bind_[0], &bind_[RESRV_COLUMNS-1]);
1696 
1697  // When checking whether the IP is unique we need to bind the IPv6 address
1698  // and prefix length at the end of the query as it has additional binding
1699  // for the IPv6 address and prefix length.
1700  if (unique_ip) {
1701  vec.push_back(bind_[0]); // address
1702  vec.push_back(bind_[1]); // prefix_len
1703  }
1704 
1705  return (vec);
1706  }
1707 
1708 private:
1709 
1711  uint64_t host_id_;
1712 
1714  std::string address_;
1715 
1717  unsigned long address_len_;
1718 
1720  uint8_t prefix_len_;
1721 
1723  uint8_t type_;
1724 
1726  uint8_t iaid_;
1727 
1729  IPv6Resrv resv_;
1730 
1732  MYSQL_BIND bind_[RESRV_COLUMNS];
1733 
1735  std::string columns_[RESRV_COLUMNS];
1736 
1739  my_bool error_[RESRV_COLUMNS];
1740 };
1741 
1745 class MySqlOptionExchange {
1746 private:
1747 
1749  static const size_t OPTION_COLUMNS = 10;
1750 
1751 public:
1752 
1754  MySqlOptionExchange()
1755  : type_(0), value_len_(0), formatted_value_len_(0), space_(),
1756  space_len_(0), persistent_(false), user_context_(),
1757  user_context_len_(0), client_class_(), client_class_len_(0),
1758  subnet_id_(SUBNET_ID_UNUSED), host_id_(0), option_() {
1759 
1760  BOOST_STATIC_ASSERT(9 < OPTION_COLUMNS);
1761  }
1762 
1766  std::vector<MYSQL_BIND> createBindForSend(const OptionDescriptor& opt_desc,
1767  const std::string& opt_space,
1768  const Optional<SubnetID>& subnet_id,
1769  const HostID& host_id) {
1770 
1771  // Hold pointer to the option to make sure it remains valid until
1772  // we complete a query.
1773  option_ = opt_desc.option_;
1774 
1775  memset(bind_, 0, sizeof(bind_));
1776 
1777  try {
1778  // option_id: INT UNSIGNED NOT NULL
1779  // The option_id is auto_incremented, so we need to pass the NULL
1780  // value.
1781  bind_[0].buffer_type = MYSQL_TYPE_NULL;
1782 
1783  // code: SMALLINT UNSIGNED NOT NULL
1784  type_ = option_->getType();
1785  bind_[1].buffer_type = MYSQL_TYPE_SHORT;
1786  bind_[1].buffer = reinterpret_cast<char*>(&type_);
1787  bind_[1].is_unsigned = MLM_TRUE;
1788 
1789  // value: BLOB NULL
1790  if (opt_desc.formatted_value_.empty() &&
1791  (opt_desc.option_->len() > opt_desc.option_->getHeaderLen())) {
1792  // The formatted_value is empty and the option value is
1793  // non-empty so we need to prepare on-wire format for the
1794  // option and store it in the database as a blob.
1795  OutputBuffer buf(opt_desc.option_->len());
1796  opt_desc.option_->pack(buf);
1797  const char* buf_ptr = static_cast<const char*>(buf.getData());
1798  value_.assign(buf_ptr + opt_desc.option_->getHeaderLen(),
1799  buf_ptr + buf.getLength());
1800  value_len_ = value_.size();
1801  bind_[2].buffer_type = MYSQL_TYPE_BLOB;
1802  bind_[2].buffer = &value_[0];
1803  bind_[2].buffer_length = value_len_;
1804  bind_[2].length = &value_len_;
1805 
1806  } else {
1807  // No value or formatted_value specified. In this case, the
1808  // value blob is NULL.
1809  value_.clear();
1810  bind_[2].buffer_type = MYSQL_TYPE_NULL;
1811  }
1812 
1813  // formatted_value: TEXT NULL,
1814  if (!opt_desc.formatted_value_.empty()) {
1815  formatted_value_len_ = opt_desc.formatted_value_.size();
1816  bind_[3].buffer_type = MYSQL_TYPE_STRING;
1817  bind_[3].buffer = const_cast<char*>(opt_desc.formatted_value_.c_str());
1818  bind_[3].buffer_length = formatted_value_len_;
1819  bind_[3].length = &formatted_value_len_;
1820 
1821  } else {
1822  bind_[3].buffer_type = MYSQL_TYPE_NULL;
1823  }
1824 
1825  // space: VARCHAR(128) NULL
1826  space_ = opt_space;
1827  space_len_ = space_.size();
1828  bind_[4].buffer_type = MYSQL_TYPE_STRING;
1829  bind_[4].buffer = const_cast<char*>(space_.c_str());
1830  bind_[4].buffer_length = space_len_;
1831  bind_[4].length = &space_len_;
1832 
1833  // persistent: TINYINT(1) NOT NULL DEFAULT 0
1834  persistent_ = opt_desc.persistent_;
1835  bind_[5].buffer_type = MYSQL_TYPE_TINY;
1836  bind_[5].buffer = reinterpret_cast<char*>(&persistent_);
1837  bind_[5].is_unsigned = MLM_TRUE;
1838 
1839  // user_context: TEST NULL,
1840  ConstElementPtr ctx = opt_desc.getContext();
1841  if (ctx) {
1842  user_context_ = ctx->str();
1843  user_context_len_ = user_context_.size();
1844  bind_[6].buffer_type = MYSQL_TYPE_STRING;
1845  bind_[6].buffer = const_cast<char*>(user_context_.c_str());
1846  bind_[6].buffer_length = user_context_len_;
1847  bind_[6].length = &user_context_len_;
1848  } else {
1849  bind_[6].buffer_type = MYSQL_TYPE_NULL;
1850  }
1851 
1852  // dhcp_client_class: VARCHAR(128) NULL
1853  client_class_len_ = client_class_.size();
1854  bind_[7].buffer_type = MYSQL_TYPE_STRING;
1855  bind_[7].buffer = const_cast<char*>(client_class_.c_str());
1856  bind_[7].buffer_length = client_class_len_;
1857  bind_[7].length = &client_class_len_;
1858 
1859  // dhcp4_subnet_id: INT UNSIGNED NULL
1860  if (!subnet_id.unspecified()) {
1861  subnet_id_ = subnet_id;
1862  bind_[8].buffer_type = MYSQL_TYPE_LONG;
1863  bind_[8].buffer = reinterpret_cast<char*>(subnet_id_);
1864  bind_[8].is_unsigned = MLM_TRUE;
1865 
1866  } else {
1867  bind_[8].buffer_type = MYSQL_TYPE_NULL;
1868  }
1869 
1870  // host_id: INT UNSIGNED NOT NULL
1871  host_id_ = host_id;
1872  bind_[9].buffer_type = MYSQL_TYPE_LONG;
1873  bind_[9].buffer = reinterpret_cast<char*>(&host_id_);
1874  bind_[9].is_unsigned = MLM_TRUE;
1875 
1876  } catch (const std::exception& ex) {
1878  "Could not create bind array for inserting DHCP "
1879  "option: " << option_->toText() << ", reason: "
1880  << ex.what());
1881  }
1882 
1883  return (std::vector<MYSQL_BIND>(&bind_[0], &bind_[OPTION_COLUMNS]));
1884  }
1885 
1886 private:
1887 
1889  uint16_t type_;
1890 
1892  std::vector<uint8_t> value_;
1893 
1895  unsigned long value_len_;
1896 
1898  unsigned long formatted_value_len_;
1899 
1901  std::string space_;
1902 
1904  unsigned long space_len_;
1905 
1908  bool persistent_;
1909 
1911  std::string user_context_;
1912 
1914  unsigned long user_context_len_;
1915 
1917  std::string client_class_;
1918 
1920  unsigned long client_class_len_;
1921 
1923  uint32_t subnet_id_;
1924 
1926  uint32_t host_id_;
1927 
1929  OptionPtr option_;
1930 
1932  MYSQL_BIND bind_[OPTION_COLUMNS];
1933 };
1934 
1935 } // namespace
1936 
1937 namespace isc {
1938 namespace dhcp {
1939 
1950 public:
1951 
1958  IOServiceAccessorPtr io_service_accessor,
1959  db::DbCallback db_reconnect_callback);
1960 
1965 
1968  boost::shared_ptr<MySqlHostWithOptionsExchange> host_ipv4_exchange_;
1969 
1972  boost::shared_ptr<MySqlHostIPv6Exchange> host_ipv6_exchange_;
1973 
1977  boost::shared_ptr<MySqlHostIPv6Exchange> host_ipv46_exchange_;
1978 
1981  boost::shared_ptr<MySqlIPv6ReservationExchange> host_ipv6_reservation_exchange_;
1982 
1986  boost::shared_ptr<MySqlOptionExchange> host_option_exchange_;
1987 
1990 
1993 };
1994 
2002 public:
2003 
2005  std::vector<MySqlHostContextPtr> pool_;
2006 
2008  std::mutex mutex_;
2009 };
2010 
2012 typedef boost::shared_ptr<MySqlHostContextPool> MySqlHostContextPoolPtr;
2013 
2016 public:
2017 
2027  GET_HOST_DHCPID, // Gets hosts by host identifier
2028  GET_HOST_ADDR, // Gets hosts by IPv4 address
2029  GET_HOST_SUBID4_DHCPID, // Gets host by IPv4 SubnetID, HW address/DUID
2030  GET_HOST_SUBID6_DHCPID, // Gets host by IPv6 SubnetID, HW address/DUID
2031  GET_HOST_SUBID_ADDR, // Gets host by IPv4 SubnetID and IPv4 address
2032  GET_HOST_PREFIX, // Gets host by IPv6 prefix
2033  GET_HOST_SUBID6_ADDR, // Gets host by IPv6 SubnetID and IPv6 prefix
2034  GET_HOST_SUBID4, // Gets hosts by IPv4 SubnetID
2035  GET_HOST_SUBID6, // Gets hosts by IPv6 SubnetID
2036  GET_HOST_HOSTNAME, // Gets hosts by hostname
2037  GET_HOST_HOSTNAME_SUBID4, // Gets hosts by hostname and IPv4 SubnetID
2038  GET_HOST_HOSTNAME_SUBID6, // Gets hosts by hostname and IPv6 SubnetID
2039  GET_HOST_SUBID4_PAGE, // Gets hosts by IPv4 SubnetID beginning by HID
2040  GET_HOST_SUBID6_PAGE, // Gets hosts by IPv6 SubnetID beginning by HID
2041  GET_HOST_PAGE4, // Gets v4 hosts beginning by HID
2042  GET_HOST_PAGE6, // Gets v6 hosts beginning by HID
2043  INSERT_HOST_NON_UNIQUE_IP, // Insert new host to collection with allowing IP duplicates
2044  INSERT_HOST_UNIQUE_IP, // Insert new host to collection with checking for IP duplicates
2045  INSERT_V6_RESRV_NON_UNIQUE,// Insert v6 reservation without checking that it is unique
2046  INSERT_V6_RESRV_UNIQUE, // Insert v6 reservation with checking that it is unique
2047  INSERT_V4_HOST_OPTION, // Insert DHCPv4 option
2048  INSERT_V6_HOST_OPTION, // Insert DHCPv6 option
2049  DEL_HOST_ADDR4, // Delete v4 host (subnet-id, addr4)
2050  DEL_HOST_ADDR6, // Delete v6 host (subnet-id, addr6)
2051  DEL_HOST_SUBID4_ID, // Delete v4 host (subnet-id, ident.type, identifier)
2052  DEL_HOST_SUBID6_ID, // Delete v6 host (subnet-id, ident.type, identifier)
2053  NUM_STATEMENTS // Number of statements
2054  };
2055 
2061  static const StatementIndex WRITE_STMTS_BEGIN = INSERT_HOST_NON_UNIQUE_IP;
2062 
2068 
2071 
2094  static bool dbReconnect(ReconnectCtlPtr db_reconnect_ctl);
2095 
2105  MySqlHostContextPtr createContext() const;
2106 
2118  std::pair<uint32_t, uint32_t> getVersion() const;
2119 
2128  void addStatement(MySqlHostContextPtr& ctx,
2130  std::vector<MYSQL_BIND>& bind);
2131 
2140  bool delStatement(MySqlHostContextPtr& ctx,
2141  StatementIndex stindex,
2142  MYSQL_BIND* bind);
2143 
2149  void addResv(MySqlHostContextPtr& ctx,
2150  const IPv6Resrv& resv,
2151  const HostID& id);
2152 
2162  void addOption(MySqlHostContextPtr& ctx,
2164  const OptionDescriptor& opt_desc,
2165  const std::string& opt_space,
2166  const Optional<SubnetID>& subnet_id,
2167  const HostID& host_id);
2168 
2176  void addOptions(MySqlHostContextPtr& ctx,
2177  const StatementIndex& stindex,
2178  const ConstCfgOptionPtr& options_cfg,
2179  const uint64_t host_id);
2180 
2192  void checkError(MySqlHostContextPtr& ctx,
2193  const int status,
2194  const StatementIndex index,
2195  const char* what) const;
2196 
2215  void getHostCollection(MySqlHostContextPtr& ctx,
2216  StatementIndex stindex,
2217  MYSQL_BIND* bind,
2218  boost::shared_ptr<MySqlHostExchange> exchange,
2219  ConstHostCollection& result,
2220  bool single) const;
2221 
2239  ConstHostPtr getHost(MySqlHostContextPtr& ctx,
2240  const SubnetID& subnet_id,
2241  const Host::IdentifierType& identifier_type,
2242  const uint8_t* identifier_begin,
2243  const size_t identifier_len,
2244  StatementIndex stindex,
2245  boost::shared_ptr<MySqlHostExchange> exchange) const;
2246 
2256  void checkReadOnly(MySqlHostContextPtr& ctx) const;
2257 
2260 
2264 
2266  MySqlHostContextPoolPtr pool_;
2267 
2271 
2273  std::string timer_name_;
2274 };
2275 
2276 namespace {
2277 
2279 typedef boost::array<TaggedStatement, MySqlHostDataSourceImpl::NUM_STATEMENTS>
2280 TaggedStatementArray;
2281 
2284 TaggedStatementArray tagged_statements = { {
2285  // Retrieves host information, IPv6 reservations and both DHCPv4 and
2286  // DHCPv6 options associated with the host. The LEFT JOIN clause is used
2287  // to retrieve information from 4 different tables using a single query.
2288  // Hence, this query returns multiple rows for a single host.
2289  {MySqlHostDataSourceImpl::GET_HOST_DHCPID,
2290  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2291  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, "
2292  "h.hostname, h.dhcp4_client_classes, h.dhcp6_client_classes, "
2293  "h.user_context, "
2294  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2295  "h.dhcp4_boot_file_name, h.auth_key, "
2296  "o4.option_id, o4.code, o4.value, o4.formatted_value, o4.space, "
2297  "o4.persistent, o4.user_context, "
2298  "o6.option_id, o6.code, o6.value, o6.formatted_value, o6.space, "
2299  "o6.persistent, o6.user_context, "
2300  "r.reservation_id, r.address, r.prefix_len, r.type, "
2301  "r.dhcp6_iaid "
2302  "FROM hosts AS h "
2303  "LEFT JOIN dhcp4_options AS o4 "
2304  "ON h.host_id = o4.host_id "
2305  "LEFT JOIN dhcp6_options AS o6 "
2306  "ON h.host_id = o6.host_id "
2307  "LEFT JOIN ipv6_reservations AS r "
2308  "ON h.host_id = r.host_id "
2309  "WHERE dhcp_identifier = ? AND dhcp_identifier_type = ? "
2310  "ORDER BY h.host_id, o4.option_id, o6.option_id, r.reservation_id"},
2311 
2312  // Retrieves host information along with the DHCPv4 options associated with
2313  // it. Left joining the dhcp4_options table results in multiple rows being
2314  // returned for the same host. The host is retrieved by IPv4 address.
2315  {MySqlHostDataSourceImpl::GET_HOST_ADDR,
2316  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2317  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2318  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2319  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2320  "h.dhcp4_boot_file_name, h.auth_key, "
2321  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2322  "o.persistent, o.user_context "
2323  "FROM hosts AS h "
2324  "LEFT JOIN dhcp4_options AS o "
2325  "ON h.host_id = o.host_id "
2326  "WHERE ipv4_address = ? "
2327  "ORDER BY h.host_id, o.option_id"},
2328 
2329  // Retrieves host information and DHCPv4 options using subnet identifier
2330  // and client's identifier. Left joining the dhcp4_options table results in
2331  // multiple rows being returned for the same host.
2332  {MySqlHostDataSourceImpl::GET_HOST_SUBID4_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, h.hostname, "
2335  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2336  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2337  "h.dhcp4_boot_file_name, h.auth_key, "
2338  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2339  "o.persistent, o.user_context "
2340  "FROM hosts AS h "
2341  "LEFT JOIN dhcp4_options AS o "
2342  "ON h.host_id = o.host_id "
2343  "WHERE h.dhcp4_subnet_id = ? AND h.dhcp_identifier_type = ? "
2344  "AND h.dhcp_identifier = ? "
2345  "ORDER BY h.host_id, o.option_id"},
2346 
2347  // Retrieves host information, IPv6 reservations and DHCPv6 options
2348  // associated with a host. The number of rows returned is a multiplication
2349  // of number of IPv6 reservations and DHCPv6 options.
2350  {MySqlHostDataSourceImpl::GET_HOST_SUBID6_DHCPID,
2351  "SELECT h.host_id, h.dhcp_identifier, "
2352  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2353  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2354  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2355  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2356  "h.dhcp4_boot_file_name, h.auth_key, "
2357  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2358  "o.persistent, o.user_context, "
2359  "r.reservation_id, r.address, r.prefix_len, r.type, "
2360  "r.dhcp6_iaid "
2361  "FROM hosts AS h "
2362  "LEFT JOIN dhcp6_options AS o "
2363  "ON h.host_id = o.host_id "
2364  "LEFT JOIN ipv6_reservations AS r "
2365  "ON h.host_id = r.host_id "
2366  "WHERE h.dhcp6_subnet_id = ? AND h.dhcp_identifier_type = ? "
2367  "AND h.dhcp_identifier = ? "
2368  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2369 
2370  // Retrieves host information and DHCPv4 options for the host using subnet
2371  // identifier and IPv4 reservation. Left joining the dhcp4_options table
2372  // results in multiple rows being returned for the host. The number of
2373  // rows depends on the number of options defined for the host.
2374  {MySqlHostDataSourceImpl::GET_HOST_SUBID_ADDR,
2375  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2376  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2377  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2378  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2379  "h.dhcp4_boot_file_name, h.auth_key, "
2380  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2381  "o.persistent, o.user_context "
2382  "FROM hosts AS h "
2383  "LEFT JOIN dhcp4_options AS o "
2384  "ON h.host_id = o.host_id "
2385  "WHERE h.dhcp4_subnet_id = ? AND h.ipv4_address = ? "
2386  "ORDER BY h.host_id, o.option_id"},
2387 
2388  // Retrieves host information, IPv6 reservations and DHCPv6 options
2389  // associated with a host using prefix and prefix length. This query
2390  // returns host information for a single host. However, multiple rows
2391  // are returned due to left joining IPv6 reservations and DHCPv6 options.
2392  // The number of rows returned is multiplication of number of existing
2393  // IPv6 reservations and DHCPv6 options.
2394  {MySqlHostDataSourceImpl::GET_HOST_PREFIX,
2395  "SELECT h.host_id, h.dhcp_identifier, "
2396  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2397  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2398  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2399  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2400  "h.dhcp4_boot_file_name, h.auth_key, "
2401  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2402  "o.persistent, o.user_context,"
2403  "r.reservation_id, r.address, r.prefix_len, r.type, "
2404  "r.dhcp6_iaid "
2405  "FROM hosts AS h "
2406  "LEFT JOIN dhcp6_options AS o "
2407  "ON h.host_id = o.host_id "
2408  "LEFT JOIN ipv6_reservations AS r "
2409  "ON h.host_id = r.host_id "
2410  "WHERE h.host_id = "
2411  "( SELECT host_id FROM ipv6_reservations "
2412  "WHERE address = ? AND prefix_len = ? ) "
2413  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2414 
2415  // Retrieves host information, IPv6 reservations and DHCPv6 options
2416  // associated with a host using IPv6 subnet id and prefix. This query
2417  // returns host information for a single host. However, multiple rows
2418  // are returned due to left joining IPv6 reservations and DHCPv6 options.
2419  // The number of rows returned is multiplication of number of existing
2420  // IPv6 reservations and DHCPv6 options.
2421  {MySqlHostDataSourceImpl::GET_HOST_SUBID6_ADDR,
2422  "SELECT h.host_id, h.dhcp_identifier, "
2423  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2424  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2425  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2426  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2427  "h.dhcp4_boot_file_name, h.auth_key, "
2428  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2429  "o.persistent, o.user_context, "
2430  "r.reservation_id, r.address, r.prefix_len, r.type, "
2431  "r.dhcp6_iaid "
2432  "FROM hosts AS h "
2433  "LEFT JOIN dhcp6_options AS o "
2434  "ON h.host_id = o.host_id "
2435  "LEFT JOIN ipv6_reservations AS r "
2436  "ON h.host_id = r.host_id "
2437  "WHERE h.dhcp6_subnet_id = ? AND r.address = ? "
2438  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2439 
2440  // Retrieves host information along with the DHCPv4 options associated with
2441  // it. Left joining the dhcp4_options table results in multiple rows being
2442  // returned for the same host. Hosts are retrieved by IPv4 subnet id.
2443  {MySqlHostDataSourceImpl::GET_HOST_SUBID4,
2444  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2445  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2446  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2447  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2448  "h.dhcp4_boot_file_name, h.auth_key, "
2449  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2450  "o.persistent, o.user_context "
2451  "FROM hosts AS h "
2452  "LEFT JOIN dhcp4_options AS o "
2453  "ON h.host_id = o.host_id "
2454  "WHERE h.dhcp4_subnet_id = ? "
2455  "ORDER BY h.host_id, o.option_id"},
2456 
2457  // Retrieves host information, IPv6 reservations and DHCPv6 options
2458  // associated with a host. The number of rows returned is a multiplication
2459  // of number of IPv6 reservations and DHCPv6 options. Hosts are retrieved
2460  // by IPv6 subnet id.
2461  {MySqlHostDataSourceImpl::GET_HOST_SUBID6,
2462  "SELECT h.host_id, h.dhcp_identifier, "
2463  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2464  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2465  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2466  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2467  "h.dhcp4_boot_file_name, h.auth_key, "
2468  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2469  "o.persistent, o.user_context, "
2470  "r.reservation_id, r.address, r.prefix_len, r.type, "
2471  "r.dhcp6_iaid "
2472  "FROM hosts AS h "
2473  "LEFT JOIN dhcp6_options AS o "
2474  "ON h.host_id = o.host_id "
2475  "LEFT JOIN ipv6_reservations AS r "
2476  "ON h.host_id = r.host_id "
2477  "WHERE h.dhcp6_subnet_id = ? "
2478  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2479 
2480  // Retrieves host information, IPv6 reservations and both DHCPv4 and
2481  // DHCPv6 options associated with the host. The LEFT JOIN clause is used
2482  // to retrieve information from 4 different tables using a single query.
2483  // Hence, this query returns multiple rows for a single host.
2484  {MySqlHostDataSourceImpl::GET_HOST_HOSTNAME,
2485  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2486  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, "
2487  "h.hostname, h.dhcp4_client_classes, h.dhcp6_client_classes, "
2488  "h.user_context, "
2489  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2490  "h.dhcp4_boot_file_name, h.auth_key, "
2491  "o4.option_id, o4.code, o4.value, o4.formatted_value, o4.space, "
2492  "o4.persistent, o4.user_context, "
2493  "o6.option_id, o6.code, o6.value, o6.formatted_value, o6.space, "
2494  "o6.persistent, o6.user_context, "
2495  "r.reservation_id, r.address, r.prefix_len, r.type, "
2496  "r.dhcp6_iaid "
2497  "FROM hosts AS h "
2498  "LEFT JOIN dhcp4_options AS o4 "
2499  "ON h.host_id = o4.host_id "
2500  "LEFT JOIN dhcp6_options AS o6 "
2501  "ON h.host_id = o6.host_id "
2502  "LEFT JOIN ipv6_reservations AS r "
2503  "ON h.host_id = r.host_id "
2504  "WHERE h.hostname = ? "
2505  "ORDER BY h.host_id, o4.option_id, o6.option_id, r.reservation_id"},
2506 
2507  // Retrieves host information and DHCPv4 options using hostname and
2508  // subnet identifier. Left joining the dhcp4_options table results in
2509  // multiple rows being returned for the same host.
2510  {MySqlHostDataSourceImpl::GET_HOST_HOSTNAME_SUBID4,
2511  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2512  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2513  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2514  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2515  "h.dhcp4_boot_file_name, h.auth_key, "
2516  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2517  "o.persistent, o.user_context "
2518  "FROM hosts AS h "
2519  "LEFT JOIN dhcp4_options AS o "
2520  "ON h.host_id = o.host_id "
2521  "WHERE h.hostname = ? AND h.dhcp4_subnet_id = ? "
2522  "ORDER BY h.host_id, o.option_id"},
2523 
2524  // Retrieves host information, IPv6 reservations and DHCPv6 options
2525  // using hostname and subnet identifier. The number of rows returned
2526  // is a multiplication of number of IPv6 reservations and DHCPv6 options.
2527  {MySqlHostDataSourceImpl::GET_HOST_HOSTNAME_SUBID6,
2528  "SELECT h.host_id, h.dhcp_identifier, "
2529  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2530  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2531  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2532  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2533  "h.dhcp4_boot_file_name, h.auth_key, "
2534  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2535  "o.persistent, o.user_context, "
2536  "r.reservation_id, r.address, r.prefix_len, r.type, "
2537  "r.dhcp6_iaid "
2538  "FROM hosts AS h "
2539  "LEFT JOIN dhcp6_options AS o "
2540  "ON h.host_id = o.host_id "
2541  "LEFT JOIN ipv6_reservations AS r "
2542  "ON h.host_id = r.host_id "
2543  "WHERE h.hostname = ? AND h.dhcp6_subnet_id = ? "
2544  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2545 
2546  // Retrieves host information along with the DHCPv4 options associated with
2547  // it. Left joining the dhcp4_options table results in multiple rows being
2548  // returned for the same host. Hosts are retrieved by IPv4 subnet id
2549  // and with a host id greater than the start one.
2550  // The number of hosts returned is lower or equal to the limit.
2551  {MySqlHostDataSourceImpl::GET_HOST_SUBID4_PAGE,
2552  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2553  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2554  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2555  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2556  "h.dhcp4_boot_file_name, h.auth_key, "
2557  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2558  "o.persistent, o.user_context "
2559  "FROM ( SELECT * FROM hosts AS h "
2560  "WHERE h.dhcp4_subnet_id = ? AND h.host_id > ? "
2561  "ORDER BY h.host_id "
2562  "LIMIT ? ) AS h "
2563  "LEFT JOIN dhcp4_options AS o "
2564  "ON h.host_id = o.host_id "
2565  "ORDER BY h.host_id, o.option_id"},
2566 
2567  // Retrieves host information, IPv6 reservations and DHCPv6 options
2568  // associated with a host. The number of rows returned is a multiplication
2569  // of number of IPv6 reservations and DHCPv6 options. Hosts are retrieved
2570  // by IPv6 subnet id and with a host id greater than the start one.
2571  // The number of hosts returned is lower or equal to the limit.
2572  {MySqlHostDataSourceImpl::GET_HOST_SUBID6_PAGE,
2573  "SELECT h.host_id, h.dhcp_identifier, "
2574  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2575  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2576  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2577  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2578  "h.dhcp4_boot_file_name, h.auth_key, "
2579  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2580  "o.persistent, o.user_context, "
2581  "r.reservation_id, r.address, r.prefix_len, r.type, "
2582  "r.dhcp6_iaid "
2583  "FROM ( SELECT * FROM hosts AS h "
2584  "WHERE h.dhcp6_subnet_id = ? AND h.host_id > ? "
2585  "ORDER BY h.host_id "
2586  "LIMIT ? ) AS h "
2587  "LEFT JOIN dhcp6_options AS o "
2588  "ON h.host_id = o.host_id "
2589  "LEFT JOIN ipv6_reservations AS r "
2590  "ON h.host_id = r.host_id "
2591  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2592 
2593  // Retrieves host information along with the DHCPv4 options associated with
2594  // it. Left joining the dhcp4_options table results in multiple rows being
2595  // returned for the same host. Hosts are retrieved with a host id greater
2596  // than the start one.
2597  // The number of hosts returned is lower or equal to the limit.
2598  {MySqlHostDataSourceImpl::GET_HOST_PAGE4,
2599  "SELECT h.host_id, h.dhcp_identifier, h.dhcp_identifier_type, "
2600  "h.dhcp4_subnet_id, h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2601  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2602  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2603  "h.dhcp4_boot_file_name, h.auth_key, "
2604  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2605  "o.persistent, o.user_context "
2606  "FROM ( SELECT * FROM hosts AS h "
2607  "WHERE h.host_id > ? "
2608  "ORDER BY h.host_id "
2609  "LIMIT ? ) AS h "
2610  "LEFT JOIN dhcp4_options AS o "
2611  "ON h.host_id = o.host_id "
2612  "ORDER BY h.host_id, o.option_id"},
2613 
2614  // Retrieves host information, IPv6 reservations and DHCPv6 options
2615  // associated with a host. The number of rows returned is a multiplication
2616  // of number of IPv6 reservations and DHCPv6 options. Hosts are retrieved
2617  // with a host id greater than the start one.
2618  // The number of hosts returned is lower or equal to the limit.
2619  {MySqlHostDataSourceImpl::GET_HOST_PAGE6,
2620  "SELECT h.host_id, h.dhcp_identifier, "
2621  "h.dhcp_identifier_type, h.dhcp4_subnet_id, "
2622  "h.dhcp6_subnet_id, h.ipv4_address, h.hostname, "
2623  "h.dhcp4_client_classes, h.dhcp6_client_classes, h.user_context, "
2624  "h.dhcp4_next_server, h.dhcp4_server_hostname, "
2625  "h.dhcp4_boot_file_name, h.auth_key, "
2626  "o.option_id, o.code, o.value, o.formatted_value, o.space, "
2627  "o.persistent, o.user_context, "
2628  "r.reservation_id, r.address, r.prefix_len, r.type, "
2629  "r.dhcp6_iaid "
2630  "FROM ( SELECT * FROM hosts AS h "
2631  "WHERE h.host_id > ? "
2632  "ORDER BY h.host_id "
2633  "LIMIT ? ) AS h "
2634  "LEFT JOIN dhcp6_options AS o "
2635  "ON h.host_id = o.host_id "
2636  "LEFT JOIN ipv6_reservations AS r "
2637  "ON h.host_id = r.host_id "
2638  "ORDER BY h.host_id, o.option_id, r.reservation_id"},
2639 
2640  // Inserts a host into the 'hosts' table without checking that there is
2641  // a reservation for the IP address.
2642  {MySqlHostDataSourceImpl::INSERT_HOST_NON_UNIQUE_IP,
2643  "INSERT INTO hosts(host_id, dhcp_identifier, dhcp_identifier_type, "
2644  "dhcp4_subnet_id, dhcp6_subnet_id, ipv4_address, hostname, "
2645  "dhcp4_client_classes, dhcp6_client_classes, "
2646  "user_context, dhcp4_next_server, "
2647  "dhcp4_server_hostname, dhcp4_boot_file_name, auth_key) "
2648  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"},
2649 
2650  // Inserts a host into the 'hosts' table with checking that reserved IP
2651  // address is unique. The innermost query checks if there is at least
2652  // one host for the given IP/subnet combination. For checking whether
2653  // hosts exists or not it doesn't matter if we select actual columns,
2654  // thus SELECT 1 was used as an optimization to avoid selecting data
2655  // that will be ignored anyway. If the host does not exist the new
2656  // host is inserted. DUAL is a special MySQL table from which we can
2657  // select the values to be inserted. If the host with the given IP
2658  // address already exists the new host won't be inserted. The caller
2659  // can check the number of affected rows to detect that there was
2660  // a duplicate host in the database.
2661  {MySqlHostDataSourceImpl::INSERT_HOST_UNIQUE_IP,
2662  "INSERT INTO hosts(host_id, dhcp_identifier, dhcp_identifier_type, "
2663  "dhcp4_subnet_id, dhcp6_subnet_id, ipv4_address, hostname, "
2664  "dhcp4_client_classes, dhcp6_client_classes, "
2665  "user_context, dhcp4_next_server, "
2666  "dhcp4_server_hostname, dhcp4_boot_file_name, auth_key) "
2667  "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? FROM DUAL "
2668  "WHERE NOT EXISTS ("
2669  "SELECT 1 FROM hosts "
2670  "WHERE ipv4_address = ? AND dhcp4_subnet_id = ? "
2671  "LIMIT 1"
2672  ")"},
2673 
2674  // Inserts a single IPv6 reservation into 'reservations' table without
2675  // checking that the inserted reservation is unique.
2676  {MySqlHostDataSourceImpl::INSERT_V6_RESRV_NON_UNIQUE,
2677  "INSERT INTO ipv6_reservations(address, prefix_len, type, "
2678  "dhcp6_iaid, host_id) "
2679  "VALUES (?, ?, ?, ?, ?)"},
2680 
2681  // Inserts a single IPv6 reservation into 'reservations' table with
2682  // checking that the inserted reservation is unique.
2683  {MySqlHostDataSourceImpl::INSERT_V6_RESRV_UNIQUE,
2684  "INSERT INTO ipv6_reservations(address, prefix_len, type, "
2685  "dhcp6_iaid, host_id) "
2686  "SELECT ?, ?, ?, ?, ? FROM DUAL "
2687  "WHERE NOT EXISTS ("
2688  "SELECT 1 FROM ipv6_reservations "
2689  "WHERE address = ? AND prefix_len = ? "
2690  "LIMIT 1"
2691  ")"},
2692 
2693  // Inserts a single DHCPv4 option into 'dhcp4_options' table.
2694  // Using fixed scope_id = 3, which associates an option with host.
2695  {MySqlHostDataSourceImpl::INSERT_V4_HOST_OPTION,
2696  "INSERT INTO dhcp4_options(option_id, code, value, formatted_value, space, "
2697  "persistent, user_context, dhcp_client_class, dhcp4_subnet_id, host_id, scope_id) "
2698  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 3)"},
2699 
2700  // Inserts a single DHCPv6 option into 'dhcp6_options' table.
2701  // Using fixed scope_id = 3, which associates an option with host.
2702  {MySqlHostDataSourceImpl::INSERT_V6_HOST_OPTION,
2703  "INSERT INTO dhcp6_options(option_id, code, value, formatted_value, space, "
2704  "persistent, user_context, dhcp_client_class, dhcp6_subnet_id, host_id, scope_id) "
2705  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 3)"},
2706 
2707  // Delete IPv4 reservations by subnet id and reserved address.
2708  {MySqlHostDataSourceImpl::DEL_HOST_ADDR4,
2709  "DELETE FROM hosts WHERE dhcp4_subnet_id = ? AND ipv4_address = ?"},
2710 
2711  // Delete IPv6 reservations by subnet id and reserved address/prefix.
2712  {MySqlHostDataSourceImpl::DEL_HOST_ADDR6,
2713  "DELETE h FROM hosts AS h "
2714  "INNER JOIN ipv6_reservations AS r "
2715  "ON h.host_id = r.host_id "
2716  "WHERE h.dhcp6_subnet_id = ? AND r.address = ?"},
2717 
2718  // Delete a single IPv4 reservation by subnet id and identifier.
2719  {MySqlHostDataSourceImpl::DEL_HOST_SUBID4_ID,
2720  "DELETE FROM hosts WHERE dhcp4_subnet_id = ? AND dhcp_identifier_type=? "
2721  "AND dhcp_identifier = ?"},
2722 
2723  // Delete a single IPv6 reservation by subnet id and identifier.
2724  {MySqlHostDataSourceImpl::DEL_HOST_SUBID6_ID,
2725  "DELETE FROM hosts WHERE dhcp6_subnet_id = ? AND dhcp_identifier_type=? "
2726  "AND dhcp_identifier = ?"}
2727  }
2728 };
2729 
2730 } // namespace
2731 
2732 // MySqlHostContext Constructor
2733 
2734 MySqlHostContext::MySqlHostContext(const DatabaseConnection::ParameterMap& parameters,
2735  IOServiceAccessorPtr io_service_accessor,
2736  db::DbCallback db_reconnect_callback)
2737  : conn_(parameters, io_service_accessor, db_reconnect_callback),
2738  is_readonly_(true) {
2739 }
2740 
2741 // MySqlHostContextAlloc Constructor and Destructor
2742 
2744  MySqlHostDataSourceImpl& mgr) : ctx_(), mgr_(mgr) {
2745 
2746  if (MultiThreadingMgr::instance().getMode()) {
2747  // multi-threaded
2748  {
2749  // we need to protect the whole pool_ operation, hence extra scope {}
2750  lock_guard<mutex> lock(mgr_.pool_->mutex_);
2751  if (!mgr_.pool_->pool_.empty()) {
2752  ctx_ = mgr_.pool_->pool_.back();
2753  mgr_.pool_->pool_.pop_back();
2754  }
2755  }
2756  if (!ctx_) {
2757  ctx_ = mgr_.createContext();
2758  }
2759  } else {
2760  // single-threaded
2761  if (mgr_.pool_->pool_.empty()) {
2762  isc_throw(Unexpected, "No available MySQL host context?!");
2763  }
2764  ctx_ = mgr_.pool_->pool_.back();
2765  }
2766 }
2767 
2769  if (MultiThreadingMgr::instance().getMode()) {
2770  // multi-threaded
2771  lock_guard<mutex> lock(mgr_.pool_->mutex_);
2772  mgr_.pool_->pool_.push_back(ctx_);
2773  if (ctx_->conn_.isUnusable()) {
2774  mgr_.unusable_ = true;
2775  }
2776  } else if (ctx_->conn_.isUnusable()) {
2777  mgr_.unusable_ = true;
2778  }
2779 }
2780 
2782  : parameters_(parameters), ip_reservations_unique_(true), unusable_(false),
2783  timer_name_("") {
2784 
2785  // Create unique timer name per instance.
2786  timer_name_ = "MySqlHostMgr[";
2787  timer_name_ += boost::lexical_cast<std::string>(reinterpret_cast<uint64_t>(this));
2788  timer_name_ += "]DbReconnectTimer";
2789 
2790  // Validate the schema version first.
2791  std::pair<uint32_t, uint32_t> code_version(MYSQL_SCHEMA_VERSION_MAJOR,
2793  std::pair<uint32_t, uint32_t> db_version = getVersion();
2794  if (code_version != db_version) {
2796  "MySQL schema version mismatch: need version: "
2797  << code_version.first << "." << code_version.second
2798  << " found version: " << db_version.first << "."
2799  << db_version.second);
2800  }
2801 
2802  // Create an initial context.
2803  pool_.reset(new MySqlHostContextPool());
2804  pool_->pool_.push_back(createContext());
2805 }
2806 
2807 // Create context.
2808 
2814 
2815  // Open the database.
2816  ctx->conn_.openDatabase();
2817 
2818  // Prepare query statements. Those are will be only used to retrieve
2819  // information from the database, so they can be used even if the
2820  // database is read only for the current user.
2821  ctx->conn_.prepareStatements(tagged_statements.begin(),
2822  tagged_statements.begin() + WRITE_STMTS_BEGIN);
2823 
2824  // Check if the backend is explicitly configured to operate with
2825  // read only access to the database.
2826  ctx->is_readonly_ = ctx->conn_.configuredReadOnly();
2827 
2828  // If we are using read-write mode for the database we also prepare
2829  // statements for INSERTS etc.
2830  if (!ctx->is_readonly_) {
2831  // Prepare statements for writing to the database, e.g. INSERT.
2832  ctx->conn_.prepareStatements(tagged_statements.begin() + WRITE_STMTS_BEGIN,
2833  tagged_statements.end());
2834  } else {
2836  }
2837 
2838  // Create the exchange objects for use in exchanging data between the
2839  // program and the database.
2840  ctx->host_ipv4_exchange_.reset(new MySqlHostWithOptionsExchange(MySqlHostWithOptionsExchange::DHCP4_ONLY));
2841  ctx->host_ipv6_exchange_.reset(new MySqlHostIPv6Exchange(MySqlHostWithOptionsExchange::DHCP6_ONLY));
2842  ctx->host_ipv46_exchange_.reset(new MySqlHostIPv6Exchange(MySqlHostWithOptionsExchange::DHCP4_AND_DHCP6));
2843  ctx->host_ipv6_reservation_exchange_.reset(new MySqlIPv6ReservationExchange());
2844  ctx->host_option_exchange_.reset(new MySqlOptionExchange());
2845 
2846  // Create ReconnectCtl for this connection.
2847  ctx->conn_.makeReconnectCtl(timer_name_);
2848 
2849  return (ctx);
2850 }
2851 
2853 }
2854 
2855 bool
2858 
2859  // Invoke application layer connection lost callback.
2860  if (!DatabaseConnection::invokeDbLostCallback(db_reconnect_ctl)) {
2861  return (false);
2862  }
2863 
2864  bool reopened = false;
2865 
2866  const std::string timer_name = db_reconnect_ctl->timerName();
2867 
2868  // At least one connection was lost.
2869  try {
2870  CfgDbAccessPtr cfg_db = CfgMgr::instance().getCurrentCfg()->getCfgDbAccess();
2871  std::list<std::string> host_db_access_list = cfg_db->getHostDbAccessStringList();
2872  for (std::string& hds : host_db_access_list) {
2873  auto parameters = DatabaseConnection::parse(hds);
2874  if (HostMgr::delBackend("mysql", hds, true)) {
2875  HostMgr::addBackend(hds);
2876  }
2877  }
2878  reopened = true;
2879  } catch (const std::exception& ex) {
2881  .arg(ex.what());
2882  }
2883 
2884  if (reopened) {
2885  // Cancel the timer.
2886  if (TimerMgr::instance()->isTimerRegistered(timer_name)) {
2887  TimerMgr::instance()->unregisterTimer(timer_name);
2888  }
2889 
2890  // Invoke application layer connection recovered callback.
2891  if (!DatabaseConnection::invokeDbRecoveredCallback(db_reconnect_ctl)) {
2892  return (false);
2893  }
2894  } else {
2895  if (!db_reconnect_ctl->checkRetries()) {
2896  // We're out of retries, log it and initiate shutdown.
2898  .arg(db_reconnect_ctl->maxRetries());
2899 
2900  // Cancel the timer.
2901  if (TimerMgr::instance()->isTimerRegistered(timer_name)) {
2902  TimerMgr::instance()->unregisterTimer(timer_name);
2903  }
2904 
2905  // Invoke application layer connection failed callback.
2907  return (false);
2908  }
2909 
2911  .arg(db_reconnect_ctl->maxRetries() - db_reconnect_ctl->retriesLeft() + 1)
2912  .arg(db_reconnect_ctl->maxRetries())
2913  .arg(db_reconnect_ctl->retryInterval());
2914 
2915  // Start the timer.
2916  if (!TimerMgr::instance()->isTimerRegistered(timer_name)) {
2917  TimerMgr::instance()->registerTimer(timer_name,
2918  std::bind(&MySqlHostDataSourceImpl::dbReconnect, db_reconnect_ctl),
2919  db_reconnect_ctl->retryInterval(),
2921  }
2922  TimerMgr::instance()->setup(timer_name);
2923  }
2924 
2925  return (true);
2926 }
2927 
2928 std::pair<uint32_t, uint32_t>
2932 
2934 }
2935 
2936 void
2938  StatementIndex stindex,
2939  std::vector<MYSQL_BIND>& bind) {
2940  // Bind the parameters to the statement
2941  int status = mysql_stmt_bind_param(ctx->conn_.statements_[stindex], &bind[0]);
2942  checkError(ctx, status, stindex, "unable to bind parameters");
2943 
2944  // Execute the statement
2945  status = MysqlExecuteStatement(ctx->conn_.statements_[stindex]);
2946 
2947  if (status != 0) {
2948  // Failure: check for the special case of duplicate entry.
2949  if (mysql_errno(ctx->conn_.mysql_) == ER_DUP_ENTRY) {
2950  isc_throw(DuplicateEntry, "Database duplicate entry error");
2951  }
2952  checkError(ctx, status, stindex, "unable to execute");
2953  }
2954 
2955  // If the number of rows inserted is 0 it means that the query detected
2956  // an attempt to insert duplicated data for which there is no unique
2957  // index in the database. Unique indexes are not created in the database
2958  // when it may be sometimes allowed to insert duplicated records per
2959  // server's configuration.
2960  my_ulonglong numrows = mysql_stmt_affected_rows(ctx->conn_.statements_[stindex]);
2961  if (numrows == 0) {
2962  isc_throw(DuplicateEntry, "Database duplicate entry error");
2963  }
2964 }
2965 
2966 bool
2968  StatementIndex stindex,
2969  MYSQL_BIND* bind) {
2970  // Bind the parameters to the statement
2971  int status = mysql_stmt_bind_param(ctx->conn_.statements_[stindex], &bind[0]);
2972  checkError(ctx, status, stindex, "unable to bind parameters");
2973 
2974  // Execute the statement
2975  status = MysqlExecuteStatement(ctx->conn_.statements_[stindex]);
2976 
2977  if (status != 0) {
2978  checkError(ctx, status, stindex, "unable to execute");
2979  }
2980 
2981  // Let's check how many hosts were deleted.
2982  my_ulonglong numrows = mysql_stmt_affected_rows(ctx->conn_.statements_[stindex]);
2983 
2984  return (numrows != 0);
2985 }
2986 
2987 void
2989  const IPv6Resrv& resv,
2990  const HostID& id) {
2991  std::vector<MYSQL_BIND> bind = ctx->host_ipv6_reservation_exchange_->
2992  createBindForSend(resv, id, ip_reservations_unique_);
2993 
2995 }
2996 
2997 void
2999  const StatementIndex& stindex,
3000  const OptionDescriptor& opt_desc,
3001  const std::string& opt_space,
3002  const Optional<SubnetID>& subnet_id,
3003  const HostID& id) {
3004  std::vector<MYSQL_BIND> bind = ctx->host_option_exchange_->createBindForSend(opt_desc, opt_space, subnet_id, id);
3005 
3006  addStatement(ctx, stindex, bind);
3007 }
3008 
3009 void
3011  const StatementIndex& stindex,
3012  const ConstCfgOptionPtr& options_cfg,
3013  const uint64_t host_id) {
3014  // Get option space names and vendor space names and combine them within a
3015  // single list.
3016  std::list<std::string> option_spaces = options_cfg->getOptionSpaceNames();
3017  std::list<std::string> vendor_spaces = options_cfg->getVendorIdsSpaceNames();
3018  option_spaces.insert(option_spaces.end(), vendor_spaces.begin(),
3019  vendor_spaces.end());
3020 
3021  // For each option space retrieve all options and insert them into the
3022  // database.
3023  for (auto space = option_spaces.begin(); space != option_spaces.end(); ++space) {
3024  OptionContainerPtr options = options_cfg->getAll(*space);
3025  if (options && !options->empty()) {
3026  for (auto opt = options->begin(); opt != options->end(); ++opt) {
3027  addOption(ctx, stindex, *opt, *space, Optional<SubnetID>(), host_id);
3028  }
3029  }
3030  }
3031 }
3032 
3033 void
3035  const int status,
3036  const StatementIndex index,
3037  const char* what) const {
3038  ctx->conn_.checkError(status, index, what);
3039 }
3040 
3041 void
3043  StatementIndex stindex,
3044  MYSQL_BIND* bind,
3045  boost::shared_ptr<MySqlHostExchange> exchange,
3046  ConstHostCollection& result,
3047  bool single) const {
3048 
3049  // Bind the selection parameters to the statement
3050  int status = mysql_stmt_bind_param(ctx->conn_.statements_[stindex], bind);
3051  checkError(ctx, status, stindex, "unable to bind WHERE clause parameter");
3052 
3053  // Set up the MYSQL_BIND array for the data being returned and bind it to
3054  // the statement.
3055  std::vector<MYSQL_BIND> outbind = exchange->createBindForReceive();
3056  status = mysql_stmt_bind_result(ctx->conn_.statements_[stindex], &outbind[0]);
3057  checkError(ctx, status, stindex, "unable to bind SELECT clause parameters");
3058 
3059  // Execute the statement
3060  status = MysqlExecuteStatement(ctx->conn_.statements_[stindex]);
3061  checkError(ctx, status, stindex, "unable to execute");
3062 
3063  // Ensure that all the lease information is retrieved in one go to avoid
3064  // overhead of going back and forth between client and server.
3065  status = mysql_stmt_store_result(ctx->conn_.statements_[stindex]);
3066  checkError(ctx, status, stindex, "unable to set up for storing all results");
3067 
3068  // Set up the fetch "release" object to release resources associated
3069  // with the call to mysql_stmt_fetch when this method exits, then
3070  // retrieve the data. mysql_stmt_fetch return value equal to 0 represents
3071  // successful data fetch.
3072  MySqlFreeResult fetch_release(ctx->conn_.statements_[stindex]);
3073  while ((status = mysql_stmt_fetch(ctx->conn_.statements_[stindex])) ==
3075  try {
3076  exchange->processFetchedData(result);
3077 
3078  } catch (const isc::BadValue& ex) {
3079  // Rethrow the exception with a bit more data.
3080  isc_throw(BadValue, ex.what() << ". Statement is <" <<
3081  ctx->conn_.text_statements_[stindex] << ">");
3082  }
3083 
3084  if (single && (result.size() > 1)) {
3085  isc_throw(MultipleRecords, "multiple records were found in the "
3086  "database where only one was expected for query "
3087  << ctx->conn_.text_statements_[stindex]);
3088  }
3089  }
3090 
3091  // How did the fetch end?
3092  // If mysql_stmt_fetch return value is equal to 1 an error occurred.
3093  if (status == MLM_MYSQL_FETCH_FAILURE) {
3094  // Error - unable to fetch results
3095  checkError(ctx, status, stindex, "unable to fetch results");
3096 
3097  } else if (status == MYSQL_DATA_TRUNCATED) {
3098  // Data truncated - throw an exception indicating what was at fault
3099  isc_throw(DataTruncated, ctx->conn_.text_statements_[stindex]
3100  << " returned truncated data: columns affected are "
3101  << exchange->getErrorColumns());
3102  }
3103 }
3104 
3107  const SubnetID& subnet_id,
3108  const Host::IdentifierType& identifier_type,
3109  const uint8_t* identifier_begin,
3110  const size_t identifier_len,
3111  StatementIndex stindex,
3112  boost::shared_ptr<MySqlHostExchange> exchange) const {
3113 
3114  // Set up the WHERE clause value
3115  MYSQL_BIND inbind[3];
3116  memset(inbind, 0, sizeof(inbind));
3117 
3118  uint32_t subnet_buffer = static_cast<uint32_t>(subnet_id);
3119  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3120  inbind[0].buffer = reinterpret_cast<char*>(&subnet_buffer);
3121  inbind[0].is_unsigned = MLM_TRUE;
3122 
3123  // Identifier value.
3124  std::vector<char> identifier_vec(identifier_begin,
3125  identifier_begin + identifier_len);
3126  unsigned long length = identifier_vec.size();
3127  inbind[2].buffer_type = MYSQL_TYPE_BLOB;
3128  inbind[2].buffer = &identifier_vec[0];
3129  inbind[2].buffer_length = length;
3130  inbind[2].length = &length;
3131 
3132  // Identifier type.
3133  char identifier_type_copy = static_cast<char>(identifier_type);
3134  inbind[1].buffer_type = MYSQL_TYPE_TINY;
3135  inbind[1].buffer = reinterpret_cast<char*>(&identifier_type_copy);
3136  inbind[1].is_unsigned = MLM_TRUE;
3137 
3138  ConstHostCollection collection;
3139  getHostCollection(ctx, stindex, inbind, exchange, collection, true);
3140 
3141  // Return single record if present, else clear the host.
3142  ConstHostPtr result;
3143  if (!collection.empty()) {
3144  result = *collection.begin();
3145  }
3146 
3147  return (result);
3148 }
3149 
3150 void
3152  if (ctx->is_readonly_) {
3153  isc_throw(ReadOnlyDb, "MySQL host database backend is configured to"
3154  " operate in read only mode");
3155  }
3156 }
3157 
3159  : impl_(new MySqlHostDataSourceImpl(parameters)) {
3160 }
3161 
3163 }
3164 
3167  return impl_->parameters_;
3168 }
3169 
3170 void
3172  // Get a context
3173  MySqlHostContextAlloc get_context(*impl_);
3174  MySqlHostContextPtr ctx = get_context.ctx_;
3175 
3176  // If operating in read-only mode, throw exception.
3177  impl_->checkReadOnly(ctx);
3178 
3179  // Initiate MySQL transaction as we will have to make multiple queries
3180  // to insert host information into multiple tables. If that fails on
3181  // any stage, the transaction will be rolled back by the destructor of
3182  // the MySqlTransaction class.
3183  MySqlTransaction transaction(ctx->conn_);
3184 
3185  // If we're configured to check that an IP reservation within a given subnet
3186  // is unique, the IP reservation exists and the subnet is actually set
3187  // we will be using a special query that checks for uniqueness. Otherwise,
3188  // we will use a regular insert statement.
3189  bool unique_ip = impl_->ip_reservations_unique_ && !host->getIPv4Reservation().isV4Zero()
3190  && host->getIPv4SubnetID() != SUBNET_ID_UNUSED;
3191 
3192  // Create the MYSQL_BIND array for the host
3193  std::vector<MYSQL_BIND> bind = ctx->host_ipv4_exchange_->createBindForSend(host, unique_ip);
3194 
3195  // ... and insert the host.
3196  impl_->addStatement(ctx, unique_ip ? MySqlHostDataSourceImpl::INSERT_HOST_UNIQUE_IP :
3198 
3199  // Gets the last inserted hosts id
3200  uint64_t host_id = mysql_insert_id(ctx->conn_.mysql_);
3201 
3202  // Insert DHCPv4 options.
3203  ConstCfgOptionPtr cfg_option4 = host->getCfgOption4();
3204  if (cfg_option4) {
3205  impl_->addOptions(ctx, MySqlHostDataSourceImpl::INSERT_V4_HOST_OPTION,
3206  cfg_option4, host_id);
3207  }
3208 
3209  // Insert DHCPv6 options.
3210  ConstCfgOptionPtr cfg_option6 = host->getCfgOption6();
3211  if (cfg_option6) {
3212  impl_->addOptions(ctx, MySqlHostDataSourceImpl::INSERT_V6_HOST_OPTION,
3213  cfg_option6, host_id);
3214  }
3215 
3216  // Insert IPv6 reservations.
3217  IPv6ResrvRange v6resv = host->getIPv6Reservations();
3218  if (std::distance(v6resv.first, v6resv.second) > 0) {
3219  for (IPv6ResrvIterator resv = v6resv.first; resv != v6resv.second;
3220  ++resv) {
3221  impl_->addResv(ctx, resv->second, host_id);
3222  }
3223  }
3224 
3225  // Everything went fine, so explicitly commit the transaction.
3226  transaction.commit();
3227 }
3228 
3229 bool
3231  const asiolink::IOAddress& addr) {
3232  // Get a context
3233  MySqlHostContextAlloc get_context(*impl_);
3234  MySqlHostContextPtr ctx = get_context.ctx_;
3235 
3236  // If operating in read-only mode, throw exception.
3237  impl_->checkReadOnly(ctx);
3238 
3239  // Set up the WHERE clause value
3240  MYSQL_BIND inbind[2];
3241 
3242  uint32_t subnet = subnet_id;
3243  memset(inbind, 0, sizeof(inbind));
3244  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3245  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3246  inbind[0].is_unsigned = MLM_TRUE;
3247 
3248  // v4
3249  if (addr.isV4()) {
3250  uint32_t addr4 = addr.toUint32();
3251  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3252  inbind[1].buffer = reinterpret_cast<char*>(&addr4);
3253  inbind[1].is_unsigned = MLM_TRUE;
3254 
3255  return (impl_->delStatement(ctx, MySqlHostDataSourceImpl::DEL_HOST_ADDR4, inbind));
3256  }
3257 
3258  // v6
3259  std::string addr_str = addr.toText();
3260  unsigned long addr_len = addr_str.size();
3261  inbind[1].buffer_type = MYSQL_TYPE_BLOB;
3262  inbind[1].buffer = reinterpret_cast<char*>
3263  (const_cast<char*>(addr_str.c_str()));
3264  inbind[1].length = &addr_len;
3265  inbind[1].buffer_length = addr_len;
3266 
3267  return (impl_->delStatement(ctx, MySqlHostDataSourceImpl::DEL_HOST_ADDR6, inbind));
3268 }
3269 
3270 bool
3272  const Host::IdentifierType& identifier_type,
3273  const uint8_t* identifier_begin,
3274  const size_t identifier_len) {
3275  // Get a context
3276  MySqlHostContextAlloc get_context(*impl_);
3277  MySqlHostContextPtr ctx = get_context.ctx_;
3278 
3279  // If operating in read-only mode, throw exception.
3280  impl_->checkReadOnly(ctx);
3281 
3282  // Set up the WHERE clause value
3283  MYSQL_BIND inbind[3];
3284 
3285  // subnet-id
3286  memset(inbind, 0, sizeof(inbind));
3287  uint32_t subnet = static_cast<uint32_t>(subnet_id);
3288  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3289  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3290  inbind[0].is_unsigned = MLM_TRUE;
3291 
3292  // identifier type
3293  char identifier_type_copy = static_cast<char>(identifier_type);
3294  inbind[1].buffer_type = MYSQL_TYPE_TINY;
3295  inbind[1].buffer = reinterpret_cast<char*>(&identifier_type_copy);
3296  inbind[1].is_unsigned = MLM_TRUE;
3297 
3298  // identifier value
3299  std::vector<char> identifier_vec(identifier_begin,
3300  identifier_begin + identifier_len);
3301  unsigned long length = identifier_vec.size();
3302  inbind[2].buffer_type = MYSQL_TYPE_BLOB;
3303  inbind[2].buffer = &identifier_vec[0];
3304  inbind[2].buffer_length = length;
3305  inbind[2].length = &length;
3306 
3307  ConstHostCollection collection;
3308  return (impl_->delStatement(ctx, MySqlHostDataSourceImpl::DEL_HOST_SUBID4_ID, inbind));
3309 }
3310 
3311 bool
3313  const Host::IdentifierType& identifier_type,
3314  const uint8_t* identifier_begin,
3315  const size_t identifier_len) {
3316  // Get a context
3317  MySqlHostContextAlloc get_context(*impl_);
3318  MySqlHostContextPtr ctx = get_context.ctx_;
3319 
3320  // If operating in read-only mode, throw exception.
3321  impl_->checkReadOnly(ctx);
3322 
3323  // Set up the WHERE clause value
3324  MYSQL_BIND inbind[3];
3325 
3326  // subnet-id
3327  memset(inbind, 0, sizeof(inbind));
3328  uint32_t subnet = static_cast<uint32_t>(subnet_id);
3329  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3330  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3331  inbind[0].is_unsigned = MLM_TRUE;
3332 
3333  // identifier type
3334  char identifier_type_copy = static_cast<char>(identifier_type);
3335  inbind[1].buffer_type = MYSQL_TYPE_TINY;
3336  inbind[1].buffer = reinterpret_cast<char*>(&identifier_type_copy);
3337  inbind[1].is_unsigned = MLM_TRUE;
3338 
3339  // identifier value
3340  std::vector<char> identifier_vec(identifier_begin,
3341  identifier_begin + identifier_len);
3342  unsigned long length = identifier_vec.size();
3343  inbind[2].buffer_type = MYSQL_TYPE_BLOB;
3344  inbind[2].buffer = &identifier_vec[0];
3345  inbind[2].buffer_length = length;
3346  inbind[2].length = &length;
3347 
3348  ConstHostCollection collection;
3349  return (impl_->delStatement(ctx, MySqlHostDataSourceImpl::DEL_HOST_SUBID6_ID, inbind));
3350 }
3351 
3354  const uint8_t* identifier_begin,
3355  const size_t identifier_len) const {
3356  // Get a context
3357  MySqlHostContextAlloc get_context(*impl_);
3358  MySqlHostContextPtr ctx = get_context.ctx_;
3359 
3360  // Set up the WHERE clause value
3361  MYSQL_BIND inbind[2];
3362  memset(inbind, 0, sizeof(inbind));
3363 
3364  // Identifier type.
3365  char identifier_type_copy = static_cast<char>(identifier_type);
3366  inbind[1].buffer = &identifier_type_copy;
3367  inbind[1].buffer_type = MYSQL_TYPE_TINY;
3368  inbind[1].is_unsigned = MLM_TRUE;
3369 
3370  // Identifier value.
3371  std::vector<char> identifier_vec(identifier_begin,
3372  identifier_begin + identifier_len);
3373  unsigned long int length = identifier_vec.size();
3374  inbind[0].buffer_type = MYSQL_TYPE_BLOB;
3375  inbind[0].buffer = &identifier_vec[0];
3376  inbind[0].buffer_length = length;
3377  inbind[0].length = &length;
3378 
3379  ConstHostCollection result;
3380  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_DHCPID, inbind,
3381  ctx->host_ipv46_exchange_, result, false);
3382 
3383  return (result);
3384 }
3385 
3387 MySqlHostDataSource::getAll4(const SubnetID& subnet_id) const {
3388  // Get a context
3389  MySqlHostContextAlloc get_context(*impl_);
3390  MySqlHostContextPtr ctx = get_context.ctx_;
3391 
3392  // Set up the WHERE clause value
3393  MYSQL_BIND inbind[1];
3394  memset(inbind, 0, sizeof(inbind));
3395  uint32_t subnet = subnet_id;
3396  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3397  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3398  inbind[0].is_unsigned = MLM_TRUE;
3399 
3400  ConstHostCollection result;
3401  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID4, inbind,
3402  ctx->host_ipv4_exchange_, result, false);
3403 
3404  return (result);
3405 }
3406 
3408 MySqlHostDataSource::getAll6(const SubnetID& subnet_id) const {
3409  // Get a context
3410  MySqlHostContextAlloc get_context(*impl_);
3411  MySqlHostContextPtr ctx = get_context.ctx_;
3412 
3413  // Set up the WHERE clause value
3414  MYSQL_BIND inbind[1];
3415  memset(inbind, 0, sizeof(inbind));
3416  uint32_t subnet = subnet_id;
3417  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3418  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3419  inbind[0].is_unsigned = MLM_TRUE;
3420 
3421  ConstHostCollection result;
3422  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID6, inbind,
3423  ctx->host_ipv6_exchange_, result, false);
3424 
3425  return (result);
3426 }
3427 
3429 MySqlHostDataSource::getAllbyHostname(const std::string& hostname) const {
3430  // Get a context
3431  MySqlHostContextAlloc get_context(*impl_);
3432  MySqlHostContextPtr ctx = get_context.ctx_;
3433 
3434  // Set up the WHERE clause value
3435  MYSQL_BIND inbind[1];
3436  memset(inbind, 0, sizeof(inbind));
3437 
3438  // Hostname
3439  char hostname_[HOSTNAME_MAX_LEN];
3440  strncpy(hostname_, hostname.c_str(), HOSTNAME_MAX_LEN - 1);
3441  unsigned long length = hostname.length();
3442  inbind[0].buffer_type = MYSQL_TYPE_STRING;
3443  inbind[0].buffer = reinterpret_cast<char*>(hostname_);
3444  inbind[0].buffer_length = length;
3445  inbind[0].length = &length;
3446 
3447  ConstHostCollection result;
3448  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_HOSTNAME, inbind,
3449  ctx->host_ipv46_exchange_, result, false);
3450 
3451  return (result);
3452 }
3453 
3455 MySqlHostDataSource::getAllbyHostname4(const std::string& hostname,
3456  const SubnetID& subnet_id) const {
3457  // Get a context
3458  MySqlHostContextAlloc get_context(*impl_);
3459  MySqlHostContextPtr ctx = get_context.ctx_;
3460 
3461  // Set up the WHERE clause value
3462  MYSQL_BIND inbind[2];
3463  memset(inbind, 0, sizeof(inbind));
3464 
3465  // Hostname
3466  char hostname_[HOSTNAME_MAX_LEN];
3467  strncpy(hostname_, hostname.c_str(), HOSTNAME_MAX_LEN - 1);
3468  unsigned long length = hostname.length();
3469  inbind[0].buffer_type = MYSQL_TYPE_STRING;
3470  inbind[0].buffer = reinterpret_cast<char*>(hostname_);
3471  inbind[0].buffer_length = length;
3472  inbind[0].length = &length;
3473 
3474  // Subnet ID
3475  uint32_t subnet = subnet_id;
3476  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3477  inbind[1].buffer = reinterpret_cast<char*>(&subnet);
3478  inbind[1].is_unsigned = MLM_TRUE;
3479 
3480  ConstHostCollection result;
3481  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_HOSTNAME_SUBID4, inbind,
3482  ctx->host_ipv4_exchange_, result, false);
3483 
3484  return (result);
3485 }
3486 
3488 MySqlHostDataSource::getAllbyHostname6(const std::string& hostname,
3489  const SubnetID& subnet_id) const {
3490  // Get a context
3491  MySqlHostContextAlloc get_context(*impl_);
3492  MySqlHostContextPtr ctx = get_context.ctx_;
3493 
3494  // Set up the WHERE clause value
3495  MYSQL_BIND inbind[2];
3496  memset(inbind, 0, sizeof(inbind));
3497 
3498  // Hostname
3499  char hostname_[HOSTNAME_MAX_LEN];
3500  strncpy(hostname_, hostname.c_str(), HOSTNAME_MAX_LEN - 1);
3501  unsigned long length = hostname.length();
3502  inbind[0].buffer_type = MYSQL_TYPE_STRING;
3503  inbind[0].buffer = reinterpret_cast<char*>(hostname_);
3504  inbind[0].buffer_length = length;
3505  inbind[0].length = &length;
3506 
3507  // Subnet ID
3508  uint32_t subnet = subnet_id;
3509  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3510  inbind[1].buffer = reinterpret_cast<char*>(&subnet);
3511  inbind[1].is_unsigned = MLM_TRUE;
3512 
3513  ConstHostCollection result;
3514  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_HOSTNAME_SUBID6, inbind,
3515  ctx->host_ipv6_exchange_, result, false);
3516 
3517  return (result);
3518 }
3519 
3522  size_t& /*source_index*/,
3523  uint64_t lower_host_id,
3524  const HostPageSize& page_size) const {
3525  // Get a context
3526  MySqlHostContextAlloc get_context(*impl_);
3527  MySqlHostContextPtr ctx = get_context.ctx_;
3528 
3529  // Set up the WHERE clause value
3530  MYSQL_BIND inbind[3];
3531  memset(inbind, 0, sizeof(inbind));
3532 
3533  // Bind subnet id
3534  uint32_t subnet = subnet_id;
3535  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3536  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3537  inbind[0].is_unsigned = MLM_TRUE;
3538 
3539  // Bind lower host id
3540  uint32_t host_id = lower_host_id;
3541  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3542  inbind[1].buffer = reinterpret_cast<char*>(&host_id);
3543  inbind[1].is_unsigned = MLM_TRUE;
3544 
3545  // Bind page size value
3546  uint32_t page_size_data = page_size.page_size_;
3547  inbind[2].buffer_type = MYSQL_TYPE_LONG;
3548  inbind[2].buffer = reinterpret_cast<char*>(&page_size_data);
3549  inbind[2].is_unsigned = MLM_TRUE;
3550 
3551  ConstHostCollection result;
3552  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID4_PAGE, inbind,
3553  ctx->host_ipv4_exchange_, result, false);
3554 
3555  return (result);
3556 }
3557 
3560  size_t& /*source_index*/,
3561  uint64_t lower_host_id,
3562  const HostPageSize& page_size) const {
3563  // Get a context
3564  MySqlHostContextAlloc get_context(*impl_);
3565  MySqlHostContextPtr ctx = get_context.ctx_;
3566 
3567  // Set up the WHERE clause value
3568  MYSQL_BIND inbind[3];
3569  memset(inbind, 0, sizeof(inbind));
3570 
3571  // Bind subnet id
3572  uint32_t subnet = subnet_id;
3573  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3574  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3575  inbind[0].is_unsigned = MLM_TRUE;
3576 
3577  // Bind lower host id
3578  uint32_t host_id = lower_host_id;
3579  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3580  inbind[1].buffer = reinterpret_cast<char*>(&host_id);
3581  inbind[1].is_unsigned = MLM_TRUE;
3582 
3583  // Bind page size value
3584  uint32_t page_size_data = page_size.page_size_;
3585  inbind[2].buffer_type = MYSQL_TYPE_LONG;
3586  inbind[2].buffer = reinterpret_cast<char*>(&page_size_data);
3587  inbind[2].is_unsigned = MLM_TRUE;
3588 
3589  ConstHostCollection result;
3590  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID6_PAGE, inbind,
3591  ctx->host_ipv6_exchange_, result, false);
3592 
3593  return (result);
3594 }
3595 
3597 MySqlHostDataSource::getPage4(size_t& /*source_index*/,
3598  uint64_t lower_host_id,
3599  const HostPageSize& page_size) const {
3600  // Get a context
3601  MySqlHostContextAlloc get_context(*impl_);
3602  MySqlHostContextPtr ctx = get_context.ctx_;
3603 
3604  // Set up the WHERE clause value
3605  MYSQL_BIND inbind[2];
3606  memset(inbind, 0, sizeof(inbind));
3607 
3608  // Bind lower host id
3609  uint32_t host_id = lower_host_id;
3610  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3611  inbind[0].buffer = reinterpret_cast<char*>(&host_id);
3612  inbind[0].is_unsigned = MLM_TRUE;
3613 
3614  // Bind page size value
3615  uint32_t page_size_data = page_size.page_size_;
3616  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3617  inbind[1].buffer = reinterpret_cast<char*>(&page_size_data);
3618  inbind[1].is_unsigned = MLM_TRUE;
3619 
3620  ConstHostCollection result;
3621  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_PAGE4, inbind,
3622  ctx->host_ipv4_exchange_, result, false);
3623 
3624  return (result);
3625 }
3626 
3628 MySqlHostDataSource::getPage6(size_t& /*source_index*/,
3629  uint64_t lower_host_id,
3630  const HostPageSize& page_size) const {
3631  // Get a context
3632  MySqlHostContextAlloc get_context(*impl_);
3633  MySqlHostContextPtr ctx = get_context.ctx_;
3634 
3635  // Set up the WHERE clause value
3636  MYSQL_BIND inbind[2];
3637  memset(inbind, 0, sizeof(inbind));
3638 
3639  // Bind lower host id
3640  uint32_t host_id = lower_host_id;
3641  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3642  inbind[0].buffer = reinterpret_cast<char*>(&host_id);
3643  inbind[0].is_unsigned = MLM_TRUE;
3644 
3645  // Bind page size value
3646  uint32_t page_size_data = page_size.page_size_;
3647  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3648  inbind[1].buffer = reinterpret_cast<char*>(&page_size_data);
3649  inbind[1].is_unsigned = MLM_TRUE;
3650 
3651  ConstHostCollection result;
3652  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_PAGE6, inbind,
3653  ctx->host_ipv6_exchange_, result, false);
3654 
3655  return (result);
3656 }
3657 
3660  // Get a context
3661  MySqlHostContextAlloc get_context(*impl_);
3662  MySqlHostContextPtr ctx = get_context.ctx_;
3663 
3664  // Set up the WHERE clause value
3665  MYSQL_BIND inbind[1];
3666  memset(inbind, 0, sizeof(inbind));
3667 
3668  uint32_t addr4 = address.toUint32();
3669  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3670  inbind[0].buffer = reinterpret_cast<char*>(&addr4);
3671  inbind[0].is_unsigned = MLM_TRUE;
3672 
3673  ConstHostCollection result;
3674  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_ADDR, inbind,
3675  ctx->host_ipv4_exchange_, result, false);
3676 
3677  return (result);
3678 }
3679 
3682  const Host::IdentifierType& identifier_type,
3683  const uint8_t* identifier_begin,
3684  const size_t identifier_len) const {
3685  // Get a context
3686  MySqlHostContextAlloc get_context(*impl_);
3687  MySqlHostContextPtr ctx = get_context.ctx_;
3688 
3689  return (impl_->getHost(ctx, subnet_id, identifier_type, identifier_begin, identifier_len,
3691  ctx->host_ipv4_exchange_));
3692 }
3693 
3696  const asiolink::IOAddress& address) const {
3697  if (!address.isV4()) {
3698  isc_throw(BadValue, "MySqlHostDataSource::get4(id, address): "
3699  "wrong address type, address supplied is an IPv6 address");
3700  }
3701 
3702  // Get a context
3703  MySqlHostContextAlloc get_context(*impl_);
3704  MySqlHostContextPtr ctx = get_context.ctx_;
3705 
3706  // Set up the WHERE clause value
3707  MYSQL_BIND inbind[2];
3708  uint32_t subnet = subnet_id;
3709  memset(inbind, 0, sizeof(inbind));
3710  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3711  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3712  inbind[0].is_unsigned = MLM_TRUE;
3713 
3714  uint32_t addr4 = address.toUint32();
3715  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3716  inbind[1].buffer = reinterpret_cast<char*>(&addr4);
3717  inbind[1].is_unsigned = MLM_TRUE;
3718 
3719  ConstHostCollection collection;
3720  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID_ADDR, inbind,
3721  ctx->host_ipv4_exchange_, collection, true);
3722 
3723  // Return single record if present, else clear the host.
3724  ConstHostPtr result;
3725  if (!collection.empty()) {
3726  result = *collection.begin();
3727  }
3728 
3729  return (result);
3730 }
3731 
3734  const asiolink::IOAddress& address) const {
3735  if (!address.isV4()) {
3736  isc_throw(BadValue, "MySqlHostDataSource::getAll4(id, address): "
3737  "wrong address type, address supplied is an IPv6 address");
3738  }
3739 
3740  // Get a context
3741  MySqlHostContextAlloc get_context(*impl_);
3742  MySqlHostContextPtr ctx = get_context.ctx_;
3743 
3744  // Set up the WHERE clause value
3745  MYSQL_BIND inbind[2];
3746  uint32_t subnet = subnet_id;
3747  memset(inbind, 0, sizeof(inbind));
3748  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3749  inbind[0].buffer = reinterpret_cast<char*>(&subnet);
3750  inbind[0].is_unsigned = MLM_TRUE;
3751 
3752  uint32_t addr4 = address.toUint32();
3753  inbind[1].buffer_type = MYSQL_TYPE_LONG;
3754  inbind[1].buffer = reinterpret_cast<char*>(&addr4);
3755  inbind[1].is_unsigned = MLM_TRUE;
3756 
3757  ConstHostCollection collection;
3758  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID_ADDR, inbind,
3759  ctx->host_ipv4_exchange_, collection, false);
3760  return (collection);
3761 }
3762 
3765  const Host::IdentifierType& identifier_type,
3766  const uint8_t* identifier_begin,
3767  const size_t identifier_len) const {
3768  // Get a context
3769  MySqlHostContextAlloc get_context(*impl_);
3770  MySqlHostContextPtr ctx = get_context.ctx_;
3771 
3772  return (impl_->getHost(ctx, subnet_id, identifier_type, identifier_begin, identifier_len,
3774  ctx->host_ipv6_exchange_));
3775 }
3776 
3779  const uint8_t prefix_len) const {
3780  if (!prefix.isV6()) {
3781  isc_throw(BadValue, "MySqlHostDataSource::get6(prefix, prefix_len): "
3782  "wrong address type, address supplied is an IPv4 address");
3783  }
3784 
3785  // Get a context
3786  MySqlHostContextAlloc get_context(*impl_);
3787  MySqlHostContextPtr ctx = get_context.ctx_;
3788 
3789  // Set up the WHERE clause value
3790  MYSQL_BIND inbind[2];
3791  memset(inbind, 0, sizeof(inbind));
3792 
3793  std::string addr6 = prefix.toText();
3794  unsigned long addr6_length = addr6.size();
3795 
3796  inbind[0].buffer_type = MYSQL_TYPE_BLOB;
3797  inbind[0].buffer = reinterpret_cast<char*>
3798  (const_cast<char*>(addr6.c_str()));
3799  inbind[0].length = &addr6_length;
3800  inbind[0].buffer_length = addr6_length;
3801 
3802  uint8_t tmp = prefix_len;
3803  inbind[1].buffer_type = MYSQL_TYPE_TINY;
3804  inbind[1].buffer = reinterpret_cast<char*>(&tmp);
3805  inbind[1].is_unsigned = MLM_TRUE;
3806 
3807  ConstHostCollection collection;
3808  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_PREFIX, inbind,
3809  ctx->host_ipv6_exchange_, collection, true);
3810 
3811  // Return single record if present, else clear the host.
3812  ConstHostPtr result;
3813  if (!collection.empty()) {
3814  result = *collection.begin();
3815  }
3816 
3817  return (result);
3818 }
3819 
3822  const asiolink::IOAddress& address) const {
3823  if (!address.isV6()) {
3824  isc_throw(BadValue, "MySqlHostDataSource::get6(id, address): "
3825  "wrong address type, address supplied is an IPv4 address");
3826  }
3827 
3828  // Get a context
3829  MySqlHostContextAlloc get_context(*impl_);
3830  MySqlHostContextPtr ctx = get_context.ctx_;
3831 
3832  // Set up the WHERE clause value
3833  MYSQL_BIND inbind[2];
3834  memset(inbind, 0, sizeof(inbind));
3835 
3836  uint32_t subnet_buffer = static_cast<uint32_t>(subnet_id);
3837  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3838  inbind[0].buffer = reinterpret_cast<char*>(&subnet_buffer);
3839  inbind[0].is_unsigned = MLM_TRUE;
3840 
3841  std::string addr6 = address.toText();
3842  unsigned long addr6_length = addr6.size();
3843 
3844  inbind[1].buffer_type = MYSQL_TYPE_BLOB;
3845  inbind[1].buffer = reinterpret_cast<char*>
3846  (const_cast<char*>(addr6.c_str()));
3847  inbind[1].length = &addr6_length;
3848  inbind[1].buffer_length = addr6_length;
3849 
3850  ConstHostCollection collection;
3851  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID6_ADDR, inbind,
3852  ctx->host_ipv6_exchange_, collection, true);
3853 
3854  // Return single record if present, else clear the host.
3855  ConstHostPtr result;
3856  if (!collection.empty()) {
3857  result = *collection.begin();
3858  }
3859 
3860  return (result);
3861 }
3862 
3865  const asiolink::IOAddress& address) const {
3866  if (!address.isV6()) {
3867  isc_throw(BadValue, "MySqlHostDataSource::getAll6(id, address): "
3868  "wrong address type, address supplied is an IPv4 address");
3869  }
3870 
3871  // Get a context
3872  MySqlHostContextAlloc get_context(*impl_);
3873  MySqlHostContextPtr ctx = get_context.ctx_;
3874 
3875  // Set up the WHERE clause value
3876  MYSQL_BIND inbind[2];
3877  memset(inbind, 0, sizeof(inbind));
3878 
3879  uint32_t subnet_buffer = static_cast<uint32_t>(subnet_id);
3880  inbind[0].buffer_type = MYSQL_TYPE_LONG;
3881  inbind[0].buffer = reinterpret_cast<char*>(&subnet_buffer);
3882  inbind[0].is_unsigned = MLM_TRUE;
3883 
3884  std::string addr6 = address.toText();
3885  unsigned long addr6_length = addr6.size();
3886 
3887  inbind[1].buffer_type = MYSQL_TYPE_BLOB;
3888  inbind[1].buffer = reinterpret_cast<char*>
3889  (const_cast<char*>(addr6.c_str()));
3890  inbind[1].length = &addr6_length;
3891  inbind[1].buffer_length = addr6_length;
3892 
3893  ConstHostCollection collection;
3894  impl_->getHostCollection(ctx, MySqlHostDataSourceImpl::GET_HOST_SUBID6_ADDR, inbind,
3895  ctx->host_ipv6_exchange_, collection, false);
3896  return (collection);
3897 }
3898 
3899 // Miscellaneous database methods.
3900 
3901 std::string
3903  std::string name = "";
3904  // Get a context
3905  MySqlHostContextAlloc get_context(*impl_);
3906  MySqlHostContextPtr ctx = get_context.ctx_;
3907 
3908  try {
3909  name = ctx->conn_.getParameter("name");
3910  } catch (...) {
3911  // Return an empty name
3912  }
3913  return (name);
3914 }
3915 
3916 std::string
3918  return (std::string("Host data source that stores host information"
3919  "in MySQL database"));
3920 }
3921 
3922 std::pair<uint32_t, uint32_t>
3924  return(impl_->getVersion());
3925 }
3926 
3927 void
3929  // Get a context
3930  MySqlHostContextAlloc get_context(*impl_);
3931  MySqlHostContextPtr ctx = get_context.ctx_;
3932 
3933  // If operating in read-only mode, throw exception.
3934  impl_->checkReadOnly(ctx);
3935  ctx->conn_.commit();
3936 }
3937 
3938 void
3940  // Get a context
3941  MySqlHostContextAlloc get_context(*impl_);
3942  MySqlHostContextPtr ctx = get_context.ctx_;
3943 
3944  // If operating in read-only mode, throw exception.
3945  impl_->checkReadOnly(ctx);
3946  ctx->conn_.rollback();
3947 }
3948 
3949 bool
3951  impl_->ip_reservations_unique_ = unique;
3952  return (true);
3953 }
3954 
3955 bool
3957  return (impl_->unusable_);
3958 }
3959 
3960 } // namespace dhcp
3961 } // namespace isc
MySqlHostContextPtr createContext() const
Create a new context.
RAII class creating a critical section.
bool my_bool
my_bool type in MySQL 8.x.
Option descriptor.
Definition: cfg_option.h:42
void unspecified(bool unspecified)
Modifies the flag that indicates whether the value is specified or unspecified.
Definition: optional.h:121
static bool dbReconnect(ReconnectCtlPtr db_reconnect_ctl)
Attempts to reconnect the server to the host DB backend manager.
const size_t OPTION_FORMATTED_VALUE_MAX_LEN
Maximum length of option value specified in textual format.
Definition: host.h:48
boost::shared_ptr< MySqlHostContextPool > MySqlHostContextPoolPtr
Type of pointers to context pools.
Wraps value holding size of the page with host reservations.
boost::shared_ptr< CfgOption > CfgOptionPtr
Non-const pointer.
Definition: cfg_option.h:706
Fetch and Release MySQL Results.
const size_t USER_CONTEXT_MAX_LEN
Maximum length of user context.
Definition: host.h:54
bool delStatement(MySqlHostContextPtr &ctx, StatementIndex stindex, MYSQL_BIND *bind)
Executes statements that delete records.
MySqlHostDataSourceImpl(const DatabaseConnection::ParameterMap &parameters)
Constructor.
const size_t CLIENT_CLASSES_MAX_LEN
Maximum length of classes stored in a dhcp4/6_client_classes columns.
Definition: host.h:36
virtual void rollback()
Rollback Transactions.
std::vector< MySqlHostContextPtr > pool_
The vector of available contexts.
#define LOG_INFO(LOGGER, MESSAGE)
Macro to conveniently test info output and log it.
Definition: macros.h:20
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)
A standard Data module exception that is thrown if a parse error is encountered when constructing an ...
Definition: data.h:43
const size_t BOOT_FILE_NAME_MAX_LEN
Maximum length of the boot file name.
Definition: host.h:60
Data is truncated.
Definition: db_exceptions.h:35
virtual bool setIPReservationsUnique(const bool unique)
Controls whether IP reservations are unique or non-unique.
boost::shared_ptr< Host > HostPtr
Pointer to the Host object.
Definition: host.h:785
static std::pair< uint32_t, uint32_t > getVersion(const ParameterMap &parameters)
Get the schema version.
void commit()
Commits transaction.
const asiolink::IOAddress & getPrefix() const
Returns prefix for the reservation.
Definition: host.h:190
const isc::log::MessageID DHCPSRV_MYSQL_HOST_DB_GET_VERSION
boost::shared_ptr< const CfgOption > ConstCfgOptionPtr
Const pointer.
Definition: cfg_option.h:709
virtual ConstHostCollection getAllbyHostname(const std::string &hostname) const
Return all hosts with a hostname.
virtual ConstHostCollection getAll6(const SubnetID &subnet_id) const
Return all hosts in a DHCPv6 subnet.
static CfgMgr & instance()
returns a single instance of Configuration Manager
Definition: cfgmgr.cc:25
const size_t page_size_
Holds page size.
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)
static isc::asiolink::IOServicePtr & getIOService()
Returns pointer to the IO service.
Definition: host_mgr.h:643
boost::shared_ptr< Option > OptionPtr
Definition: option.h:36
const uint32_t MYSQL_SCHEMA_VERSION_MAJOR
Universe
defines option universe DHCPv4 or DHCPv6
Definition: option.h:82
#define LOG_ERROR(LOGGER, MESSAGE)
Macro to conveniently test error output and log it.
Definition: macros.h:32
SrvConfigPtr getCurrentCfg()
Returns a pointer to the current configuration.
Definition: cfgmgr.cc:161
virtual bool isUnusable()
Flag which indicates if the host manager has at least one unusable connection.
STL namespace.
void addStatement(MySqlHostContextPtr &ctx, MySqlHostDataSourceImpl::StatementIndex stindex, std::vector< MYSQL_BIND > &bind)
Executes statements which inserts a row into one of the tables.
const isc::log::MessageID DHCPSRV_MYSQL_HOST_DB_RECONNECT_ATTEMPT_SCHEDULE
const uint32_t MYSQL_SCHEMA_VERSION_MINOR
std::string timer_name_
Timer name used to register database reconnect timer.
static ParameterMap parse(const std::string &dbaccess)
Parse database access string.
void addResv(MySqlHostContextPtr &ctx, const IPv6Resrv &resv, const HostID &id)
Inserts IPv6 Reservation into ipv6_reservation table.
bool unusable_
Indicates if there is at least one connection that can no longer be used for normal operations...
IPv6 reservation for a host.
Definition: host.h:161
const size_t OPTION_SPACE_MAX_LEN
Maximum length of option space name.
Definition: host.h:51
MySqlConnection conn_
MySQL connection.
std::vector< uint8_t > OptionBuffer
buffer types used in DHCP code.
Definition: option.h:24
Exception thrown on failure to open database.
const size_t SERVER_HOSTNAME_MAX_LEN
Maximum length of the server hostname.
Definition: host.h:57
int MysqlExecuteStatement(MYSQL_STMT *stmt)
Execute a prepared statement.
Multiple lease records found where one expected.
Definition: db_exceptions.h:28
DatabaseConnection::ParameterMap parameters_
The parameters.
#define isc_throw(type, stream)
A shortcut macro to insert known values into exception arguments.
A generic exception that is thrown if a parameter given to a method is considered invalid in that con...
std::string formatted_value_
Option value in textual (CSV) format.
Definition: cfg_option.h:66
Definition: edns.h:19
const my_bool MLM_FALSE
MySQL false value.
std::pair< IPv6ResrvIterator, IPv6ResrvIterator > IPv6ResrvRange
Definition: host.h:243
boost::shared_ptr< MySqlHostIPv6Exchange > host_ipv46_exchange_
Pointer to an object representing an exchange which can be used to retrieve hosts, DHCPv4 and DHCPv6 options, and IPv6 reservations using a single query.
std::pair< uint32_t, uint32_t > getVersion() const
Returns backend version.
static bool delBackend(const std::string &db_type)
Delete an alternate host backend (aka host data source).
Definition: host_mgr.cc:53
const int DHCPSRV_DBG_TRACE_DETAIL
Additional information.
Definition: dhcpsrv_log.h:38
boost::shared_ptr< CfgDbAccess > CfgDbAccessPtr
A pointer to the CfgDbAccess.
std::vector< ConstHostPtr > ConstHostCollection
Collection of the const Host objects.
Definition: host.h:791
boost::shared_ptr< MySqlHostWithOptionsExchange > host_ipv4_exchange_
The exchange objects are used for transfer of data to/from the database.
bool persistent_
Persistence flag.
Definition: cfg_option.h:51
A generic exception that is thrown when an unexpected error condition occurs.
const isc::log::MessageID DHCPSRV_MYSQL_HOST_DB_RECONNECT_ATTEMPT_FAILED
virtual void commit()
Commit Transactions.
virtual ~MySqlHostDataSource()
Virtual destructor.
boost::shared_ptr< const Element > ConstElementPtr
Definition: data.h:23
boost::shared_ptr< const Host > ConstHostPtr
Const pointer to the Host object.
Definition: host.h:788
data::ConstElementPtr getContext() const
Returns const pointer to the user context.
Definition: user_context.h:24
void addOptions(MySqlHostContextPtr &ctx, const StatementIndex &stindex, const ConstCfgOptionPtr &options_cfg, const uint64_t host_id)
Inserts multiple options into the database.
Represents a device with IPv4 and/or IPv6 reservations.
Definition: host.h:297
virtual ConstHostCollection getAllbyHostname4(const std::string &hostname, const SubnetID &subnet_id) const
Return all hosts with a hostname in a DHCPv4 subnet.
Type
Type of the reservation.
Definition: host.h:167
IPv6ResrvCollection::const_iterator IPv6ResrvIterator
Definition: host.h:241
virtual const char * what() const
Returns a C-style character string of the cause of the exception.
The OutputBuffer class is a buffer abstraction for manipulating mutable data.
Definition: buffer.h:294
const isc::log::MessageID DHCPSRV_MYSQL_HOST_DB_READONLY
OptionPtr option_
Option instance.
Definition: cfg_option.h:45
const int MLM_MYSQL_FETCH_SUCCESS
check for bool size
virtual std::pair< uint32_t, uint32_t > getVersion() const
Returns backend version.
static bool invokeDbFailedCallback(const ReconnectCtlPtr &db_reconnect_ctl)
Invokes the connection's restore failed connectivity callback.
Authentication keys.
Definition: host.h:75
Defines the logger used by the top-level component of kea-dhcp-ddns.
uint16_t code_
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.
std::function< bool(ReconnectCtlPtr db_reconnect_ctl)> DbCallback
Defines a callback prototype for propagating events upward.
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...
bool ip_reservations_unique_
Holds the setting whether the IP reservations must be unique or may be non-unique.
const isc::log::MessageID DHCPSRV_MYSQL_HOST_DB_RECONNECT_FAILED
MySqlHostContextPoolPtr pool_
The pool of contexts.
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.
static bool invokeDbRecoveredCallback(const ReconnectCtlPtr &db_reconnect_ctl)
Invokes the connection's restored connectivity callback.
virtual ConstHostCollection getAllbyHostname6(const std::string &hostname, const SubnetID &subnet_id) const
Return all hosts with a hostname in a DHCPv6 subnet.
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 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...
Implementation of the MySqlHostDataSource.
MySqlHostContextAlloc(MySqlHostDataSourceImpl &mgr)
Constructor.
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.
const int MLM_MYSQL_FETCH_FAILURE
MySQL fetch failure code.
Type getType() const
Returns reservation type.
Definition: host.h:204
static bool invokeDbLostCallback(const ReconnectCtlPtr &db_reconnect_ctl)
Invokes the connection's lost connectivity callback.
#define DHCP6_OPTION_SPACE
void checkReadOnly(MySqlHostContextPtr &ctx) const
Throws exception if database is read only.
RAII object representing MySQL transaction.
#define DHCP4_OPTION_SPACE
global std option spaces
static void addBackend(const std::string &access)
Add an alternate host backend (aka host data source).
Definition: host_mgr.cc:48
boost::shared_ptr< OptionContainer > OptionContainerPtr
Pointer to the OptionContainer object.
Definition: cfg_option.h:272
#define LOG_DEBUG(LOGGER, LEVEL, MESSAGE)
Macro to conveniently test debug output and log it.
Definition: macros.h:14
bool is_readonly_
Indicates if the database is opened in read only mode.
boost::shared_ptr< MySqlHostContext > MySqlHostContextPtr
Type of pointers to contexts.
Attempt to modify data in read-only database.
Definition: db_exceptions.h:56
boost::shared_ptr< MySqlHostIPv6Exchange > host_ipv6_exchange_
Pointer to an object representing an exchange which can be used to retrieve hosts, DHCPv6 options and IPv6 reservations.
boost::shared_ptr< OptionDefinition > OptionDefinitionPtr
Pointer to option definition object.
boost::shared_ptr< MySqlIPv6ReservationExchange > host_ipv6_reservation_exchange_
Pointer to an object representing an exchange which can be used to insert new IPv6 reservation...
void checkError(MySqlHostContextPtr &ctx, const int status, const StatementIndex index, const char *what) const
Check Error and Throw Exception.
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 ...
isc::log::Logger dhcpsrv_logger("dhcpsrv")
DHCP server library Logger.
Definition: dhcpsrv_log.h:56
IdentifierType
Type of the host identifier.
Definition: host.h:307
std::function< isc::asiolink::IOServicePtr()> IOServiceAccessor
Function which returns the IOService that can be used to recover the connection.
const size_t TEXT_AUTH_KEY_LEN
Maximum length of authentication keys (coded in hexadecimal).
Definition: host.h:66
std::map< std::string, std::string > ParameterMap
Database configuration parameter map.
uint8_t getPrefixLen() const
Returns prefix length.
Definition: host.h:195
virtual std::string getDescription() const
Returns description of the backend.
static const TimerMgrPtr & instance()
Returns pointer to the sole instance of the TimerMgr.
Definition: timer_mgr.cc:441
virtual std::string getName() const
Returns backend name.
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.
boost::shared_ptr< ReconnectCtl > ReconnectCtlPtr
Pointer to an instance of ReconnectCtl.
static const StatementIndex WRITE_STMTS_BEGIN
Index of first statement performing write to the database.
const size_t OPTION_VALUE_MAX_LEN
Maximum length of option value.
Definition: host.h:45
uint64_t HostID
HostID (used only when storing in MySQL, PostgreSQL or Cassandra)
Definition: host.h:69
virtual ConstHostCollection getAll4(const SubnetID &subnet_id) const
Return all hosts in a DHCPv4 subnet.
A template representing an optional value.
Definition: optional.h:36
std::mutex mutex_
The mutex to protect pool access.
virtual bool del(const SubnetID &subnet_id, const asiolink::IOAddress &addr)
Attempts to delete hosts by (subnet-id, address)
Exception thrown on failure to execute a database function.
const my_bool MLM_TRUE
MySQL true value.
MySqlHostDataSource(const db::DatabaseConnection::ParameterMap &parameters)
Constructor.
virtual isc::db::DatabaseConnection::ParameterMap getParameters() const
Return backend parameters.
boost::shared_ptr< IOServiceAccessor > IOServiceAccessorPtr
Pointer to an instance of IOServiceAccessor.
Database duplicate entry error.
Definition: db_exceptions.h:42
virtual void add(const HostPtr &host)
Adds a new host to the collection.
uint32_t SubnetID
Unique identifier for a subnet (both v4 and v6)
Definition: lease.h:24
Common MySQL Connector Pool.
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.