asiolink.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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::OutputBufferPtr buffer,
  386. DNSServer* server) const
  387. {
  388. (*self_)(io_message, message, buffer, server);
  389. }
  390. private:
  391. DNSLookup* self_;
  392. };
  393. /// \brief The \c DNSAnswer class is an abstract base class for a DNS
  394. /// Answer provider function.
  395. ///
  396. /// Specific derived class implementations are hidden within the
  397. /// implementation. Instances of the derived classes can be called
  398. /// as functions via the operator() interface. Pointers to these
  399. /// instances can then be provided to the \c IOService class
  400. /// via its constructor.
  401. ///
  402. /// A DNS Answer provider function takes answer data that has been obtained
  403. /// from a DNS Lookup provider functon and readies it to be sent to the
  404. /// client. After it has run, the OutputBuffer object passed to it should
  405. /// contain the answer to the query rendered into wire format.
  406. class DNSAnswer {
  407. ///
  408. /// \name Constructors and Destructor
  409. ///
  410. /// Note: The copy constructor and the assignment operator are
  411. /// intentionally defined as private, making this class non-copyable.
  412. //@{
  413. private:
  414. DNSAnswer(const DNSAnswer& source);
  415. DNSAnswer& operator=(const DNSAnswer& source);
  416. protected:
  417. /// \brief The default constructor.
  418. ///
  419. /// This is intentionally defined as \c protected as this base class
  420. /// should never be instantiated (except as part of a derived class).
  421. DNSAnswer() {}
  422. public:
  423. /// \brief The destructor
  424. virtual ~DNSAnswer() {}
  425. //@}
  426. /// \brief The function operator
  427. ///
  428. /// This makes its call indirectly via the "self" pointer, ensuring
  429. /// that the function ultimately invoked will be the one in the derived
  430. /// class.
  431. ///
  432. /// \param io_message The event message to handle
  433. /// \param message The DNS MessagePtr that needs handling
  434. /// \param buffer The result is put here
  435. virtual void operator()(const IOMessage& io_message,
  436. isc::dns::MessagePtr message,
  437. isc::dns::OutputBufferPtr buffer) const = 0;
  438. };
  439. /// \brief The \c SimpleCallback class is an abstract base class for a
  440. /// simple callback function with the signature:
  441. ///
  442. /// void simpleCallback(const IOMessage& io_message) const;
  443. ///
  444. /// Specific derived class implementations are hidden within the
  445. /// implementation. Instances of the derived classes can be called
  446. /// as functions via the operator() interface. Pointers to these
  447. /// instances can then be provided to the \c IOService class
  448. /// via its constructor.
  449. ///
  450. /// The \c SimpleCallback is expected to be used for basic, generic
  451. /// tasks such as checking for configuration changes. It may also be
  452. /// used for testing purposes.
  453. class SimpleCallback {
  454. ///
  455. /// \name Constructors and Destructor
  456. ///
  457. /// Note: The copy constructor and the assignment operator are
  458. /// intentionally defined as private, making this class non-copyable.
  459. //@{
  460. private:
  461. SimpleCallback(const SimpleCallback& source);
  462. SimpleCallback& operator=(const SimpleCallback& source);
  463. protected:
  464. /// \brief The default constructor.
  465. ///
  466. /// This is intentionally defined as \c protected as this base class
  467. /// should never be instantiated (except as part of a derived class).
  468. SimpleCallback() : self_(this) {}
  469. public:
  470. /// \brief The destructor
  471. virtual ~SimpleCallback() {}
  472. /// \brief The function operator
  473. //@}
  474. ///
  475. /// This makes its call indirectly via the "self" pointer, ensuring
  476. /// that the function ultimately invoked will be the one in the derived
  477. /// class.
  478. ///
  479. /// \param io_message The event message to handle
  480. virtual void operator()(const IOMessage& io_message) const {
  481. (*self_)(io_message);
  482. }
  483. private:
  484. SimpleCallback* self_;
  485. };
  486. /// \brief The \c RecursiveQuery class provides a layer of abstraction around
  487. /// the ASIO code that carries out an upstream query.
  488. ///
  489. /// This design is very preliminary; currently it is only capable of
  490. /// handling simple forward requests to a single resolver.
  491. class RecursiveQuery {
  492. ///
  493. /// \name Constructors
  494. ///
  495. //@{
  496. public:
  497. /// \brief Constructor for use when acting as a forwarder
  498. ///
  499. /// This is currently the only way to construct \c RecursiveQuery
  500. /// object. The addresses of the forward nameservers is specified,
  501. /// and every upstream query will be sent to one random address.
  502. /// \param dns_service The DNS Service to perform the recursive
  503. /// query on.
  504. /// \param upstream Addresses and ports of the upstream servers
  505. /// to forward queries to.
  506. /// \param timeout How long to timeout the query, in ms
  507. /// -1 means never timeout (but do not use that).
  508. /// TODO: This should be computed somehow dynamically in future
  509. /// \param retries how many times we try again (0 means just send and
  510. /// and return if it returs).
  511. RecursiveQuery(DNSService& dns_service,
  512. const std::vector<std::pair<std::string, uint16_t> >&
  513. upstream, int query_timeout = 2000,
  514. int client_timeout = 4000,
  515. int lookup_timeout = 30000,
  516. unsigned retries = 3);
  517. //@}
  518. /// \brief Initiates an upstream query in the \c RecursiveQuery object.
  519. ///
  520. /// When sendQuery() is called, a message is sent asynchronously to
  521. /// the upstream name server. When a reply arrives, 'server'
  522. /// is placed on the ASIO service queue via io_service::post(), so
  523. /// that the original \c DNSServer objct can resume processing.
  524. ///
  525. /// \param question The question being answered <qname/qclass/qtype>
  526. /// \param buffer An output buffer into which the response can be copied
  527. /// \param server A pointer to the \c DNSServer object handling the client
  528. void sendQuery(const isc::dns::Question& question,
  529. isc::dns::OutputBufferPtr buffer,
  530. DNSServer* server);
  531. private:
  532. DNSService& dns_service_;
  533. boost::shared_ptr<std::vector<std::pair<std::string, uint16_t> > >
  534. upstream_;
  535. int query_timeout_;
  536. int client_timeout_;
  537. int lookup_timeout_;
  538. unsigned retries_;
  539. };
  540. /// \brief The \c IntervalTimer class is a wrapper for the ASIO
  541. /// \c asio::deadline_timer class.
  542. ///
  543. /// This class is implemented to use \c asio::deadline_timer as
  544. /// interval timer.
  545. ///
  546. /// \c setupTimer() sets a timer to expire on (now + interval) and
  547. /// a call back function.
  548. ///
  549. /// \c IntervalTimerImpl::callback() is called by the timer when
  550. /// it expires.
  551. ///
  552. /// The function calls the call back function set by \c setupTimer()
  553. /// and updates the timer to expire in (now + interval) seconds.
  554. /// The type of call back function is \c void(void).
  555. ///
  556. /// The call back function will not be called if the instance of this
  557. /// class is destructed before the timer is expired.
  558. ///
  559. /// Note: Destruction of an instance of this class while call back
  560. /// is pending causes throwing an exception from \c IOService.
  561. ///
  562. /// Sample code:
  563. /// \code
  564. /// void function_to_call_back() {
  565. /// // this function will be called periodically
  566. /// }
  567. /// int interval_in_seconds = 1;
  568. /// IOService io_service;
  569. ///
  570. /// IntervalTimer intervalTimer(io_service);
  571. /// intervalTimer.setupTimer(function_to_call_back, interval_in_seconds);
  572. /// io_service.run();
  573. /// \endcode
  574. ///
  575. class IntervalTimer {
  576. public:
  577. /// \name The type of timer callback function
  578. typedef boost::function<void()> Callback;
  579. ///
  580. /// \name Constructors and Destructor
  581. ///
  582. /// Note: The copy constructor and the assignment operator are
  583. /// intentionally defined as private, making this class non-copyable.
  584. //@{
  585. private:
  586. IntervalTimer(const IntervalTimer& source);
  587. IntervalTimer& operator=(const IntervalTimer& source);
  588. public:
  589. /// \brief The constructor with \c IOService.
  590. ///
  591. /// This constructor may throw a standard exception if
  592. /// memory allocation fails inside the method.
  593. /// This constructor may also throw \c asio::system_error.
  594. ///
  595. /// \param io_service A reference to an instance of IOService
  596. ///
  597. IntervalTimer(IOService& io_service);
  598. /// \brief The destructor.
  599. ///
  600. /// This destructor never throws an exception.
  601. ///
  602. /// On the destruction of this class the timer will be canceled
  603. /// inside \c asio::deadline_timer.
  604. ///
  605. ~IntervalTimer();
  606. //@}
  607. /// \brief Register timer callback function and interval.
  608. ///
  609. /// This function sets callback function and interval in seconds.
  610. /// Timer will actually start after calling \c IOService::run().
  611. ///
  612. /// \param cbfunc A reference to a function \c void(void) to call back
  613. /// when the timer is expired (should not be an empty functor)
  614. /// \param interval Interval in seconds (greater than 0)
  615. ///
  616. /// Note: IntervalTimer will not pass \c asio::error_code to
  617. /// call back function. In case the timer is cancelled, the function
  618. /// will not be called.
  619. ///
  620. /// \throw isc::InvalidParameter cbfunc is empty
  621. /// \throw isc::BadValue interval is 0
  622. /// \throw isc::Unexpected ASIO library error
  623. ///
  624. void setupTimer(const Callback& cbfunc, const uint32_t interval);
  625. /// Cancel the timer.
  626. ///
  627. /// If the timer has been set up, this method cancels any asynchronous
  628. /// events waiting on the timer and stops the timer itself.
  629. /// If the timer has already been canceled, this method effectively does
  630. /// nothing.
  631. ///
  632. /// This method never throws an exception.
  633. void cancel();
  634. /// Return the timer interval.
  635. ///
  636. /// This method returns the timer interval in seconds if it's running;
  637. /// if the timer has been canceled it returns 0.
  638. ///
  639. /// This method never throws an exception.
  640. ///
  641. /// Note: We may want to change the granularity of the timer to
  642. /// milliseconds or even finer. If and when this happens the semantics
  643. /// of the return value of this method will be changed accordingly.
  644. uint32_t getInterval() const;
  645. private:
  646. IntervalTimerImpl* impl_;
  647. };
  648. } // asiolink
  649. #endif // __ASIOLINK_H
  650. // Local Variables:
  651. // mode: c++
  652. // End: