xmldata-modelingietf-netmod-yang

How to implement recursion in YANG model using leafref?


I have the following XML that I want to model with YANG. The XML contains a list of nodes and each node contains a list of neighbor nodes.

<nodes>
  <node>
    <id>1</id>
    <node>
      <id>2</id>
    </node>
  </node>
  <node>
    <id>3</id>
    <node>
      <id>4</id>
    </node>
  </node>
</nodes>

Please find below the YANG model I tried to create. Unfortunately, Yang does not support circular references in grouping.

grouping node {
  list node {
    leaf id {
      type int32;
    }
    uses node;
  }
}

container nodes {
   uses node;
}

I saw in draft-ietf-netmod-routing-cfg-16 and on ietf mail archive that a way to emulate recursion is to use leafref. How can the above xml be modeled with grouping and leafref?


Solution

  • As you said, recursion using groupings is not supported. The simplest approach would be to have a flat list of nodes, where each node has a parent node, referenced as a leafref. Something like:

    container nodes {
      list node {
        key id;
        leaf id { type int32; }
        leaf parent-id {
          type leafref {
            path "../../node/id";
          }
        }
      }
    }
    

    The equivalent XML would be:

    <nodes>
      <node>
        <id>1</id>
      <node>
      <node>
        <id>2</id>
        <parent-id>1</parent-id>
      </node>
      <node>
        <id>3</id>
      <node>
      <node>
        <id>4</id>
        <parent-id>3</parent-id>
      </node>
    </nodes>
    

    You could do the opposite, where a node refers its children (via a leafref leaf-list) instead of its parents.


    Of course, using the same data node directly recursively does work:

    container nodes {
      list node {
        key id;
        leaf id { type int32; }
    
        list node {
          key id;
          leaf id { type int32; }
    
          list node {
            key id;
            leaf id { type int32; }
    
            // and so on
          }
        }
      }
    }
    

    but this does not allow indefinitely deep hierarchies. I would avoid this pattern, though, not a clean model design.