asiolink.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. // Copyright (C) 2010 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. // $Id$
  15. #ifndef __ASIOLINK_H
  16. #define __ASIOLINK_H 1
  17. // IMPORTANT NOTE: only very few ASIO headers files can be included in
  18. // this file. In particular, asio.hpp should never be included here.
  19. // See the description of the namespace below.
  20. #include <unistd.h> // for some network system calls
  21. #include <asio/ip/address.hpp>
  22. #include <boost/shared_ptr.hpp>
  23. #include <boost/function.hpp>
  24. #include <functional>
  25. #include <string>
  26. #include <vector>
  27. #include <utility>
  28. #include <dns/buffer.h>
  29. #include <dns/message.h>
  30. #include <dns/question.h>
  31. #include <exceptions/exceptions.h>
  32. #include <asiolink/ioaddress.h>
  33. #include <asiolink/ioendpoint.h>
  34. #include <asiolink/iomessage.h>
  35. #include <asiolink/iosocket.h>
  36. namespace asio {
  37. // forward declaration for IOService::get_io_service() below
  38. class io_service;
  39. }
  40. /// \namespace asiolink
  41. /// \brief A wrapper interface for the ASIO library.
  42. ///
  43. /// The \c asiolink namespace is used to define a set of wrapper interfaces
  44. /// for the ASIO library.
  45. ///
  46. /// BIND 10 uses the non-Boost version of ASIO because it's header-only,
  47. /// i.e., does not require a separate library object to be linked, and thus
  48. /// lowers the bar for introduction.
  49. ///
  50. /// But the advantage comes with its own costs: since the header-only version
  51. /// includes more definitions in public header files, it tends to trigger
  52. /// more compiler warnings for our own sources, and, depending on the
  53. /// compiler options, may make the build fail.
  54. ///
  55. /// We also found it may be tricky to use ASIO and standard C++ libraries
  56. /// in a single translation unit, i.e., a .cc file: depending on the order
  57. /// of including header files, ASIO may or may not work on some platforms.
  58. ///
  59. /// This wrapper interface is intended to centralize these
  60. /// problematic issues in a single sub module. Other BIND 10 modules should
  61. /// simply include \c asiolink.h and use the wrapper API instead of
  62. /// including ASIO header files and using ASIO-specific classes directly.
  63. ///
  64. /// This wrapper may be used for other IO libraries if and when we want to
  65. /// switch, but generality for that purpose is not the primary goal of
  66. /// this module. The resulting interfaces are thus straightforward mapping
  67. /// to the ASIO counterparts.
  68. ///
  69. /// Notes to developers:
  70. /// Currently the wrapper interface is fairly specific to use by a
  71. /// DNS server, i.e., b10-auth or b10-resolver. But the plan is to
  72. /// generalize it and have other modules use it as well.
  73. ///
  74. /// One obvious drawback of this approach is performance overhead
  75. /// due to the additional layer. We should eventually evaluate the cost
  76. /// of the wrapper abstraction in benchmark tests. Another drawback is
  77. /// that the wrapper interfaces don't provide all features of ASIO
  78. /// (at least for the moment). We should also re-evaluate the
  79. /// maintenance overhead of providing necessary wrappers as we develop
  80. /// more.
  81. ///
  82. /// On the other hand, we may be able to exploit the wrapper approach to
  83. /// simplify the interfaces (by limiting the usage) and unify performance
  84. /// optimization points.
  85. ///
  86. /// As for optimization, we may want to provide a custom allocator for
  87. /// the placeholder of callback handlers:
  88. /// http://think-async.com/Asio/asio-1.3.1/doc/asio/reference/asio_handler_allocate.html
  89. namespace asiolink {
  90. class DNSServiceImpl;
  91. struct IOServiceImpl;
  92. struct IntervalTimerImpl;
  93. /// \brief An exception that is thrown if an error occurs within the IO
  94. /// module. This is mainly intended to be a wrapper exception class for
  95. /// ASIO specific exceptions.
  96. class IOError : public isc::Exception {
  97. public:
  98. IOError(const char* file, size_t line, const char* what) :
  99. isc::Exception(file, line, what) {}
  100. };
  101. /// \brief Forward declarations for classes used below
  102. class SimpleCallback;
  103. class DNSLookup;
  104. class DNSAnswer;
  105. /// \brief The \c IOService class is a wrapper for the ASIO \c io_service
  106. /// class.
  107. ///
  108. class IOService {
  109. ///
  110. /// \name Constructors and Destructor
  111. ///
  112. /// Note: The copy constructor and the assignment operator are
  113. /// intentionally defined as private, making this class non-copyable.
  114. //@{
  115. private:
  116. IOService(const IOService& source);
  117. IOService& operator=(const IOService& source);
  118. public:
  119. /// \brief The constructor
  120. IOService();
  121. /// \brief The destructor.
  122. ~IOService();
  123. //@}
  124. /// \brief Start the underlying event loop.
  125. ///
  126. /// This method does not return control to the caller until
  127. /// the \c stop() method is called via some handler.
  128. void run();
  129. /// \brief Run the underlying event loop for a single event.
  130. ///
  131. /// This method return control to the caller as soon as the
  132. /// first handler has completed. (If no handlers are ready when
  133. /// it is run, it will block until one is.)
  134. void run_one();
  135. /// \brief Stop the underlying event loop.
  136. ///
  137. /// This will return the control to the caller of the \c run() method.
  138. void stop();
  139. /// \brief Return the native \c io_service object used in this wrapper.
  140. ///
  141. /// This is a short term work around to support other BIND 10 modules
  142. /// that share the same \c io_service with the authoritative server.
  143. /// It will eventually be removed once the wrapper interface is
  144. /// generalized.
  145. asio::io_service& get_io_service();
  146. private:
  147. IOServiceImpl* io_impl_;
  148. };
  149. ///
  150. /// DNSService is the service that handles DNS queries and answers with
  151. /// a given IOService. This class is mainly intended to hold all the
  152. /// logic that is shared between the authoritative and the recursive
  153. /// server implementations. As such, it handles asio, including config
  154. /// updates (through the 'Checkinprovider'), and listening sockets.
  155. ///
  156. class DNSService {
  157. ///
  158. /// \name Constructors and Destructor
  159. ///
  160. /// Note: The copy constructor and the assignment operator are
  161. /// intentionally defined as private, making this class non-copyable.
  162. //@{
  163. private:
  164. DNSService(const DNSService& source);
  165. DNSService& operator=(const DNSService& source);
  166. public:
  167. /// \brief The constructor with a specific IP address and port on which
  168. /// the services listen on.
  169. ///
  170. /// \param io_service The IOService to work with
  171. /// \param port the port to listen on
  172. /// \param address the IP address to listen on
  173. /// \param checkin Provider for cc-channel events (see \c SimpleCallback)
  174. /// \param lookup The lookup provider (see \c DNSLookup)
  175. /// \param answer The answer provider (see \c DNSAnswer)
  176. DNSService(IOService& io_service, const char& port,
  177. const char& address, SimpleCallback* checkin,
  178. DNSLookup* lookup, DNSAnswer* answer);
  179. /// \brief The constructor with a specific port on which the services
  180. /// listen on.
  181. ///
  182. /// It effectively listens on "any" IPv4 and/or IPv6 addresses.
  183. /// IPv4/IPv6 services will be available if and only if \c use_ipv4
  184. /// or \c use_ipv6 is \c true, respectively.
  185. ///
  186. /// \param io_service The IOService to work with
  187. /// \param port the port to listen on
  188. /// \param ipv4 If true, listen on ipv4 'any'
  189. /// \param ipv6 If true, listen on ipv6 'any'
  190. /// \param checkin Provider for cc-channel events (see \c SimpleCallback)
  191. /// \param lookup The lookup provider (see \c DNSLookup)
  192. /// \param answer The answer provider (see \c DNSAnswer)
  193. DNSService(IOService& io_service, const char& port,
  194. const bool use_ipv4, const bool use_ipv6,
  195. SimpleCallback* checkin, DNSLookup* lookup,
  196. DNSAnswer* answer);
  197. /// \brief The constructor without any servers.
  198. ///
  199. /// Use addServer() to add some servers.
  200. DNSService(IOService& io_service, SimpleCallback* checkin,
  201. DNSLookup* lookup, DNSAnswer* answer);
  202. /// \brief The destructor.
  203. ~DNSService();
  204. //@}
  205. /// \brief Add another server to the service
  206. void addServer(uint16_t port, const std::string &address);
  207. void addServer(const char &port, const std::string &address);
  208. /// \brief Remove all servers from the service
  209. void clearServers();
  210. /// \brief Return the native \c io_service object used in this wrapper.
  211. ///
  212. /// This is a short term work around to support other BIND 10 modules
  213. /// that share the same \c io_service with the authoritative server.
  214. /// It will eventually be removed once the wrapper interface is
  215. /// generalized.
  216. asio::io_service& get_io_service() { return io_service_.get_io_service(); }
  217. private:
  218. DNSServiceImpl* impl_;
  219. IOService& io_service_;
  220. };
  221. /// \brief The \c DNSServer class is a wrapper (and base class) for
  222. /// classes which provide DNS server functionality.
  223. ///
  224. /// The classes derived from this one, \c TCPServer and \c UDPServer,
  225. /// act as the interface layer between clients sending queries, and
  226. /// functions defined elsewhere that provide answers to those queries.
  227. /// Those functions are described in more detail below under
  228. /// \c SimpleCallback, \c DNSLookup, and \c DNSAnswer.
  229. ///
  230. /// Notes to developers:
  231. /// When constructed, this class (and its derived classes) will have its
  232. /// "self_" member set to point to "this". Objects of this class (as
  233. /// instantiated through a base class) are sometimes passed by
  234. /// reference (as this superclass); calls to methods in the base
  235. /// class are then rerouted via this pointer to methods in the derived
  236. /// class. This allows code from outside asiolink, with no specific
  237. /// knowledge of \c TCPServer or \c UDPServer, to access their methods.
  238. ///
  239. /// This class is both assignable and copy-constructable. Its subclasses
  240. /// use the "stackless coroutine" pattern, meaning that it will copy itself
  241. /// when "forking", and that instances will be posted as ASIO handler
  242. /// objects, which are always copied.
  243. ///
  244. /// Because these objects are frequently copied, it is recommended
  245. /// that derived classes be kept small to reduce copy overhead.
  246. class DNSServer {
  247. protected:
  248. ///
  249. /// \name Constructors and destructors
  250. ///
  251. /// This is intentionally defined as \c protected, as this base class
  252. /// should never be instantiated except as part of a derived class.
  253. //@{
  254. DNSServer() : self_(this) {}
  255. public:
  256. /// \brief The destructor
  257. virtual ~DNSServer() {}
  258. //@}
  259. ///
  260. /// \name Class methods
  261. ///
  262. /// These methods all make their calls indirectly via the "self_"
  263. /// pointer, ensuring that the functions ultimately invoked will be
  264. /// the ones in the derived class. This makes it possible to pass
  265. /// instances of derived classes as references to this base class
  266. /// without losing access to derived class data.
  267. ///
  268. //@{
  269. /// \brief The funtion operator
  270. virtual void operator()(asio::error_code ec = asio::error_code(),
  271. size_t length = 0)
  272. {
  273. (*self_)(ec, length);
  274. }
  275. /// \brief Resume processing of the server coroutine after an
  276. /// asynchronous call (e.g., to the DNS Lookup provider) has completed.
  277. ///
  278. /// \param done If true, this signals the system there is an answer
  279. /// to return.
  280. virtual void resume(const bool done) { self_->resume(done); }
  281. /// \brief Indicate whether the server is able to send an answer
  282. /// to a query.
  283. ///
  284. /// This is presently used only for testing purposes.
  285. virtual bool hasAnswer() { return (self_->hasAnswer()); }
  286. /// \brief Returns the current value of the 'coroutine' object
  287. ///
  288. /// This is a temporary method, intended to be used for debugging
  289. /// purposes during development and removed later. It allows
  290. /// callers from outside the coroutine object to retrieve information
  291. /// about its current state.
  292. ///
  293. /// \return The value of the 'coroutine' object
  294. virtual int value() { return (self_->value()); }
  295. /// \brief Returns a pointer to a clone of this DNSServer object.
  296. ///
  297. /// When a \c DNSServer object is copied or assigned, the result will
  298. /// normally be another \c DNSServer object containing a copy
  299. /// of the original "self_" pointer. Calling clone() guarantees
  300. /// that the underlying object is also correctly copied.
  301. ///
  302. /// \return A deep copy of this DNSServer object
  303. virtual DNSServer* clone() { return (self_->clone()); }
  304. //@}
  305. protected:
  306. /// \brief Lookup handler object.
  307. ///
  308. /// This is a protected class; it can only be instantiated
  309. /// from within a derived class of \c DNSServer.
  310. ///
  311. /// A server object that has received a query creates an instance
  312. /// of this class and scheudles it on the ASIO service queue
  313. /// using asio::io_service::post(). When the handler executes, it
  314. /// calls the asyncLookup() method in the server object to start a
  315. /// DNS lookup. When the lookup is complete, the server object is
  316. /// scheduled to resume, again using io_service::post().
  317. ///
  318. /// Note that the calling object is copied into the handler object,
  319. /// not referenced. This is because, once the calling object yields
  320. /// control to the handler, it falls out of scope and may disappear
  321. template <typename T>
  322. class AsyncLookup {
  323. public:
  324. AsyncLookup(T& caller) : caller_(caller) {}
  325. void operator()() { caller_.asyncLookup(); }
  326. private:
  327. T caller_;
  328. };
  329. /// \brief Carries out a DNS lookup.
  330. ///
  331. /// This function calls the \c DNSLookup object specified by the
  332. /// DNS server when the \c IOService was created, passing along
  333. /// the details of the query and a pointer back to the current
  334. /// server object. It is called asynchronously via the AsyncLookup
  335. /// handler class.
  336. virtual void asyncLookup() { self_->asyncLookup(); }
  337. private:
  338. DNSServer* self_;
  339. };
  340. /// \brief The \c DNSLookup class is an abstract base class for a DNS
  341. /// Lookup provider function.
  342. ///
  343. /// Specific derived class implementations are hidden within the
  344. /// implementation. Instances of the derived classes can be called
  345. /// as functions via the operator() interface. Pointers to these
  346. /// instances can then be provided to the \c IOService class
  347. /// via its constructor.
  348. ///
  349. /// A DNS Lookup provider function obtains the data needed to answer
  350. /// a DNS query (e.g., from authoritative data source, cache, or upstream
  351. /// query). After it has run, the OutputBuffer object passed to it
  352. /// should contain the answer to the query, in an internal representation.
  353. class DNSLookup {
  354. ///
  355. /// \name Constructors and Destructor
  356. ///
  357. /// Note: The copy constructor and the assignment operator are
  358. /// intentionally defined as private, making this class non-copyable.
  359. //@{
  360. private:
  361. DNSLookup(const DNSLookup& source);
  362. DNSLookup& operator=(const DNSLookup& source);
  363. protected:
  364. /// \brief The default constructor.
  365. ///
  366. /// This is intentionally defined as \c protected as this base class
  367. /// should never be instantiated (except as part of a derived class).
  368. DNSLookup() : self_(this) {}
  369. public:
  370. /// \brief The destructor
  371. virtual ~DNSLookup() {}
  372. //@}
  373. /// \brief The function operator
  374. ///
  375. /// This makes its call indirectly via the "self" pointer, ensuring
  376. /// that the function ultimately invoked will be the one in the derived
  377. /// class.
  378. ///
  379. /// \param io_message The event message to handle
  380. /// \param message The DNS MessagePtr that needs handling
  381. /// \param buffer The final answer is put here
  382. /// \param DNSServer DNSServer object to use
  383. virtual void operator()(const IOMessage& io_message,
  384. isc::dns::MessagePtr message,
  385. isc::dns::MessagePtr answer_message,
  386. isc::dns::OutputBufferPtr buffer,
  387. DNSServer* server) const
  388. {
  389. (*self_)(io_message, message, answer_message, buffer, server);
  390. }
  391. private:
  392. DNSLookup* self_;
  393. };
  394. /// \brief The \c DNSAnswer class is an abstract base class for a DNS
  395. /// Answer provider function.
  396. ///
  397. /// Specific derived class implementations are hidden within the
  398. /// implementation. Instances of the derived classes can be called
  399. /// as functions via the operator() interface. Pointers to these
  400. /// instances can then be provided to the \c IOService class
  401. /// via its constructor.
  402. ///
  403. /// A DNS Answer provider function takes answer data that has been obtained
  404. /// from a DNS Lookup provider functon and readies it to be sent to the
  405. /// client. After it has run, the OutputBuffer object passed to it should
  406. /// contain the answer to the query rendered into wire format.
  407. class DNSAnswer {
  408. ///
  409. /// \name Constructors and Destructor
  410. ///
  411. /// Note: The copy constructor and the assignment operator are
  412. /// intentionally defined as private, making this class non-copyable.
  413. //@{
  414. private:
  415. DNSAnswer(const DNSAnswer& source);
  416. DNSAnswer& operator=(const DNSAnswer& source);
  417. protected:
  418. /// \brief The default constructor.
  419. ///
  420. /// This is intentionally defined as \c protected as this base class
  421. /// should never be instantiated (except as part of a derived class).
  422. DNSAnswer() {}
  423. public:
  424. /// \brief The destructor
  425. virtual ~DNSAnswer() {}
  426. //@}
  427. /// \brief The function operator
  428. ///
  429. /// This makes its call indirectly via the "self" pointer, ensuring
  430. /// that the function ultimately invoked will be the one in the derived
  431. /// class.
  432. ///
  433. /// \param io_message The event message to handle
  434. /// \param message The DNS MessagePtr that needs handling
  435. /// \param buffer The result is put here
  436. virtual void operator()(const IOMessage& io_message,
  437. isc::dns::MessagePtr message,
  438. isc::dns::MessagePtr answer_message,
  439. isc::dns::OutputBufferPtr buffer) const = 0;
  440. };
  441. /// \brief The \c SimpleCallback class is an abstract base class for a
  442. /// simple callback function with the signature:
  443. ///
  444. /// void simpleCallback(const IOMessage& io_message) const;
  445. ///
  446. /// Specific derived class implementations are hidden within the
  447. /// implementation. Instances of the derived classes can be called
  448. /// as functions via the operator() interface. Pointers to these
  449. /// instances can then be provided to the \c IOService class
  450. /// via its constructor.
  451. ///
  452. /// The \c SimpleCallback is expected to be used for basic, generic
  453. /// tasks such as checking for configuration changes. It may also be
  454. /// used for testing purposes.
  455. class SimpleCallback {
  456. ///
  457. /// \name Constructors and Destructor
  458. ///
  459. /// Note: The copy constructor and the assignment operator are
  460. /// intentionally defined as private, making this class non-copyable.
  461. //@{
  462. private:
  463. SimpleCallback(const SimpleCallback& source);
  464. SimpleCallback& operator=(const SimpleCallback& source);
  465. protected:
  466. /// \brief The default constructor.
  467. ///
  468. /// This is intentionally defined as \c protected as this base class
  469. /// should never be instantiated (except as part of a derived class).
  470. SimpleCallback() : self_(this) {}
  471. public:
  472. /// \brief The destructor
  473. virtual ~SimpleCallback() {}
  474. /// \brief The function operator
  475. //@}
  476. ///
  477. /// This makes its call indirectly via the "self" pointer, ensuring
  478. /// that the function ultimately invoked will be the one in the derived
  479. /// class.
  480. ///
  481. /// \param io_message The event message to handle
  482. virtual void operator()(const IOMessage& io_message) const {
  483. (*self_)(io_message);
  484. }
  485. private:
  486. SimpleCallback* self_;
  487. };
  488. /// \brief The \c RecursiveQuery class provides a layer of abstraction around
  489. /// the ASIO code that carries out an upstream query.
  490. ///
  491. /// This design is very preliminary; currently it is only capable of
  492. /// handling simple forward requests to a single resolver.
  493. class RecursiveQuery {
  494. ///
  495. /// \name Constructors
  496. ///
  497. //@{
  498. public:
  499. /// \brief Constructor for use when acting as a forwarder
  500. ///
  501. /// This is currently the only way to construct \c RecursiveQuery
  502. /// object. The addresses of the forward nameservers is specified,
  503. /// and every upstream query will be sent to one random address.
  504. /// \param dns_service The DNS Service to perform the recursive
  505. /// query on.
  506. /// \param upstream Addresses and ports of the upstream servers
  507. /// to forward queries to.
  508. /// \param upstream_root Addresses and ports of the root servers
  509. /// to use when resolving.
  510. /// \param timeout How long to timeout the query, in ms
  511. /// -1 means never timeout (but do not use that).
  512. /// TODO: This should be computed somehow dynamically in future
  513. /// \param retries how many times we try again (0 means just send and
  514. /// and return if it returs).
  515. RecursiveQuery(DNSService& dns_service,
  516. const std::vector<std::pair<std::string, uint16_t> >&
  517. upstream,
  518. const std::vector<std::pair<std::string, uint16_t> >&
  519. upstream_root,
  520. int timeout = -1, unsigned retries = 0);
  521. //@}
  522. /// \brief Initiates an upstream query in the \c RecursiveQuery object.
  523. ///
  524. /// When sendQuery() is called, a message is sent asynchronously to
  525. /// the upstream name server. When a reply arrives, 'server'
  526. /// is placed on the ASIO service queue via io_service::post(), so
  527. /// that the original \c DNSServer objct can resume processing.
  528. ///
  529. /// \param question The question being answered <qname/qclass/qtype>
  530. /// \param buffer An output buffer into which the response can be copied
  531. /// \param server A pointer to the \c DNSServer object handling the client
  532. void sendQuery(const isc::dns::Question& question,
  533. isc::dns::MessagePtr answer_message,
  534. isc::dns::OutputBufferPtr buffer,
  535. DNSServer* server);
  536. private:
  537. DNSService& dns_service_;
  538. boost::shared_ptr<std::vector<std::pair<std::string, uint16_t> > >
  539. upstream_;
  540. boost::shared_ptr<std::vector<std::pair<std::string, uint16_t> > >
  541. upstream_root_;
  542. int timeout_;
  543. unsigned retries_;
  544. };
  545. /// \brief The \c IntervalTimer class is a wrapper for the ASIO
  546. /// \c asio::deadline_timer class.
  547. ///
  548. /// This class is implemented to use \c asio::deadline_timer as
  549. /// interval timer.
  550. ///
  551. /// \c setupTimer() sets a timer to expire on (now + interval) and
  552. /// a call back function.
  553. ///
  554. /// \c IntervalTimerImpl::callback() is called by the timer when
  555. /// it expires.
  556. ///
  557. /// The function calls the call back function set by \c setupTimer()
  558. /// and updates the timer to expire in (now + interval) seconds.
  559. /// The type of call back function is \c void(void).
  560. ///
  561. /// The call back function will not be called if the instance of this
  562. /// class is destructed before the timer is expired.
  563. ///
  564. /// Note: Destruction of an instance of this class while call back
  565. /// is pending causes throwing an exception from \c IOService.
  566. ///
  567. /// Sample code:
  568. /// \code
  569. /// void function_to_call_back() {
  570. /// // this function will be called periodically
  571. /// }
  572. /// int interval_in_seconds = 1;
  573. /// IOService io_service;
  574. ///
  575. /// IntervalTimer intervalTimer(io_service);
  576. /// intervalTimer.setupTimer(function_to_call_back, interval_in_seconds);
  577. /// io_service.run();
  578. /// \endcode
  579. ///
  580. class IntervalTimer {
  581. public:
  582. /// \name The type of timer callback function
  583. typedef boost::function<void()> Callback;
  584. ///
  585. /// \name Constructors and Destructor
  586. ///
  587. /// Note: The copy constructor and the assignment operator are
  588. /// intentionally defined as private, making this class non-copyable.
  589. //@{
  590. private:
  591. IntervalTimer(const IntervalTimer& source);
  592. IntervalTimer& operator=(const IntervalTimer& source);
  593. public:
  594. /// \brief The constructor with \c IOService.
  595. ///
  596. /// This constructor may throw a standard exception if
  597. /// memory allocation fails inside the method.
  598. /// This constructor may also throw \c asio::system_error.
  599. ///
  600. /// \param io_service A reference to an instance of IOService
  601. ///
  602. IntervalTimer(IOService& io_service);
  603. /// \brief The destructor.
  604. ///
  605. /// This destructor never throws an exception.
  606. ///
  607. /// On the destruction of this class the timer will be canceled
  608. /// inside \c asio::deadline_timer.
  609. ///
  610. ~IntervalTimer();
  611. //@}
  612. /// \brief Register timer callback function and interval.
  613. ///
  614. /// This function sets callback function and interval in seconds.
  615. /// Timer will actually start after calling \c IOService::run().
  616. ///
  617. /// \param cbfunc A reference to a function \c void(void) to call back
  618. /// when the timer is expired (should not be an empty functor)
  619. /// \param interval Interval in seconds (greater than 0)
  620. ///
  621. /// Note: IntervalTimer will not pass \c asio::error_code to
  622. /// call back function. In case the timer is cancelled, the function
  623. /// will not be called.
  624. ///
  625. /// \throw isc::InvalidParameter cbfunc is empty
  626. /// \throw isc::BadValue interval is 0
  627. /// \throw isc::Unexpected ASIO library error
  628. ///
  629. void setupTimer(const Callback& cbfunc, const uint32_t interval);
  630. private:
  631. IntervalTimerImpl* impl_;
  632. };
  633. } // asiolink
  634. #endif // __ASIOLINK_H
  635. // Local Variables:
  636. // mode: c++
  637. // End: