domaintree.h 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022
  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. #ifndef _DOMAINTREE_H
  15. #define _DOMAINTREE_H 1
  16. //! \file datasrc/memory/domaintree.h
  17. ///
  18. /// \note The purpose of the DomainTree is to provide a generic map with
  19. /// domain names as the key that can be used by various BIND 10
  20. /// modules or even by other applications. However, because of some
  21. /// unresolved design issue, the design and interface are not fixed,
  22. /// and DomainTree isn't ready to be used as a base data structure
  23. /// by other modules.
  24. #include <exceptions/exceptions.h>
  25. #include <util/memory_segment.h>
  26. #include <dns/name.h>
  27. #include <dns/labelsequence.h>
  28. #include <boost/utility.hpp>
  29. #include <boost/shared_ptr.hpp>
  30. #include <boost/interprocess/offset_ptr.hpp>
  31. #include <boost/static_assert.hpp>
  32. #include <ostream>
  33. #include <algorithm>
  34. #include <cassert>
  35. namespace isc {
  36. namespace datasrc {
  37. namespace memory {
  38. /// Forward declare DomainTree class here is convinent for following
  39. /// friend class declare inside DomainTreeNode and DomainTreeNodeChain
  40. template <typename T, typename DT>
  41. class DomainTree;
  42. /// \brief \c DomainTreeNode is used by DomainTree to store any data
  43. /// related to one domain name.
  44. ///
  45. /// This is meant to be used only from DomainTree. It is meaningless to
  46. /// inherit it or create instances of it from elsewhere. For that
  47. /// reason, the constructor (and the allocator, see below) is private.
  48. ///
  49. /// It serves three roles. One is to keep structure of the \c DomainTree
  50. /// as a red-black tree. For that purpose, it has left, right and parent
  51. /// pointers and color member. These are private and accessed only from
  52. /// within the tree.
  53. ///
  54. /// The second one is to store data for one domain name. The data
  55. /// related functions can be used to access and set the data.
  56. ///
  57. /// The third role is to keep the hierarchy of domains. The down pointer
  58. /// points to a subtree of subdomains. The parent pointer of a subtree's
  59. /// root node points to the parent leaf of the upper tree.
  60. ///
  61. /// One special kind of node is non-terminal node. It has subdomains
  62. /// with RRsets, but doesn't have any RRsets itself.
  63. ///
  64. /// In order to keep memory footprint as small as possible, the node
  65. /// data are heavily packed. Specifically, some internal node
  66. /// properties (such as the node color) are encoded as part of "flags",
  67. /// some of the flag bits can also be set by the user application. Each
  68. /// node is associated with a sequence of domain name labels, which is
  69. /// essentially the search/insert key for the node (see also the
  70. /// description of DomainTree). This is encoded as opaque binary
  71. /// immediately following the main node object. The size of the
  72. /// allocated space for the labels data is encoded by borrowing some
  73. /// bits of the "flags" field.
  74. template <typename T, typename DT>
  75. class DomainTreeNode : public boost::noncopyable {
  76. private:
  77. /// The DomainTreeNode is meant for use from within DomainTree, so
  78. /// it has access to it.
  79. friend class DomainTree<T,DT>;
  80. /// \brief Just a type alias
  81. ///
  82. /// We are going to use a lot of these offset pointers here and they
  83. /// have a long name.
  84. typedef boost::interprocess::offset_ptr<DomainTreeNode<T,DT> >
  85. DomainTreeNodePtr;
  86. /// \name Constructors
  87. ///
  88. /// \note The existence of a DomainTreeNode without a DomainTree is
  89. /// meaningless. Therefore the constructors are private.
  90. //@{
  91. /// \brief Constructor from normal nodes.
  92. DomainTreeNode(size_t labels_capacity);
  93. /// \brief Destructor
  94. ~DomainTreeNode();
  95. //@}
  96. /// \brief Accessor to the memory region for node labels.
  97. ///
  98. /// The only valid usage of the returned pointer is to pass it to
  99. /// the corresponding constructor of \c dns::LabelSequence.
  100. const void* getLabelsData() const { return (this + 1); }
  101. /// \brief Accessor to the memory region for node labels, mutable version.
  102. ///
  103. /// The only valid usage of the returned pointer is to pass it to
  104. /// \c LabelSequence::serialize() with the node's labels_capacity_ member
  105. /// (which should be sufficiently large for the \c LabelSequence in that
  106. /// context).
  107. void* getLabelsData() { return (this + 1); }
  108. /// \brief Allocate and construct \c DomainTreeNode
  109. ///
  110. /// This static method allocates memory for a new \c DomainTreeNode
  111. /// object from the given memory segment, constructs the object, and
  112. /// returns a pointer to it.
  113. ///
  114. /// \throw std::bad_alloc Memory allocation fails.
  115. ///
  116. /// \param mem_sgmt A \c MemorySegment from which memory for the new
  117. /// \c DomainTreeNode is allocated.
  118. static DomainTreeNode<T,DT>* create(util::MemorySegment& mem_sgmt,
  119. const dns::LabelSequence& labels)
  120. {
  121. const size_t labels_len = labels.getSerializedLength();
  122. void* p = mem_sgmt.allocate(sizeof(DomainTreeNode<T,DT>) + labels_len);
  123. DomainTreeNode<T,DT>* node = new(p) DomainTreeNode<T,DT>(labels_len);
  124. labels.serialize(node->getLabelsData(), labels_len);
  125. return (node);
  126. }
  127. /// \brief Destruct and deallocate \c DomainTreeNode
  128. ///
  129. /// \throw none
  130. ///
  131. /// \param mem_sgmt The \c MemorySegment that allocated memory for
  132. /// \c rbnode.
  133. /// \param rbnode A non NULL pointer to a valid \c DomainTreeNode object
  134. /// that was originally created by the \c create() method (the behavior
  135. /// is undefined if this condition isn't met).
  136. static void destroy(util::MemorySegment& mem_sgmt,
  137. DomainTreeNode<T,DT>* rbnode) {
  138. const size_t labels_capacity = rbnode->labels_capacity_;
  139. rbnode->~DomainTreeNode<T,DT>();
  140. mem_sgmt.deallocate(rbnode,
  141. sizeof(DomainTreeNode<T,DT>) + labels_capacity);
  142. }
  143. /// \brief Reset node's label sequence to a new one.
  144. ///
  145. /// The new labels must be a sub sequence of the current label sequence;
  146. /// otherwise the serialize() method will throw an exception.
  147. void resetLabels(const dns::LabelSequence& labels) {
  148. labels.serialize(getLabelsData(), labels_capacity_);
  149. }
  150. public:
  151. /// Node flags.
  152. ///
  153. /// Each flag value defines a non default property for a specific node.
  154. /// These are defined as bitmask type values for the convenience of
  155. /// internal implementation, but applications are expected to use
  156. /// each flag separately via the enum definitions.
  157. ///
  158. /// All (settable) flags are off by default; they must be explicitly
  159. /// set to on by the \c setFlag() method.
  160. enum Flags {
  161. FLAG_CALLBACK = 1, ///< Callback enabled. See \ref callback
  162. FLAG_RED = 2, ///< Node color; 1 if node is red, 0 if node is black.
  163. FLAG_SUBTREE_ROOT = 4, ///< Set if the node is the root of a subtree
  164. FLAG_USER1 = 0x400000U, ///< Application specific flag
  165. FLAG_USER2 = 0x200000U, ///< Application specific flag
  166. FLAG_USER3 = 0x100000U, ///< Application specific flag
  167. FLAG_MAX = 0x400000U // for integrity check
  168. };
  169. private:
  170. // Some flag values are expected to be used for internal purposes
  171. // (e.g., representing the node color) in future versions, so we
  172. // limit the settable flags via the \c setFlag() method to those
  173. // explicitly defined in \c Flags. This constant represents all
  174. // such flags.
  175. static const uint32_t SETTABLE_FLAGS = (FLAG_CALLBACK | FLAG_USER1 |
  176. FLAG_USER2 | FLAG_USER3);
  177. public:
  178. /// \name Getter functions.
  179. //@{
  180. /// \brief Return the name of current node.
  181. ///
  182. /// It's relative to its containing node.
  183. ///
  184. /// To get the absolute name of one node, the node path from the top node
  185. /// to current node has to be recorded.
  186. ///
  187. /// \note We should eventually deprecate this method and revise all its
  188. /// usage with \c getLabels(). At this point the only user of this method
  189. /// is getAbsoluteName()::getAbsoluteName(), which would have to be revised
  190. /// using \c LabelSequence. Until then we keep this interface as a
  191. /// simplest form of wrapper; it's not efficient, but should be replaced
  192. /// before we need to worry about that.
  193. const isc::dns::Name getName() const {
  194. return (dns::Name(dns::LabelSequence(getLabelsData()).toText()));
  195. }
  196. /// \brief Return the label sequence of the node.
  197. ///
  198. /// This method returns the label sequence corresponding to this node
  199. /// in the form of \c dns::LabelSequence object. Any modification to
  200. /// the tree can invalidate the returned \c LabelSequence object or copy
  201. /// of it; in general, it's expected to be used in a very limited scope.
  202. dns::LabelSequence getLabels() const {
  203. return (dns::LabelSequence(getLabelsData()));
  204. }
  205. /// \brief Return the data stored in this node.
  206. ///
  207. /// You should not delete the data, it is deleted when the tree is
  208. /// destroyed.
  209. T* getData() { return (data_); }
  210. /// \brief Return the data stored in this node (const).
  211. const T* getData() const { return (data_); }
  212. /// \brief return whether the node has related data.
  213. ///
  214. /// There can be empty nodes inside the DomainTree. They are usually the
  215. /// non-terminal domains, but it is possible (yet probably meaningless)
  216. /// empty nodes anywhere.
  217. bool isEmpty() const { return (data_ == NULL); }
  218. //@}
  219. /// \name Setter functions.
  220. //@{
  221. /// \brief Set the data stored in the node. If there is old data, it
  222. /// is destroyed.
  223. void setData(T* data) {
  224. const DT deleter;
  225. deleter(data_);
  226. data_ = data;
  227. }
  228. //@}
  229. /// \name Node flag manipulation methods
  230. //@{
  231. /// Get the status of a node flag.
  232. ///
  233. /// This method returns whether the given node flag is set (enabled)
  234. /// on the node. The \c flag parameter is expected to be one of the
  235. /// defined \c Flags constants. For simplicity, the method interface
  236. /// does not prohibit passing an undefined flag or combined flags, but
  237. /// the return value in such a case will be meaningless for the caller
  238. /// (an application would have to use an ugly cast for such an unintended
  239. /// form of call, which will hopefully avoid accidental misuse).
  240. ///
  241. /// \exception None
  242. /// \param flag The flag to be tested.
  243. /// \return \c true if the \c flag is set; \c false otherwise.
  244. bool getFlag(Flags flag) const {
  245. return ((flags_ & flag) != 0);
  246. }
  247. /// Set or clear a node flag.
  248. ///
  249. /// This method changes the status of the specified node flag to either
  250. /// "on" (enabled) or "off" (disabled). The new status is specified by
  251. /// the \c on parameter.
  252. /// Like the \c getFlag() method, \c flag is expected to be one of the
  253. /// defined \c Flags constants. If an undefined or unsettable flag is
  254. /// specified, \c isc::InvalidParameter exception will be thrown.
  255. ///
  256. /// \exception isc::InvalidParameter Unsettable flag is specified
  257. /// \exception None otherwise
  258. /// \param flag The node flag to be changed.
  259. /// \param on If \c true, set the flag to on; otherwise set it to off.
  260. void setFlag(Flags flag, bool on = true) {
  261. if ((flag & ~SETTABLE_FLAGS) != 0) {
  262. isc_throw(isc::InvalidParameter,
  263. "Unsettable DomainTree flag is being set");
  264. }
  265. if (on) {
  266. flags_ |= flag;
  267. } else {
  268. flags_ &= ~flag;
  269. }
  270. }
  271. //@}
  272. private:
  273. /// \name Callback related methods
  274. ///
  275. /// See the description of \c DomainTree<T,DT>::find() at \ref callback
  276. /// about callbacks.
  277. ///
  278. /// These methods never throw an exception.
  279. //@{
  280. /// Return if callback is enabled at the node.
  281. //@}
  282. /// \brief Define rbnode color
  283. enum DomainTreeNodeColor {BLACK, RED};
  284. /// \brief Returns the color of this node
  285. DomainTreeNodeColor getColor() const {
  286. if ((flags_ & FLAG_RED) != 0) {
  287. return (RED);
  288. } else {
  289. return (BLACK);
  290. }
  291. }
  292. /// \brief Sets the color of this node
  293. void setColor(const DomainTreeNodeColor color) {
  294. if (color == RED) {
  295. flags_ |= FLAG_RED;
  296. } else {
  297. flags_ &= ~FLAG_RED;
  298. }
  299. }
  300. void setSubTreeRoot(bool root) {
  301. if (root) {
  302. flags_ |= FLAG_SUBTREE_ROOT;
  303. } else {
  304. flags_ &= ~FLAG_SUBTREE_ROOT;
  305. }
  306. }
  307. bool isSubTreeRoot() const {
  308. return ((flags_ & FLAG_SUBTREE_ROOT) != 0);
  309. }
  310. public:
  311. /// \brief returns the parent of the root of its subtree
  312. ///
  313. /// This method takes a node and returns the parent of the root of
  314. /// its subtree (i.e, it returns the node's immediate ancestor in
  315. /// the tree-of-tree hierarchy). If the node is at the top level
  316. /// (which should be absolute), it will return \c NULL.
  317. ///
  318. /// This method never throws an exception.
  319. const DomainTreeNode<T,DT>* getUpperNode() const;
  320. private:
  321. /// \brief return the next node which is bigger than current node
  322. /// in the same subtree
  323. ///
  324. /// The next successor for this node is the next bigger node in terms of
  325. /// the DNSSEC order relation within the same single subtree.
  326. /// Note that it may NOT be the next bigger node in the entire DomainTree;
  327. /// DomainTree is a tree in tree, and the real next node may reside in
  328. /// an upper or lower subtree of the subtree where this node belongs.
  329. /// For example, if this node has a sub domain, the real next node is
  330. /// the smallest node in the sub domain tree.
  331. ///
  332. /// If this node is the biggest node within the subtree, this method
  333. /// returns \c NULL.
  334. ///
  335. /// This method never throws an exception.
  336. const DomainTreeNode<T,DT>* successor() const;
  337. /// \brief return the next node which is smaller than current node
  338. /// in the same subtree
  339. ///
  340. /// The predecessor for this node is the next smaller node in terms of
  341. /// the DNSSEC order relation within the same single subtree.
  342. /// Note that it may NOT be the next smaller node in the entire DomainTree;
  343. /// DomainTree is a tree in tree, and the real next node may reside in
  344. /// an upper or lower subtree of the subtree where this node belongs.
  345. /// For example, if the predecessor node has a sub domain, the real next
  346. /// node is the largest node in the sub domain tree.
  347. ///
  348. /// If this node is the smallest node within the subtree, this method
  349. /// returns \c NULL.
  350. ///
  351. /// This method never throws an exception.
  352. const DomainTreeNode<T,DT>* predecessor() const;
  353. /// \brief private shared implementation of successor and predecessor
  354. ///
  355. /// As the two mentioned functions are merely mirror images of each other,
  356. /// it makes little sense to keep both versions. So this is the body of the
  357. /// functions and we call it with the correct pointers.
  358. ///
  359. /// Not to be called directly, not even by friends.
  360. ///
  361. /// The overhead of the member pointers should be optimised out, as this
  362. /// will probably get completely inlined into predecessor and successor
  363. /// methods.
  364. const DomainTreeNode<T,DT>*
  365. abstractSuccessor(typename DomainTreeNode<T,DT>::DomainTreeNodePtr
  366. DomainTreeNode<T,DT>::*left,
  367. typename DomainTreeNode<T,DT>::DomainTreeNodePtr
  368. DomainTreeNode<T,DT>::*right)
  369. const;
  370. /// \name Data to maintain the rbtree structure.
  371. ///
  372. /// We keep them as offset pointers. This is part of a future plan, when we
  373. /// want to share the image of the tree between multiple processes.
  374. /// However, whenever we have a chance, we switch to bare pointers during
  375. /// the processing. The pointers on stack are never shared and the offset
  376. /// pointers have non-trivial performance impact.
  377. //@{
  378. DomainTreeNodePtr parent_;
  379. /// \brief Access the parent_ as bare pointer.
  380. DomainTreeNode<T,DT>* getParent() {
  381. return (parent_.get());
  382. }
  383. /// \brief Access the parent_ as bare pointer, const.
  384. const DomainTreeNode<T,DT>* getParent() const {
  385. return (parent_.get());
  386. }
  387. DomainTreeNodePtr left_;
  388. /// \brief Access the left_ as bare pointer.
  389. DomainTreeNode<T,DT>* getLeft() {
  390. return (left_.get());
  391. }
  392. /// \brief Access the left_ as bare pointer, const.
  393. const DomainTreeNode<T,DT>* getLeft() const {
  394. return (left_.get());
  395. }
  396. DomainTreeNodePtr right_;
  397. /// \brief Access the right_ as bare pointer.
  398. DomainTreeNode<T,DT>* getRight() {
  399. return (right_.get());
  400. }
  401. /// \brief Access the right_ as bare pointer, const.
  402. const DomainTreeNode<T,DT>* getRight() const {
  403. return (right_.get());
  404. }
  405. //@}
  406. /// \brief The subdomain tree.
  407. ///
  408. /// This points to the root node of trees of subdomains of this domain.
  409. ///
  410. /// \par Adding down pointer to \c DomainTreeNode has two purposes:
  411. /// \li Accelerate the search process, with sub domain tree, it splits the
  412. /// big flat tree into several hierarchy trees.
  413. /// \li It saves memory usage as it allows storing only relative names,
  414. /// avoiding storage of the same domain labels multiple times.
  415. DomainTreeNodePtr down_;
  416. /// \brief Access the down_ as bare pointer.
  417. DomainTreeNode<T,DT>* getDown() {
  418. return (down_.get());
  419. }
  420. /// \brief Access the down_ as bare pointer, const.
  421. const DomainTreeNode<T,DT>* getDown() const {
  422. return (down_.get());
  423. }
  424. /// \brief Data stored here.
  425. T* data_;
  426. /// \brief Internal or user-configurable flags of node's properties.
  427. ///
  428. /// See the \c Flags enum for available flags.
  429. ///
  430. /// For memory efficiency reasons, we only use a subset of the 32-bit
  431. /// space, and use the rest to store the allocated size for the node's
  432. /// label sequence data.
  433. uint32_t flags_ : 23; // largest flag being 0x400000
  434. BOOST_STATIC_ASSERT((1 << 23) > FLAG_MAX); // assumption check
  435. const uint32_t labels_capacity_ : 9; // size for labelseq; range is 0..511
  436. // Make sure the reserved space for labels_capacity_ is sufficiently
  437. // large. In effect, we use the knowledge of the implementation of the
  438. // serialization, but we still only use its public interface, and the
  439. // public interface of this class doesn't rely on this assumption.
  440. // So we can change this implementation without affecting its users if
  441. // a future change to LabelSequence breaks this assumption.
  442. BOOST_STATIC_ASSERT((1 << 9) > dns::LabelSequence::MAX_SERIALIZED_LENGTH);
  443. };
  444. template <typename T, typename DT>
  445. DomainTreeNode<T,DT>::DomainTreeNode(size_t labels_capacity) :
  446. parent_(NULL),
  447. left_(NULL),
  448. right_(NULL),
  449. down_(NULL),
  450. data_(NULL),
  451. flags_(FLAG_RED | FLAG_SUBTREE_ROOT),
  452. labels_capacity_(labels_capacity)
  453. {
  454. }
  455. template <typename T, typename DT>
  456. DomainTreeNode<T,DT>::~DomainTreeNode() {
  457. }
  458. template <typename T, typename DT>
  459. const DomainTreeNode<T,DT>*
  460. DomainTreeNode<T,DT>::getUpperNode() const {
  461. const DomainTreeNode<T,DT>* current = this;
  462. // current would never be equal to NULL here (in a correct tree
  463. // implementation)
  464. while (!current->isSubTreeRoot()) {
  465. current = current->getParent();
  466. }
  467. return (current->getParent());
  468. }
  469. template <typename T, typename DT>
  470. const DomainTreeNode<T,DT>*
  471. DomainTreeNode<T,DT>::abstractSuccessor(typename DomainTreeNode<T,DT>::DomainTreeNodePtr
  472. DomainTreeNode<T,DT>::*left,
  473. typename DomainTreeNode<T,DT>::DomainTreeNodePtr
  474. DomainTreeNode<T,DT>::*right)
  475. const
  476. {
  477. // This function is written as a successor. It becomes predecessor if
  478. // the left and right pointers are swapped. So in case of predecessor,
  479. // the left pointer points to right and vice versa. Don't get confused
  480. // by the idea, just imagine the pointers look into a mirror.
  481. const DomainTreeNode<T,DT>* current = this;
  482. // If it has right node, the successor is the left-most node of the right
  483. // subtree.
  484. if ((current->*right).get() != NULL) {
  485. current = (current->*right).get();
  486. const DomainTreeNode<T,DT>* left_n;
  487. while ((left_n = (current->*left).get()) != NULL) {
  488. current = left_n;
  489. }
  490. return (current);
  491. }
  492. // Otherwise go up until we find the first left branch on our path to
  493. // root. If found, the parent of the branch is the successor.
  494. // Otherwise, we return the null node
  495. const DomainTreeNode<T,DT>* parent = current->getParent();
  496. while ((!current->isSubTreeRoot()) &&
  497. (current == (parent->*right).get())) {
  498. current = parent;
  499. parent = parent->getParent();
  500. }
  501. if (!current->isSubTreeRoot()) {
  502. return (parent);
  503. } else {
  504. return (NULL);
  505. }
  506. }
  507. template <typename T, typename DT>
  508. const DomainTreeNode<T,DT>*
  509. DomainTreeNode<T,DT>::successor() const {
  510. return (abstractSuccessor(&DomainTreeNode<T,DT>::left_,
  511. &DomainTreeNode<T,DT>::right_));
  512. }
  513. template <typename T, typename DT>
  514. const DomainTreeNode<T,DT>*
  515. DomainTreeNode<T,DT>::predecessor() const {
  516. // Swap the left and right pointers for the abstractSuccessor
  517. return (abstractSuccessor(&DomainTreeNode<T,DT>::right_,
  518. &DomainTreeNode<T,DT>::left_));
  519. }
  520. /// \brief DomainTreeNodeChain stores detailed information of \c
  521. /// DomainTree::find() result.
  522. ///
  523. /// - The \c DomainTreeNode that was last compared with the search name, and
  524. /// the comparison result at that point in the form of
  525. /// \c isc::dns::NameComparisonResult.
  526. /// - A sequence of nodes that forms a path to the found node.
  527. ///
  528. /// The comparison result can be used to handle some rare cases such as
  529. /// empty node processing.
  530. /// The node sequence keeps track of the nodes to reach any given node from
  531. /// the root of DomainTree.
  532. ///
  533. /// Currently, DomainTreeNode does not have "up" pointers in them (i.e.,
  534. /// back pointers from the root of one level of tree of trees to the
  535. /// node in the parent tree whose down pointer points to that root node)
  536. /// for memory usage reasons, so there is no other way to find the path
  537. /// back to the root from any given DomainTreeNode.
  538. ///
  539. /// \note This design may change in future versions. In particular, it's
  540. /// quite likely we want to have that pointer if we want to optimize name
  541. /// compression by exploiting the structure of the zone. If and when that
  542. /// happens we should also revisit the need for the chaining.
  543. /// Also, the class name may not be appropriate now that it contains other
  544. /// information than a node "chain", and the chain itself may even be
  545. /// deprecated. Something like "DomainTreeFindContext" may be a better name.
  546. /// This point should be revisited later.
  547. ///
  548. /// DomainTreeNodeChain is constructed and manipulated only inside the
  549. /// \c DomainTree class.
  550. /// \c DomainTree uses it as an inner data structure to iterate over the whole
  551. /// DomainTree.
  552. /// This is the reason why manipulation methods such as \c push() and \c pop()
  553. /// are private (and not shown in the doxygen document).
  554. template <typename T, typename DT>
  555. class DomainTreeNodeChain {
  556. /// DomainTreeNodeChain is initialized by DomainTree, only DomainTree has
  557. /// knowledge to manipulate it.
  558. friend class DomainTree<T,DT>;
  559. public:
  560. /// \name Constructors and Assignment Operator.
  561. ///
  562. /// \note The copy constructor and the assignment operator are
  563. /// intentionally defined as private, making this class non copyable.
  564. /// This may have to be changed in a future version with newer need.
  565. /// For now we explicitly disable copy to avoid accidental copy happens
  566. /// unintentionally.
  567. //{@
  568. /// The default constructor.
  569. ///
  570. /// \exception None
  571. DomainTreeNodeChain() : node_count_(0), last_compared_(NULL),
  572. // XXX: meaningless initial values:
  573. last_comparison_(0, 0,
  574. isc::dns::NameComparisonResult::EQUAL)
  575. {}
  576. private:
  577. DomainTreeNodeChain(const DomainTreeNodeChain<T,DT>&);
  578. DomainTreeNodeChain<T,DT>& operator=(const DomainTreeNodeChain<T,DT>&);
  579. //@}
  580. public:
  581. /// Clear the state of the chain.
  582. ///
  583. /// This method re-initializes the internal state of the chain so that
  584. /// it can be reused for subsequent operations.
  585. ///
  586. /// \exception None
  587. void clear() {
  588. node_count_ = 0;
  589. last_compared_ = NULL;
  590. }
  591. /// Return the \c DomainTreeNode that was last compared in \c
  592. /// DomainTree::find().
  593. ///
  594. /// If this chain has been passed to \c DomainTree::find() and there
  595. /// has been name comparison against the search name, the last
  596. /// compared \c DomainTreeNode is recorded within the chain. This
  597. /// method returns that node.
  598. ///
  599. /// If \c DomainTree::find() hasn't been called with this chain or
  600. /// name comparison hasn't taken place (which is possible if the
  601. /// tree is empty), this method returns \c NULL.
  602. ///
  603. /// \exception None
  604. const DomainTreeNode<T,DT>* getLastComparedNode() const {
  605. return (last_compared_);
  606. }
  607. /// Return the result of last name comparison in \c DomainTree::find().
  608. ///
  609. /// Like \c getLastComparedNode(), \c DomainTree::find() records the result
  610. /// of the last name comparison in the chain. This method returns the
  611. /// result.
  612. /// The return value of this method is only meaningful when comparison
  613. /// has taken place, i.e, when \c getLastComparedNode() would return a
  614. /// non \c NULL value.
  615. ///
  616. /// \exception None
  617. const isc::dns::NameComparisonResult& getLastComparisonResult() const {
  618. return (last_comparison_);
  619. }
  620. /// \brief Return the number of levels stored in the chain.
  621. ///
  622. /// It's equal to the number of nodes in the chain; for an empty
  623. /// chain, 0 will be returned.
  624. ///
  625. /// \exception None
  626. unsigned int getLevelCount() const { return (node_count_); }
  627. /// \brief return the absolute name for the node which this
  628. /// \c DomainTreeNodeChain currently refers to.
  629. ///
  630. /// The chain must not be empty.
  631. ///
  632. /// \exception isc::BadValue the chain is empty.
  633. /// \exception std::bad_alloc memory allocation for the new name fails.
  634. isc::dns::Name getAbsoluteName() const {
  635. if (isEmpty()) {
  636. isc_throw(isc::BadValue,
  637. "DomainTreeNodeChain::getAbsoluteName is "
  638. "called on an empty chain");
  639. }
  640. const DomainTreeNode<T,DT>* top_node = top();
  641. isc::dns::Name absolute_name = top_node->getName();
  642. int node_count = node_count_ - 1;
  643. while (node_count > 0) {
  644. top_node = nodes_[node_count - 1];
  645. absolute_name = absolute_name.concatenate(top_node->getName());
  646. --node_count;
  647. }
  648. return (absolute_name);
  649. }
  650. private:
  651. // the following private functions check invariants about the internal
  652. // state using assert() instead of exception. The state of a chain
  653. // can only be modified by operations within this file, so if any of the
  654. // assumptions fails it means an internal bug.
  655. /// \brief return whether node chain has node in it.
  656. ///
  657. /// \exception None
  658. bool isEmpty() const { return (node_count_ == 0); }
  659. /// \brief return the top node for the node chain
  660. ///
  661. /// DomainTreeNodeChain store all the nodes along top node to
  662. /// root node of DomainTree
  663. ///
  664. /// \exception None
  665. const DomainTreeNode<T,DT>* top() const {
  666. assert(!isEmpty());
  667. return (nodes_[node_count_ - 1]);
  668. }
  669. /// \brief pop the top node from the node chain
  670. ///
  671. /// After pop, up/super node of original top node will be
  672. /// the top node
  673. ///
  674. /// \exception None
  675. void pop() {
  676. assert(!isEmpty());
  677. --node_count_;
  678. }
  679. /// \brief add the node into the node chain
  680. ///
  681. /// If the node chain isn't empty, the node should be
  682. /// the sub domain of the original top node in node chain
  683. /// otherwise the node should be the root node of DomainTree.
  684. ///
  685. /// \exception None
  686. void push(const DomainTreeNode<T,DT>* node) {
  687. assert(node_count_ < RBT_MAX_LEVEL);
  688. nodes_[node_count_++] = node;
  689. }
  690. private:
  691. // The max label count for one domain name is Name::MAX_LABELS (128).
  692. // Since each node in rbtree stores at least one label, it's also equal
  693. // to the possible maximum level.
  694. const static int RBT_MAX_LEVEL = isc::dns::Name::MAX_LABELS;
  695. int node_count_;
  696. const DomainTreeNode<T,DT>* nodes_[RBT_MAX_LEVEL];
  697. const DomainTreeNode<T,DT>* last_compared_;
  698. isc::dns::NameComparisonResult last_comparison_;
  699. };
  700. // note: the following class description is documented using multiline comments
  701. // because the verbatim diagram contain a backslash, which could be interpreted
  702. // as escape of newline in singleline comment.
  703. /**
  704. * \brief \c DomainTree class represents all the domains with the same suffix.
  705. * It can be used to store the domains in one zone, for example.
  706. *
  707. * DomainTree is a generic map from domain names to any kind of
  708. * data. Internally, it uses a red-black tree. However, it isn't one
  709. * tree containing everything. Subdomains are trees, so this structure
  710. * is recursive - trees inside trees. But, from the interface point of
  711. * view, it is opaque data structure.
  712. *
  713. * \c DomainTree splits the domain space into hierarchy red black trees; nodes
  714. * in one tree has the same base name. The benefit of this struct is that:
  715. * - Enhances the query performace compared with one big flat red black tree.
  716. * - Decreases the memory footprint, as it doesn't store the suffix labels
  717. * multiple times.
  718. *
  719. * Depending on different usage, rbtree will support different search policies.
  720. * Whether to return an empty node to end user is one policy among them.
  721. * The default policy is to NOT return an empty node to end user;
  722. * to change the behavior, specify \c true for the constructor parameter
  723. * \c returnEmptyNode.
  724. * \note The search policy only affects the \c find() behavior of DomainTree.
  725. * When inserting one name into DomainTree, if the node with the name already
  726. * exists in the DomainTree and it's an empty node which doesn't have any data,
  727. * the \c insert() method will still return \c ALREADYEXISTS regardless of
  728. * the search policy.
  729. *
  730. * \anchor diagram
  731. *
  732. * with the following names:
  733. * - a
  734. * - b
  735. * - c
  736. * - x.d.e.f
  737. * - z.d.e.f
  738. * - g.h
  739. * - o.w.y.d.e.f
  740. * - p.w.y.d.e.f
  741. * - q.w.y.d.e.f
  742. *
  743. * the tree will look like:
  744. * \verbatim
  745. .
  746. |
  747. b
  748. / \
  749. a d.e.f
  750. /|\
  751. c | g.h
  752. |
  753. w.y
  754. /|\
  755. x | z
  756. |
  757. p
  758. / \
  759. o q
  760. \endverbatim
  761. * \todo
  762. * - add remove interface
  763. */
  764. template <typename T, typename DT>
  765. class DomainTree : public boost::noncopyable {
  766. friend class DomainTreeNode<T,DT>;
  767. public:
  768. /// \brief The return value for the \c find() and insert() methods
  769. enum Result {
  770. SUCCESS, ///< Insert was successful
  771. /// \brief The node returned from find mathes exactly the name given
  772. EXACTMATCH,
  773. PARTIALMATCH, ///< A superdomain node was found
  774. NOTFOUND, ///< Not even any superdomain was found
  775. /// \brief Returned by insert() if a node of the name already exists
  776. ALREADYEXISTS,
  777. };
  778. /// \brief Allocate and construct \c DomainTree
  779. ///
  780. /// This static method allocates memory for a new \c DomainTree object
  781. /// from the given memory segment, constructs the object, and returns
  782. /// a pointer to it.
  783. ///
  784. /// \throw std::bad_alloc Memory allocation fails.
  785. ///
  786. /// \param mem_sgmt A \c MemorySegment from which memory for the new
  787. /// \c DomainTree is allocated.
  788. static DomainTree* create(util::MemorySegment& mem_sgmt,
  789. bool return_empty_node = false)
  790. {
  791. void* p = mem_sgmt.allocate(sizeof(DomainTree<T,DT>));
  792. return (new(p) DomainTree<T,DT>(return_empty_node));
  793. }
  794. /// \brief Destruct and deallocate \c DomainTree
  795. ///
  796. /// This method also destroys and deallocates all nodes inserted to the
  797. /// tree.
  798. ///
  799. /// \note The memory segment (\c mem_sgmt) must be the same one that
  800. /// was originally used to allocate memory for the tree (and for all
  801. /// nodes inserted to the tree, due to the requirement of \c insert()),
  802. /// since the tree itself doesn't maintain a reference to the segment.
  803. /// This is not a robust interface, but since we plan to share the tree
  804. /// structure by multiple processes via shared memory or possibly allow
  805. /// the memory image to be dumped to a file for later reload, there
  806. /// doesn't seem to be an easy way to store such reference in the data
  807. /// itself. We should probably consider a wrapper interface that
  808. /// encapsulates the corresponding segment and always use it for any
  809. /// allocation/deallocation of tree related data (the tree itself, their
  810. /// nodes, and node data) to keep the usage as safe as possible.
  811. ///
  812. /// \throw none
  813. ///
  814. /// \param mem_sgmt The \c MemorySegment that allocated memory for
  815. /// \c rbtree and for all nodes inserted to the tree.
  816. /// \param rbtree A non NULL pointer to a valid \c DomainTree object
  817. /// that was originally created by the \c create() method (the behavior
  818. /// is undefined if this condition isn't met).
  819. static void destroy(util::MemorySegment& mem_sgmt,
  820. DomainTree<T,DT>* rbtree) {
  821. rbtree->deleteAllNodes(mem_sgmt);
  822. rbtree->~DomainTree<T,DT>();
  823. mem_sgmt.deallocate(rbtree, sizeof(DomainTree<T,DT>));
  824. }
  825. private:
  826. /// \name Constructor and Destructor
  827. //@{
  828. /// \brief The constructor.
  829. ///
  830. /// An object of this class is always expected to be created by the
  831. /// allocator (\c create()), so the constructor is hidden as private.
  832. ///
  833. /// It never throws an exception.
  834. explicit DomainTree(bool returnEmptyNode = false);
  835. /// \brief The destructor.
  836. ///
  837. /// An object of this class is always expected to be destroyed explicitly
  838. /// by \c destroy(), so the constructor is hidden as private.
  839. ///
  840. /// \note DomainTree is not intended to be inherited so the destructor
  841. /// is not virtual
  842. ~DomainTree();
  843. //@}
  844. public:
  845. /// \name Find methods
  846. ///
  847. /// \brief Find the node that gives a longest match against the given name.
  848. ///
  849. /// \anchor find
  850. ///
  851. /// These methods search the DomainTree for a node whose name is
  852. /// longest against name. The found node, if any, is returned via
  853. /// the node pointer.
  854. ///
  855. /// By default, nodes that don't have data (see
  856. /// DomainTreeNode::isEmpty) are ignored and the result can be
  857. /// NOTFOUND even if there's a node whose name matches. If the \c
  858. /// DomainTree is constructed with its \c returnEmptyNode parameter
  859. /// being \c true, empty nodes will also be match candidates.
  860. ///
  861. /// \note Even when \c returnEmptyNode is \c true, not all empty
  862. /// nodes in terms of the DNS protocol may necessarily be found by
  863. /// this method. For example, in the \ref diagram shown in the
  864. /// class description, the name y.d.e.f is logically contained in
  865. /// the tree as part of the node w.y, but the \c find() variants
  866. /// cannot find the former for the search key of y.d.e.f, no matter
  867. /// how the \c DomainTree is constructed. The caller of this method
  868. /// must use a different way to identify the hidden match when
  869. /// necessary.
  870. ///
  871. /// These methods involve operations on names that can throw an
  872. /// exception. If that happens the exception will be propagated to
  873. /// the caller. The callback function should generally not throw an
  874. /// exception, but if it throws, the exception will be propagated to
  875. /// the caller.
  876. ///
  877. /// The \c name parameter says what should be found. The node parameter
  878. /// is output-only, and in case of EXACTMATCH or PARTIALMATCH, it is set
  879. /// to a pointer to the found node.
  880. ///
  881. /// They return:
  882. /// - EXACTMATCH when a node with the same name as requested exists.
  883. /// - PARTIALMATCH when a node with the same name does not exist (or is
  884. /// empty), but there's a (nonempty) superdomain of the requested one.
  885. /// The superdomain with longest name is returned through the node
  886. /// parameter. Beware that if you store a zone in the tree, you may get
  887. /// PARTIALMATCH with zone apex when the given domain name is not there.
  888. /// You should not try to delegate into another zone in that case.
  889. /// - NOTFOUND if there's no node with the same name nor any superdomain
  890. /// of it. In that case, node parameter is left intact.
  891. //@{
  892. /// \brief Simple find.
  893. ///
  894. /// Acts as described in the \ref find section.
  895. Result find(const isc::dns::Name& name,
  896. DomainTreeNode<T,DT>** node) const {
  897. DomainTreeNodeChain<T,DT> node_path;
  898. const isc::dns::LabelSequence ls(name);
  899. return (find<void*>(ls, node, node_path, NULL, NULL));
  900. }
  901. /// \brief Simple find returning immutable node.
  902. ///
  903. /// Acts as described in the \ref find section, but returns immutable node
  904. /// pointer.
  905. Result find(const isc::dns::Name& name,
  906. const DomainTreeNode<T,DT>** node) const {
  907. DomainTreeNodeChain<T,DT> node_path;
  908. DomainTreeNode<T,DT> *target_node = NULL;
  909. const isc::dns::LabelSequence ls(name);
  910. Result ret = (find<void*>(ls, &target_node, node_path, NULL, NULL));
  911. if (ret != NOTFOUND) {
  912. *node = target_node;
  913. }
  914. return (ret);
  915. }
  916. /// \brief Simple find, with node_path tracking
  917. ///
  918. /// Acts as described in the \ref find section.
  919. Result find(const isc::dns::Name& name, DomainTreeNode<T,DT>** node,
  920. DomainTreeNodeChain<T,DT>& node_path) const
  921. {
  922. const isc::dns::LabelSequence ls(name);
  923. return (find<void*>(ls, node, node_path, NULL, NULL));
  924. }
  925. /// \brief Simple find returning immutable node, with node_path tracking
  926. ///
  927. /// Acts as described in the \ref find section, but returns immutable node
  928. /// pointer.
  929. Result find(const isc::dns::Name& name, const DomainTreeNode<T,DT>** node,
  930. DomainTreeNodeChain<T,DT>& node_path) const
  931. {
  932. DomainTreeNode<T,DT> *target_node = NULL;
  933. const isc::dns::LabelSequence ls(name);
  934. Result ret = (find<void*>(ls, &target_node, node_path, NULL, NULL));
  935. if (ret != NOTFOUND) {
  936. *node = target_node;
  937. }
  938. return (ret);
  939. }
  940. /// \brief Simple find returning immutable node.
  941. ///
  942. /// Acts as described in the \ref find section, but returns immutable
  943. /// node pointer.
  944. template <typename CBARG>
  945. Result find(const isc::dns::Name& name,
  946. const DomainTreeNode<T,DT>** node,
  947. DomainTreeNodeChain<T,DT>& node_path,
  948. bool (*callback)(const DomainTreeNode<T,DT>&, CBARG),
  949. CBARG callback_arg) const
  950. {
  951. DomainTreeNode<T,DT>* target_node = NULL;
  952. const isc::dns::LabelSequence ls(name);
  953. Result ret = find(ls, &target_node, node_path, callback,
  954. callback_arg);
  955. if (ret != NOTFOUND) {
  956. *node = target_node;
  957. }
  958. return (ret);
  959. }
  960. /// \brief Find with callback and node chain
  961. /// \anchor callback
  962. ///
  963. /// This version of \c find() is specifically designed for the backend
  964. /// of the \c InMemoryZoneFinder class, and implements all necessary
  965. /// features for that purpose. Other applications shouldn't need these
  966. /// additional features, and should normally use the simpler versions.
  967. ///
  968. /// This version of \c find() calls the callback whenever traversing (on
  969. /// the way from root down the tree) a marked node on the way down through
  970. /// the domain namespace (see \c DomainTreeNode::FLAG_CALLBACK).
  971. ///
  972. /// Also, this version takes a \c LabelSequence object, not a \c Name
  973. /// object to be as efficient as possible; operations on the former
  974. /// needed for the search are generally much more efficient than those
  975. /// for the latter. Since \c Name objects are more commonly used
  976. /// in other parts of the implementation, other versions take a \c Name
  977. /// and convert it to \c LabelSequence. This conversion is cheap,
  978. /// while the other direction isn't, and since there would be cases
  979. /// where an implementation primarily handles \c LabelSequence objects
  980. /// as an efficient representation of names, it would make most sense
  981. /// to provide the interface that takes \c LabelSequence.
  982. ///
  983. /// If you return true from the callback, the search is stopped and a
  984. /// PARTIALMATCH is returned with the given node. Note that this node
  985. /// doesn't really need to be the one with longest possible match.
  986. ///
  987. /// The callback is not called for the node which matches exactly
  988. /// (EXACTMATCH is returned). This is typically the last node in the
  989. /// traversal during a successful search.
  990. ///
  991. /// This callback mechanism was designed with zone cut (delegation)
  992. /// processing in mind. The marked nodes would be the ones at delegation
  993. /// points. It is not expected that any other applications would need
  994. /// callbacks; they should use the versions of find without callbacks.
  995. /// The callbacks are not general functors for the same reason - we don't
  996. /// expect it to be needed.
  997. ///
  998. /// Another special feature of this version is the ability to record
  999. /// more detailed information regarding the search result.
  1000. ///
  1001. /// This information will be returned via the \c node_path parameter,
  1002. /// which is an object of class \c DomainTreeNodeChain.
  1003. /// The passed parameter must be empty.
  1004. ///
  1005. /// On success, the node sequence stored in \c node_path will contain all
  1006. /// the ancestor nodes from the found node towards the root.
  1007. /// For example, if we look for o.w.y.d.e.f in the example \ref diagram,
  1008. /// \c node_path will contain w.y and d.e.f; the \c top() node of the
  1009. /// chain will be o, w.y and d.e.f will be stored below it.
  1010. ///
  1011. /// This feature can be used to get the absolute name for a node; to
  1012. /// do so, we need to travel upside from the node toward the root,
  1013. /// concatenating all ancestor labels. A node chain can also be
  1014. /// used to find the next and previous nodes of a given node in the
  1015. /// entire DomainTree; the \c nextNode() and \c previousNode()
  1016. /// methods take a node chain as a parameter.
  1017. ///
  1018. /// \exception isc::BadValue node_path is not empty.
  1019. ///
  1020. /// \param target_labels_orig Target to be found
  1021. /// \param node On success (either \c EXACTMATCH or \c PARTIALMATCH)
  1022. /// it will store a pointer to the matching node
  1023. /// \param node_path Other search details will be stored (see the
  1024. /// description)
  1025. /// \param callback If non- \c NULL, a call back function to be called
  1026. /// at marked nodes (see the description).
  1027. /// \param callback_arg A caller supplied argument to be passed to
  1028. /// \c callback.
  1029. ///
  1030. /// \return As in the description, but in case of callback returning
  1031. /// \c true, it returns immediately with the current node.
  1032. template <typename CBARG>
  1033. Result find(const isc::dns::LabelSequence& target_labels_orig,
  1034. DomainTreeNode<T,DT>** node,
  1035. DomainTreeNodeChain<T,DT>& node_path,
  1036. bool (*callback)(const DomainTreeNode<T,DT>&, CBARG),
  1037. CBARG callback_arg) const;
  1038. /// \brief Simple find returning immutable node.
  1039. ///
  1040. /// Acts as described in the \ref find section, but returns immutable
  1041. /// node pointer.
  1042. template <typename CBARG>
  1043. Result find(const isc::dns::LabelSequence& target_labels,
  1044. const DomainTreeNode<T,DT>** node,
  1045. DomainTreeNodeChain<T,DT>& node_path,
  1046. bool (*callback)(const DomainTreeNode<T,DT>&, CBARG),
  1047. CBARG callback_arg) const
  1048. {
  1049. DomainTreeNode<T,DT>* target_node = NULL;
  1050. Result ret = find(target_labels, &target_node, node_path,
  1051. callback, callback_arg);
  1052. if (ret != NOTFOUND) {
  1053. *node = target_node;
  1054. }
  1055. return (ret);
  1056. }
  1057. //@}
  1058. /// \brief return the next bigger node in DNSSEC order from a given node
  1059. /// chain.
  1060. ///
  1061. /// This method identifies the next bigger node of the node currently
  1062. /// referenced in \c node_path and returns it.
  1063. /// This method also updates the passed \c node_path so that it will store
  1064. /// the path for the returned next node.
  1065. /// It will be convenient when we want to iterate over the all nodes
  1066. /// of \c DomainTree; we can do this by calling this method repeatedly
  1067. /// starting from the root node.
  1068. ///
  1069. /// \note \c nextNode() will iterate over all the nodes in
  1070. /// DomainTree including empty nodes. If empty node isn't desired,
  1071. /// it's easy to add logic to check return node and keep invoking \c
  1072. /// nextNode() until the non-empty node is retrieved.
  1073. ///
  1074. /// \exception isc::BadValue node_path is empty.
  1075. ///
  1076. /// \param node_path A node chain that stores all the nodes along
  1077. /// the path from root to node.
  1078. ///
  1079. /// \return An \c DomainTreeNode that is next bigger than \c node;
  1080. /// if \c node is the largest, \c NULL will be returned.
  1081. const DomainTreeNode<T,DT>*
  1082. nextNode(DomainTreeNodeChain<T,DT>& node_path) const;
  1083. /// \brief return the next smaller node in DNSSEC order from a node
  1084. /// searched by DomainTree::find().
  1085. ///
  1086. /// This acts similarly to \c nextNode(), but it walks in the other
  1087. /// direction. But unlike \c nextNode(), this can start even if the
  1088. /// node requested by \c find() was not found. In that case, it will
  1089. /// identify the node that is previous to the queried name.
  1090. ///
  1091. /// \note \c previousNode() will iterate over all the nodes in DomainTree
  1092. /// including empty nodes. If empty node isn't desired, it's easy to add
  1093. /// logic to check return node and keep invoking \c previousNode() until the
  1094. /// non-empty node is retrieved.
  1095. ///
  1096. /// \exception isc::BadValue node_path is empty.
  1097. ///
  1098. /// \param node_path A node chain that stores all the nodes along the path
  1099. /// from root to node and the result of \c find(). This will get modified.
  1100. /// You should not use the node_path again except for repetitive calls
  1101. /// of this method.
  1102. ///
  1103. /// \return An \c DomainTreeNode that is next smaller than \c node;
  1104. /// if \c node is the smallest, \c NULL will be returned.
  1105. const DomainTreeNode<T,DT>*
  1106. previousNode(DomainTreeNodeChain<T,DT>& node_path) const;
  1107. /// \brief Get the total number of nodes in the tree
  1108. ///
  1109. /// It includes nodes internally created as a result of adding a domain
  1110. /// name that is a subdomain of an existing node of the tree.
  1111. /// This function is mainly intended to be used for debugging.
  1112. int getNodeCount() const { return (node_count_); }
  1113. /// \name Debug function
  1114. //@{
  1115. /// \brief Print the nodes in the trees.
  1116. ///
  1117. /// \param os A \c std::ostream object to which the tree is printed.
  1118. /// \param depth A factor of the initial indentation. Each line
  1119. /// will begin with space character repeating <code>5 * depth</code>
  1120. /// times.
  1121. void dumpTree(std::ostream& os, unsigned int depth = 0) const;
  1122. /// \brief Print the nodes in the trees for processing with
  1123. /// Graphviz's dot.
  1124. ///
  1125. /// \param os A \c std::ostream object to which the tree is printed.
  1126. /// \param show_pointers Show node and parent pointers in the node
  1127. void dumpDot(std::ostream& os, bool show_pointers = false) const;
  1128. //@}
  1129. /// \name Modify functions
  1130. //@{
  1131. /// \brief Insert the domain name into the tree.
  1132. ///
  1133. /// It either finds an already existing node of the given name, or
  1134. /// inserts a new one if none exists yet. In any case, the \c
  1135. /// inserted_node parameter is set to point to that node. You can
  1136. /// fill data into it or modify it. So, if you don't know if a node
  1137. /// exists or not and you need to modify it, just call insert and
  1138. /// act by the result.
  1139. ///
  1140. /// Please note that the tree can add some empty nodes by itself, so
  1141. /// don't assume that if you didn't insert a node of that name it
  1142. /// doesn't exist.
  1143. ///
  1144. /// This method normally involves resource allocation. If it fails
  1145. /// the corresponding standard exception will be thrown.
  1146. ///
  1147. /// This method does not provide the strong exception guarantee in its
  1148. /// strict sense; if an exception is thrown in the middle of this
  1149. /// method, the internal structure may change. However, it should
  1150. /// still retain the same property as a mapping container before this
  1151. /// method is called. For example, the result of \c find() should be
  1152. /// the same. This method provides the weak exception guarantee in its
  1153. /// normal sense.
  1154. ///
  1155. /// \param mem_sgmt A \c MemorySegment object for allocating memory of
  1156. /// a new node to be inserted. Must be the same segment as that used
  1157. /// for creating the tree itself.
  1158. /// \param name The name to be inserted into the tree.
  1159. /// \param inserted_node This is an output parameter and is set to the
  1160. /// node.
  1161. ///
  1162. /// \return
  1163. /// - SUCCESS The node was added.
  1164. /// - ALREADYEXISTS There was already a node of that name, so it was not
  1165. /// added.
  1166. Result insert(util::MemorySegment& mem_sgmt, const isc::dns::Name& name,
  1167. DomainTreeNode<T,DT>** inserted_node);
  1168. /// \brief Delete all tree nodes.
  1169. ///
  1170. /// \throw none.
  1171. ///
  1172. /// \param mem_sgmt The \c MemorySegment object used to insert the nodes
  1173. /// (which was also used for creating the tree due to the requirement of
  1174. /// \c inert()).
  1175. void deleteAllNodes(util::MemorySegment& mem_sgmt);
  1176. /// \brief Swaps two tree's contents.
  1177. ///
  1178. /// This and \c other trees must have been created with the same
  1179. /// memory segment (see the discussion in \c create()); otherwise the
  1180. /// behavior is undefined.
  1181. ///
  1182. /// This acts the same as many std::*.swap functions, exchanges the
  1183. /// contents. This doesn't throw anything.
  1184. void swap(DomainTree<T,DT>& other) {
  1185. std::swap(root_, other.root_);
  1186. std::swap(node_count_, other.node_count_);
  1187. }
  1188. //@}
  1189. private:
  1190. /// \name DomainTree balance functions
  1191. //@{
  1192. void
  1193. insertRebalance(typename DomainTreeNode<T,DT>::DomainTreeNodePtr* root,
  1194. DomainTreeNode<T,DT>* node);
  1195. DomainTreeNode<T,DT>*
  1196. rightRotate(typename DomainTreeNode<T,DT>::DomainTreeNodePtr* root,
  1197. DomainTreeNode<T,DT>* node);
  1198. DomainTreeNode<T,DT>*
  1199. leftRotate(typename DomainTreeNode<T,DT>::DomainTreeNodePtr* root,
  1200. DomainTreeNode<T,DT>* node);
  1201. //@}
  1202. /// \name Helper functions
  1203. //@{
  1204. /// \brief delete tree whose root is equal to node
  1205. void deleteHelper(util::MemorySegment& mem_sgmt,
  1206. DomainTreeNode<T,DT> *node,
  1207. const DT& deleter);
  1208. /// \brief Print the information of given DomainTreeNode.
  1209. void dumpTreeHelper(std::ostream& os, const DomainTreeNode<T,DT>* node,
  1210. unsigned int depth) const;
  1211. /// \brief Print the information of given DomainTreeNode for dot.
  1212. int dumpDotHelper(std::ostream& os, const DomainTreeNode<T,DT>* node,
  1213. int* nodecount, bool show_pointers) const;
  1214. /// \brief Indentation helper function for dumpTree
  1215. static void indent(std::ostream& os, unsigned int depth);
  1216. /// Split one node into two nodes for "prefix" and "suffix" parts of
  1217. /// the labels of the original node, respectively. The given node
  1218. /// will hold the suffix labels, while the new node will hold the prefix.
  1219. /// The newly created node represents the labels that the original node
  1220. /// did, so necessary data are swapped.
  1221. /// (Note: as commented in the code, this behavior should be changed).
  1222. void nodeFission(util::MemorySegment& mem_sgmt, DomainTreeNode<T,DT>& node,
  1223. const isc::dns::LabelSequence& new_prefix,
  1224. const isc::dns::LabelSequence& new_suffix);
  1225. //@}
  1226. typename DomainTreeNode<T,DT>::DomainTreeNodePtr root_;
  1227. /// the node count of current tree
  1228. unsigned int node_count_;
  1229. /// search policy for rbtree
  1230. const bool needsReturnEmptyNode_;
  1231. };
  1232. template <typename T, typename DT>
  1233. DomainTree<T,DT>::DomainTree(bool returnEmptyNode) :
  1234. root_(NULL),
  1235. node_count_(0),
  1236. needsReturnEmptyNode_(returnEmptyNode)
  1237. {
  1238. }
  1239. template <typename T, typename DT>
  1240. DomainTree<T,DT>::~DomainTree() {
  1241. assert(node_count_ == 0);
  1242. }
  1243. template <typename T, typename DT>
  1244. void
  1245. DomainTree<T,DT>::deleteHelper(util::MemorySegment& mem_sgmt,
  1246. DomainTreeNode<T,DT>* root,
  1247. const DT& deleter) {
  1248. if (root == NULL) {
  1249. return;
  1250. }
  1251. DomainTreeNode<T,DT>* node = root;
  1252. while (root->getLeft() != NULL || root->getRight() != NULL) {
  1253. DomainTreeNode<T,DT>* left(NULL);
  1254. DomainTreeNode<T,DT>* right(NULL);
  1255. while ((left = node->getLeft()) != NULL ||
  1256. (right = node->getRight()) != NULL) {
  1257. node = (left != NULL) ? left : right;
  1258. }
  1259. DomainTreeNode<T,DT>* parent = node->getParent();
  1260. if (parent->getLeft() == node) {
  1261. parent->left_ = NULL;
  1262. } else {
  1263. parent->right_ = NULL;
  1264. }
  1265. deleteHelper(mem_sgmt, node->getDown(), deleter);
  1266. deleter(node->data_);
  1267. DomainTreeNode<T,DT>::destroy(mem_sgmt, node);
  1268. --node_count_;
  1269. node = parent;
  1270. }
  1271. deleteHelper(mem_sgmt, root->getDown(), deleter);
  1272. deleter(root->data_);
  1273. DomainTreeNode<T,DT>::destroy(mem_sgmt, root);
  1274. --node_count_;
  1275. }
  1276. template <typename T, typename DT>
  1277. template <typename CBARG>
  1278. typename DomainTree<T,DT>::Result
  1279. DomainTree<T,DT>::find(const isc::dns::LabelSequence& target_labels_orig,
  1280. DomainTreeNode<T,DT>** target,
  1281. DomainTreeNodeChain<T,DT>& node_path,
  1282. bool (*callback)(const DomainTreeNode<T,DT>&, CBARG),
  1283. CBARG callback_arg) const
  1284. {
  1285. if (!node_path.isEmpty()) {
  1286. isc_throw(isc::BadValue,
  1287. "DomainTree::find is given a non empty chain");
  1288. }
  1289. DomainTreeNode<T,DT>* node = root_.get();
  1290. Result ret = NOTFOUND;
  1291. dns::LabelSequence target_labels(target_labels_orig);
  1292. while (node != NULL) {
  1293. node_path.last_compared_ = node;
  1294. node_path.last_comparison_ = target_labels.compare(node->getLabels());
  1295. const isc::dns::NameComparisonResult::NameRelation relation =
  1296. node_path.last_comparison_.getRelation();
  1297. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1298. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  1299. node_path.push(node);
  1300. *target = node;
  1301. ret = EXACTMATCH;
  1302. }
  1303. break;
  1304. } else if (relation == isc::dns::NameComparisonResult::NONE) {
  1305. // If the two labels have no hierarchical relationship in terms
  1306. // of matching, we should continue the binary search.
  1307. node = (node_path.last_comparison_.getOrder() < 0) ?
  1308. node->getLeft() : node->getRight();
  1309. } else {
  1310. if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1311. if (needsReturnEmptyNode_ || !node->isEmpty()) {
  1312. ret = PARTIALMATCH;
  1313. *target = node;
  1314. if (callback != NULL &&
  1315. node->getFlag(DomainTreeNode<T,DT>::FLAG_CALLBACK)) {
  1316. if ((callback)(*node, callback_arg)) {
  1317. break;
  1318. }
  1319. }
  1320. }
  1321. node_path.push(node);
  1322. target_labels.stripRight(
  1323. node_path.last_comparison_.getCommonLabels());
  1324. node = node->getDown();
  1325. } else {
  1326. break;
  1327. }
  1328. }
  1329. }
  1330. return (ret);
  1331. }
  1332. template <typename T, typename DT>
  1333. const DomainTreeNode<T,DT>*
  1334. DomainTree<T,DT>::nextNode(DomainTreeNodeChain<T,DT>& node_path) const {
  1335. if (node_path.isEmpty()) {
  1336. isc_throw(isc::BadValue,
  1337. "DomainTree::nextNode is given an empty chain");
  1338. }
  1339. const DomainTreeNode<T,DT>* node = node_path.top();
  1340. // if node has sub domain, the next domain is the smallest
  1341. // domain in sub domain tree
  1342. const DomainTreeNode<T,DT>* down = node->getDown();
  1343. if (down != NULL) {
  1344. const DomainTreeNode<T,DT>* left_most = down;
  1345. while (left_most->getLeft() != NULL) {
  1346. left_most = left_most->getLeft();
  1347. }
  1348. node_path.push(left_most);
  1349. return (left_most);
  1350. }
  1351. // try to find a successor.
  1352. // if no successor found move to up level, the next successor
  1353. // is the successor of up node in the up level tree, if
  1354. // up node doesn't have successor we gonna keep moving to up
  1355. // level
  1356. while (!node_path.isEmpty()) {
  1357. const DomainTreeNode<T,DT>* up_node_successor =
  1358. node_path.top()->successor();
  1359. node_path.pop();
  1360. if (up_node_successor != NULL) {
  1361. node_path.push(up_node_successor);
  1362. return (up_node_successor);
  1363. }
  1364. }
  1365. return (NULL);
  1366. }
  1367. template <typename T, typename DT>
  1368. const DomainTreeNode<T,DT>*
  1369. DomainTree<T,DT>::previousNode(DomainTreeNodeChain<T,DT>& node_path) const {
  1370. if (getNodeCount() == 0) {
  1371. // Special case for empty trees. It would look every time like
  1372. // we didn't search, because the last compared is empty. This is
  1373. // a slight hack and not perfect, but this is better than throwing
  1374. // on empty tree. And we probably won't meet an empty tree in practice
  1375. // anyway.
  1376. return (NULL);
  1377. }
  1378. if (node_path.last_compared_ == NULL) {
  1379. isc_throw(isc::BadValue,
  1380. "DomainTree::previousNode() called before find()");
  1381. }
  1382. // If the relation isn't EQUAL, it means the find was called previously
  1383. // and didn't find the exact node. Therefore we need to locate the place
  1384. // to start iterating the chain of domains.
  1385. //
  1386. // The logic here is not too complex, we just need to take care to handle
  1387. // all the cases and decide where to go from there.
  1388. switch (node_path.last_comparison_.getRelation()) {
  1389. case dns::NameComparisonResult::COMMONANCESTOR:
  1390. case dns::NameComparisonResult::NONE:
  1391. // We compared with a leaf in the tree and wanted to go to one of
  1392. // the children. But the child was not there. It now depends on the
  1393. // direction in which we wanted to go.
  1394. if (node_path.last_comparison_.getOrder() < 0) {
  1395. // We wanted to go left. So the one we compared with is
  1396. // the one higher than we wanted. If we just put it into
  1397. // the node_path, then the following algorithm below will find
  1398. // the smaller one.
  1399. //
  1400. // This is exactly the same as with superdomain below.
  1401. // Therefore, we just fall through to the next case.
  1402. } else {
  1403. // We wanted to go right. That means we want to output the
  1404. // one which is the largest in the tree defined by the
  1405. // compared one (it is either the compared one, or some
  1406. // subdomain of it). There probably is not an easy trick
  1407. // for this, so we just find the correct place.
  1408. const DomainTreeNode<T,DT>* current(node_path.last_compared_);
  1409. while (current != NULL) {
  1410. node_path.push(current);
  1411. // Go a level down and as much right there as possible
  1412. current = current->getDown();
  1413. if (current != NULL) {
  1414. const DomainTreeNode<T,DT>* right;
  1415. while ((right = current->getRight()) != NULL) {
  1416. current = right;
  1417. }
  1418. }
  1419. }
  1420. // Now, the one on top of the path is the one we want. We
  1421. // return it now and leave it there, so we can search for
  1422. // previous of it the next time we'are called.
  1423. node_path.last_comparison_ =
  1424. dns::NameComparisonResult(0, 0,
  1425. dns::NameComparisonResult::EQUAL);
  1426. return (node_path.top());
  1427. }
  1428. // No break; here - we want to fall through. See above.
  1429. case dns::NameComparisonResult::SUPERDOMAIN:
  1430. // This is the case there's a "compressed" node and we looked for
  1431. // only part of it. The node itself is larger than we wanted, but
  1432. // if we put it to the node_path and then go one step left from it,
  1433. // we get the correct result.
  1434. node_path.push(node_path.last_compared_);
  1435. // Correct the comparison result, so we won't trigger this case
  1436. // next time previousNode is called. We already located the correct
  1437. // place to start. The value is partly nonsense, but that doesn't
  1438. // matter any more.
  1439. node_path.last_comparison_ =
  1440. dns::NameComparisonResult(0, 0,
  1441. dns::NameComparisonResult::EQUAL);
  1442. break;
  1443. case dns::NameComparisonResult::SUBDOMAIN:
  1444. // A subdomain means we returned the one above the searched one
  1445. // already and it is on top of the stack. This is was smaller
  1446. // than the one already, but we want to return yet smaller one.
  1447. // So we act as if it was EQUAL.
  1448. break;
  1449. case dns::NameComparisonResult::EQUAL:
  1450. // The find gave us an exact match or the previousNode was called
  1451. // already, which located the exact node. The rest of the function
  1452. // goes one domain left and returns it for us.
  1453. break;
  1454. }
  1455. // So, the node_path now contains the path to a node we want previous for.
  1456. // We just need to go one step left.
  1457. if (node_path.isEmpty()) {
  1458. // We got past the first one. So, we're returning NULL from
  1459. // now on.
  1460. return (NULL);
  1461. }
  1462. const DomainTreeNode<T,DT>* node(node_path.top());
  1463. // Try going left in this tree
  1464. node = node->predecessor();
  1465. if (node == NULL) {
  1466. // We are the smallest ones in this tree. We go one level
  1467. // up. That one is the smaller one than us.
  1468. node_path.pop();
  1469. if (node_path.isEmpty()) {
  1470. // We're past the first one
  1471. return (NULL);
  1472. } else {
  1473. return (node_path.top());
  1474. }
  1475. }
  1476. // Exchange the node at the top of the path, as we move horizontaly
  1477. // through the domain tree
  1478. node_path.pop();
  1479. node_path.push(node);
  1480. // Try going as deep as possible, keeping on the right side of the trees
  1481. const DomainTreeNode<T,DT>* down;
  1482. while ((down = node->getDown()) != NULL) {
  1483. // Move to the tree below
  1484. node = down;
  1485. if (node != NULL) {
  1486. // And get as much to the right of the tree as possible
  1487. const DomainTreeNode<T,DT>* right;
  1488. while ((right = node->getRight()) != NULL) {
  1489. node = right;
  1490. }
  1491. }
  1492. // Now, we found the right-most node in the sub-tree, we need to
  1493. // include it in the path
  1494. node_path.push(node);
  1495. }
  1496. // Now, if the current node has no down_ pointer any more, it's the
  1497. // correct one.
  1498. return (node);
  1499. }
  1500. template <typename T, typename DT>
  1501. typename DomainTree<T,DT>::Result
  1502. DomainTree<T,DT>::insert(util::MemorySegment& mem_sgmt,
  1503. const isc::dns::Name& target_name,
  1504. DomainTreeNode<T,DT>** new_node)
  1505. {
  1506. DomainTreeNode<T,DT>* parent = NULL;
  1507. DomainTreeNode<T,DT>* current = root_.get();
  1508. DomainTreeNode<T,DT>* up_node = NULL;
  1509. isc::dns::LabelSequence target_labels(target_name);
  1510. int order = -1;
  1511. while (current != NULL) {
  1512. const dns::LabelSequence current_labels(current->getLabels());
  1513. const isc::dns::NameComparisonResult compare_result =
  1514. target_labels.compare(current_labels);
  1515. const isc::dns::NameComparisonResult::NameRelation relation =
  1516. compare_result.getRelation();
  1517. if (relation == isc::dns::NameComparisonResult::EQUAL) {
  1518. if (new_node != NULL) {
  1519. *new_node = current;
  1520. }
  1521. return (ALREADYEXISTS);
  1522. } else if (relation == isc::dns::NameComparisonResult::NONE) {
  1523. parent = current;
  1524. order = compare_result.getOrder();
  1525. current = order < 0 ? current->getLeft() : current->getRight();
  1526. } else if (relation == isc::dns::NameComparisonResult::SUBDOMAIN) {
  1527. // insert sub domain to sub tree
  1528. parent = NULL;
  1529. up_node = current;
  1530. target_labels.stripRight(compare_result.getCommonLabels());
  1531. current = current->getDown();
  1532. } else {
  1533. // The number of labels in common is fewer than the number of
  1534. // labels at the current node, so the current node must be
  1535. // adjusted to have just the common suffix, and a down pointer
  1536. // made to a new tree.
  1537. dns::LabelSequence common_ancestor = target_labels;
  1538. common_ancestor.stripLeft(target_labels.getLabelCount() -
  1539. compare_result.getCommonLabels());
  1540. dns::LabelSequence new_prefix = current_labels;
  1541. new_prefix.stripRight(compare_result.getCommonLabels());
  1542. nodeFission(mem_sgmt, *current, new_prefix, common_ancestor);
  1543. }
  1544. }
  1545. typename DomainTreeNode<T,DT>::DomainTreeNodePtr* current_root =
  1546. (up_node != NULL) ? &(up_node->down_) : &root_;
  1547. // Once a new node is created, no exception will be thrown until the end
  1548. // of the function, so we can simply create and hold a new node pointer.
  1549. DomainTreeNode<T,DT>* node = DomainTreeNode<T,DT>::create(mem_sgmt,
  1550. target_labels);
  1551. node->parent_ = parent;
  1552. if (parent == NULL) {
  1553. *current_root = node;
  1554. // node is the new root of sub tree, so its init color is BLACK
  1555. node->setColor(DomainTreeNode<T,DT>::BLACK);
  1556. node->setSubTreeRoot(true);
  1557. node->parent_ = up_node;
  1558. } else if (order < 0) {
  1559. node->setSubTreeRoot(false);
  1560. parent->left_ = node;
  1561. } else {
  1562. node->setSubTreeRoot(false);
  1563. parent->right_ = node;
  1564. }
  1565. insertRebalance(current_root, node);
  1566. if (new_node != NULL) {
  1567. *new_node = node;
  1568. }
  1569. ++node_count_;
  1570. return (SUCCESS);
  1571. }
  1572. template <typename T, typename DT>
  1573. void
  1574. DomainTree<T,DT>::deleteAllNodes(util::MemorySegment& mem_sgmt) {
  1575. const DT deleter;
  1576. deleteHelper(mem_sgmt, root_.get(), deleter);
  1577. root_ = NULL;
  1578. }
  1579. // Note: when we redesign this (still keeping the basic concept), we should
  1580. // change this part so the newly created node will be used for the inserted
  1581. // name (and therefore the name for the existing node doesn't change).
  1582. // Otherwise, things like shortcut links between nodes won't work.
  1583. // See Trac #2054.
  1584. template <typename T, typename DT>
  1585. void
  1586. DomainTree<T,DT>::nodeFission(util::MemorySegment& mem_sgmt,
  1587. DomainTreeNode<T,DT>& node,
  1588. const isc::dns::LabelSequence& new_prefix,
  1589. const isc::dns::LabelSequence& new_suffix)
  1590. {
  1591. // Create and reset the labels.
  1592. // Once a new node is created, no exception will be thrown until
  1593. // the end of the function, and it will keep consistent behavior
  1594. // (i.e., a weak form of strong exception guarantee) even if code
  1595. // after the call to this function throws an exception.
  1596. DomainTreeNode<T,DT>* down_node = DomainTreeNode<T,DT>::create(mem_sgmt,
  1597. new_prefix);
  1598. node.resetLabels(new_suffix);
  1599. std::swap(node.data_, down_node->data_);
  1600. // Swap flags bitfields; yes, this is ugly (it appears we cannot use
  1601. // std::swap for bitfields). The right solution is to implement
  1602. // the above note regarding #2054, then we won't have to swap the
  1603. // flags in the first place.
  1604. const bool is_root = node.isSubTreeRoot();
  1605. const uint32_t tmp = node.flags_;
  1606. node.flags_ = down_node->flags_;
  1607. down_node->flags_ = tmp;
  1608. node.setSubTreeRoot(is_root);
  1609. down_node->down_ = node.getDown();
  1610. if (down_node->down_ != NULL) {
  1611. down_node->down_->parent_ = down_node;
  1612. }
  1613. node.down_ = down_node;
  1614. down_node->parent_ = &node;
  1615. // Restore the color of the node (may have gotten changed by the flags
  1616. // swap)
  1617. node.setColor(down_node->getColor());
  1618. // root node of sub tree, the initial color is BLACK
  1619. down_node->setColor(DomainTreeNode<T,DT>::BLACK);
  1620. // mark it as the root of a subtree
  1621. down_node->setSubTreeRoot(true);
  1622. ++node_count_;
  1623. }
  1624. template <typename T, typename DT>
  1625. void
  1626. DomainTree<T,DT>::insertRebalance
  1627. (typename DomainTreeNode<T,DT>::DomainTreeNodePtr* root,
  1628. DomainTreeNode<T,DT>* node)
  1629. {
  1630. DomainTreeNode<T,DT>* uncle;
  1631. DomainTreeNode<T,DT>* parent;
  1632. while (node != (*root).get() &&
  1633. ((parent = node->getParent())->getColor()) ==
  1634. DomainTreeNode<T,DT>::RED) {
  1635. // Here, node->parent_ is not NULL and it is also red, so
  1636. // node->parent_->parent_ is also not NULL.
  1637. if (parent == parent->getParent()->getLeft()) {
  1638. uncle = parent->getParent()->getRight();
  1639. if (uncle != NULL && uncle->getColor() ==
  1640. DomainTreeNode<T,DT>::RED) {
  1641. parent->setColor(DomainTreeNode<T,DT>::BLACK);
  1642. uncle->setColor(DomainTreeNode<T,DT>::BLACK);
  1643. parent->getParent()->setColor(DomainTreeNode<T,DT>::RED);
  1644. node = parent->getParent();
  1645. } else {
  1646. if (node == parent->getRight()) {
  1647. node = parent;
  1648. leftRotate(root, node);
  1649. parent = node->getParent();
  1650. }
  1651. parent->setColor(DomainTreeNode<T,DT>::BLACK);
  1652. parent->getParent()->setColor(DomainTreeNode<T,DT>::RED);
  1653. rightRotate(root, parent->getParent());
  1654. }
  1655. } else {
  1656. uncle = parent->getParent()->getLeft();
  1657. if (uncle != NULL && uncle->getColor() ==
  1658. DomainTreeNode<T,DT>::RED) {
  1659. parent->setColor(DomainTreeNode<T,DT>::BLACK);
  1660. uncle->setColor(DomainTreeNode<T,DT>::BLACK);
  1661. parent->getParent()->setColor(DomainTreeNode<T,DT>::RED);
  1662. node = parent->getParent();
  1663. } else {
  1664. if (node == parent->getLeft()) {
  1665. node = parent;
  1666. rightRotate(root, node);
  1667. parent = node->getParent();
  1668. }
  1669. parent->setColor(DomainTreeNode<T,DT>::BLACK);
  1670. parent->getParent()->setColor(DomainTreeNode<T,DT>::RED);
  1671. leftRotate(root, parent->getParent());
  1672. }
  1673. }
  1674. }
  1675. (*root)->setColor(DomainTreeNode<T,DT>::BLACK);
  1676. }
  1677. template <typename T, typename DT>
  1678. DomainTreeNode<T,DT>*
  1679. DomainTree<T,DT>::leftRotate
  1680. (typename DomainTreeNode<T,DT>::DomainTreeNodePtr* root,
  1681. DomainTreeNode<T,DT>* node)
  1682. {
  1683. DomainTreeNode<T,DT>* const right = node->getRight();
  1684. DomainTreeNode<T,DT>* const rleft = right->getLeft();
  1685. node->right_ = rleft;
  1686. if (rleft != NULL) {
  1687. rleft->parent_ = node;
  1688. }
  1689. DomainTreeNode<T,DT>* const parent = node->getParent();
  1690. right->parent_ = parent;
  1691. if (!node->isSubTreeRoot()) {
  1692. right->setSubTreeRoot(false);
  1693. if (node == parent->getLeft()) {
  1694. parent->left_ = right;
  1695. } else {
  1696. parent->right_ = right;
  1697. }
  1698. } else {
  1699. right->setSubTreeRoot(true);
  1700. *root = right;
  1701. }
  1702. right->left_ = node;
  1703. node->parent_ = right;
  1704. node->setSubTreeRoot(false);
  1705. return (node);
  1706. }
  1707. template <typename T, typename DT>
  1708. DomainTreeNode<T,DT>*
  1709. DomainTree<T,DT>::rightRotate
  1710. (typename DomainTreeNode<T,DT>::DomainTreeNodePtr* root,
  1711. DomainTreeNode<T,DT>* node)
  1712. {
  1713. DomainTreeNode<T,DT>* const left = node->getLeft();
  1714. DomainTreeNode<T,DT>* const lright = left->getRight();
  1715. node->left_ = lright;
  1716. if (lright != NULL) {
  1717. lright->parent_ = node;
  1718. }
  1719. DomainTreeNode<T,DT>* const parent = node->getParent();
  1720. left->parent_ = parent;
  1721. if (!node->isSubTreeRoot()) {
  1722. left->setSubTreeRoot(false);
  1723. if (node == parent->getRight()) {
  1724. parent->right_ = left;
  1725. } else {
  1726. parent->left_ = left;
  1727. }
  1728. } else {
  1729. left->setSubTreeRoot(true);
  1730. *root = left;
  1731. }
  1732. left->right_ = node;
  1733. node->parent_ = left;
  1734. node->setSubTreeRoot(false);
  1735. return (node);
  1736. }
  1737. template <typename T, typename DT>
  1738. void
  1739. DomainTree<T,DT>::dumpTree(std::ostream& os, unsigned int depth) const {
  1740. indent(os, depth);
  1741. os << "tree has " << node_count_ << " node(s)\n";
  1742. dumpTreeHelper(os, root_.get(), depth);
  1743. }
  1744. template <typename T, typename DT>
  1745. void
  1746. DomainTree<T,DT>::dumpTreeHelper(std::ostream& os,
  1747. const DomainTreeNode<T,DT>* node,
  1748. unsigned int depth) const
  1749. {
  1750. if (node == NULL) {
  1751. indent(os, depth);
  1752. os << "NULL\n";
  1753. return;
  1754. }
  1755. indent(os, depth);
  1756. os << node->getLabels() << " ("
  1757. << ((node->getColor() == DomainTreeNode<T,DT>::BLACK) ? "black" : "red")
  1758. << ")";
  1759. if (node->isEmpty()) {
  1760. os << " [invisible]";
  1761. }
  1762. if (node->isSubTreeRoot()) {
  1763. os << " [subtreeroot]";
  1764. }
  1765. os << "\n";
  1766. const DomainTreeNode<T,DT>* down = node->getDown();
  1767. if (down != NULL) {
  1768. indent(os, depth + 1);
  1769. os << "begin down from " << node->getLabels() << "\n";
  1770. dumpTreeHelper(os, down, depth + 1);
  1771. indent(os, depth + 1);
  1772. os << "end down from " << node->getLabels() << "\n";
  1773. }
  1774. dumpTreeHelper(os, node->getLeft(), depth + 1);
  1775. dumpTreeHelper(os, node->getRight(), depth + 1);
  1776. }
  1777. template <typename T, typename DT>
  1778. void
  1779. DomainTree<T,DT>::indent(std::ostream& os, unsigned int depth) {
  1780. static const unsigned int INDENT_FOR_EACH_DEPTH = 5;
  1781. os << std::string(depth * INDENT_FOR_EACH_DEPTH, ' ');
  1782. }
  1783. template <typename T, typename DT>
  1784. void
  1785. DomainTree<T,DT>::dumpDot(std::ostream& os, bool show_pointers) const {
  1786. int nodecount = 0;
  1787. os << "digraph g {\n";
  1788. os << "node [shape = record,height=.1];\n";
  1789. dumpDotHelper(os, root_.get(), &nodecount, show_pointers);
  1790. os << "}\n";
  1791. }
  1792. template <typename T, typename DT>
  1793. int
  1794. DomainTree<T,DT>::dumpDotHelper(std::ostream& os,
  1795. const DomainTreeNode<T,DT>* node,
  1796. int* nodecount, bool show_pointers) const
  1797. {
  1798. if (node == NULL) {
  1799. return 0;
  1800. }
  1801. int l = dumpDotHelper(os, node->getLeft(), nodecount, show_pointers);
  1802. int r = dumpDotHelper(os, node->getRight(), nodecount, show_pointers);
  1803. int d = dumpDotHelper(os, node->getDown(), nodecount, show_pointers);
  1804. *nodecount += 1;
  1805. os << "node" << *nodecount <<
  1806. "[label = \"<f0> |<f1> " << node->getLabels() <<
  1807. "|<f2>";
  1808. if (show_pointers) {
  1809. os << "|<f3> n=" << node << "|<f4> p=" << node->getParent();
  1810. }
  1811. os << "\"] [";
  1812. if (node->getColor() == DomainTreeNode<T,DT>::RED) {
  1813. os << "color=red";
  1814. } else {
  1815. os << "color=black";
  1816. }
  1817. if (node->isSubTreeRoot()) {
  1818. os << ",penwidth=3";
  1819. }
  1820. if (node->isEmpty()) {
  1821. os << ",style=filled,fillcolor=lightgrey";
  1822. }
  1823. os << "];\n";
  1824. if (node->getLeft() != NULL) {
  1825. os << "\"node" << *nodecount << "\":f0 -> \"node" << l << "\":f1;\n";
  1826. }
  1827. if (node->getDown() != NULL) {
  1828. os << "\"node" << *nodecount << "\":f1 -> \"node" << d <<
  1829. "\":f1 [penwidth=5];\n";
  1830. }
  1831. if (node->getRight() != NULL) {
  1832. os << "\"node" << *nodecount << "\":f2 -> \"node" << r << "\":f1;\n";
  1833. }
  1834. return (*nodecount);
  1835. }
  1836. } // namespace memory
  1837. } // namespace datasrc
  1838. } // namespace isc
  1839. #endif // _DOMAINTREE_H
  1840. // Local Variables:
  1841. // mode: c++
  1842. // End: